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.

fix(video): isolate plugin cleanup and stream ownership per app

yhhc24d055324ac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 256697e2b..c0f104d73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **Video plugin cleanup releases only the selected App.** Shared plugin instances retain separate video backends and stream maps for each App, so closing a preview cannot stop another App's video or leave its own backend behind. Cleanup detaches the world subscription and disables its old update system. Stopping component streams also retires them from the video service instead of pumping stopped handles.
+
- **Video components switch streams when their source changes.** Changing a live component's source releases its previous stream and opens the new source. Unchanged sources keep their stream across frames; clearing the source or removing the entity still releases the current stream.
- **WASM video exports fail when required transcoding fails.** An unavailable or failed video converter no longer stages an original MP4 that the target's WASM decoder cannot play. The cook reports the failed asset, and mini-game exports propagate asset cooking failures as build errors instead of reporting a usable package.
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2cb6d234c..b97dc3af8 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -9642,7 +9642,7 @@ ResourceDef<VideoAPI>
## VideoPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
stopAll: () => void
static new (): VideoPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 90e49c91d..64faa5d72 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -9846,7 +9846,7 @@ ResourceDef<VideoAPI>
## VideoPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
stopAll: () => void
static new (): VideoPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 9b1fe932b..50e772d56 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -9637,7 +9637,7 @@ ResourceDef<VideoAPI>
## VideoPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
stopAll: () => void
static new (): VideoPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 99174b370..9af477fc1 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -9916,7 +9916,7 @@ ResourceDef<VideoAPI>
## VideoPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
stopAll: () => void
static new (): VideoPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 4bb2f86ec..bee310953 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -9644,7 +9644,7 @@ ResourceDef<VideoAPI>
## VideoPlugin — class @experimental
```
build: (app: App) => void
-cleanup: () => void
+cleanup: (app?: App) => void
name: string
stopAll: () => void
static new (): VideoPlugin
diff --git a/sdk/src/video/VideoPlugin.ts b/sdk/src/video/VideoPlugin.ts
index aca903f59..b9b6c6cbf 100644
--- a/sdk/src/video/VideoPlugin.ts
+++ b/sdk/src/video/VideoPlugin.ts
@@ -59,12 +59,20 @@ function driveRenderable(world: World, entity: Entity, handle: VideoStreamHandle
return false;
}
+interface VideoPluginState {
+ video: VideoAPI;
+ handles: Map<number, VideoStreamHandle>;
+ offDespawn: () => void;
+ released: boolean;
+}
+
export class VideoPlugin implements Plugin {
name = 'video';
- private video_: VideoAPI | null = null;
- private handles_: Map<number, VideoStreamHandle> | null = null;
+ private readonly states_ = new WeakMap<App, VideoPluginState>();
+ private latestState_: VideoPluginState | null = null;
build(app: App): void {
+ this.cleanup(app);
// createVideoBackend is optional; fall back to the silent Null backend.
// The context's getters are lazy so the wasm backend resolves the
// side-module host / audio service per stream (they may attach to the
@@ -76,16 +84,14 @@ export class VideoPlugin implements Plugin {
},
}) ?? new NullVideoBackend();
const video = new VideoAPI(backend);
- this.video_ = video;
app.insertResource(VideoPlayer, video);
const handles = new Map<number, VideoStreamHandle>();
const sources = new WeakMap<VideoStreamHandle, string>();
- this.handles_ = handles;
const warnedNoSprite = new Set<number>();
const live = new Set<number>();
- app.world.onDespawn((entity: Entity) => {
+ const offDespawn = app.world.onDespawn((entity: Entity) => {
const handle = handles.get(entity as number);
if (handle) {
video.stop(handle);
@@ -93,13 +99,16 @@ export class VideoPlugin implements Plugin {
}
warnedNoSprite.delete(entity as number);
});
+ const state: VideoPluginState = { video, handles, offDespawn, released: false };
+ this.states_.set(app, state);
+ this.latestState_ = state;
app.addSystemToSchedule(
Schedule.Update,
defineSystem(
[Res(Time), Res(VideoPlayer)],
(_time: TimeData, videoAPI: VideoAPI) => {
- if (isEditor() && !isPlayMode()) return;
+ if (state.released || (isEditor() && !isPlayMode())) return;
const world = app.world;
// Null on a native core: the frame upload goes through the
// ResourceManager's byte path instead of a wasm heap.
@@ -158,16 +167,21 @@ export class VideoPlugin implements Plugin {
}
stopAll(): void {
- if (this.handles_) {
- for (const handle of this.handles_.values()) handle.stop();
- this.handles_.clear();
- }
+ const state = this.latestState_;
+ if (!state || state.released) return;
+ for (const handle of state.handles.values()) state.video.stop(handle);
+ state.handles.clear();
}
- cleanup(): void {
- this.stopAll();
- this.video_?.dispose();
- this.video_ = null;
+ cleanup(app?: App): void {
+ const state = app ? this.states_.get(app) : this.latestState_;
+ if (!state || state.released) return;
+ state.released = true;
+ if (app) this.states_.delete(app);
+ if (state === this.latestState_) this.latestState_ = null;
+ state.offDespawn();
+ state.handles.clear();
+ state.video.dispose();
}
}
diff --git a/sdk/tests/video-plugin-lifecycle.test.ts b/sdk/tests/video-plugin-lifecycle.test.ts
new file mode 100644
index 000000000..b755bfbdf
--- /dev/null
+++ b/sdk/tests/video-plugin-lifecycle.test.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { afterEach, expect, it, vi } from 'vitest';
+import { App } from '../src/app/app';
+import { VideoPlugin } from '../src/video/VideoPlugin';
+import { VideoPlayer } from '../src/video/VideoAPI';
+import { Video } from '../src/video/VideoComponents';
+import { NullVideoBackend } from '../src/video/NullVideoBackend';
+
+const { backends } = vi.hoisted(() => ({ backends: [] as NullVideoBackend[] }));
+vi.mock('../src/platform/base', async original => ({
+ ...await original<typeof import('../src/platform/base')>(),
+ getPlatform: () => ({ createVideoBackend: () => {
+ const backend = new NullVideoBackend(); vi.spyOn(backend, 'dispose');
+ vi.spyOn(backend, 'createStream').mockImplementation((_url, options) => {
+ const handle = new NullVideoBackend().createStream('', options);
+ vi.spyOn(handle, 'stop'); vi.spyOn(handle, 'pump'); return handle;
+ });
+ backends.push(backend); return backend;
+ } }),
+}));
+const apps: App[] = [];
+function build(plugin: VideoPlugin) { const app = App.new(); apps.push(app); app.addPlugin(plugin); return app; }
+afterEach(() => { for (const app of apps.splice(0)) app.quit(); backends.length = 0; });
+
+it('quitting an older app releases its video backend and preserves the newer app', () => {
+ const plugin = new VideoPlugin(), first = build(plugin), second = build(plugin);
+ const a = first.getResource(VideoPlayer).play('first.mp4'), b = second.getResource(VideoPlayer).play('second.mp4');
+ first.quit();
+ expect(backends[0].dispose).toHaveBeenCalledOnce();
+ expect(backends[1].dispose).not.toHaveBeenCalled();
+ expect(a.stop).toHaveBeenCalledOnce(); expect(b.stop).not.toHaveBeenCalled();
+ second.quit(); expect(backends[1].dispose).toHaveBeenCalledOnce();
+});
+
+it('releases 100 preview backends without stopping the main app video', () => {
+ const plugin = new VideoPlugin(), main = build(plugin);
+ const handle = main.getResource(VideoPlayer).play('main.mp4');
+ for (let i = 0; i < 100; i++) { const preview = build(plugin); preview.quit(); }
+ expect(handle.stop).not.toHaveBeenCalled();
+ expect(backends[0].dispose).not.toHaveBeenCalled();
+ for (const backend of backends.slice(1)) expect(backend.dispose).toHaveBeenCalledOnce();
+ main.quit(); expect(handle.stop).toHaveBeenCalledOnce();
+});
+
+it('stopAll retires component handles from the video service, once', async () => {
+ const plugin = new VideoPlugin(), app = build(plugin), api = app.getResource(VideoPlayer);
+ const entity = app.world.spawn(); app.world.insert(entity, Video, { source: 'a.mp4' });
+ await app.tick(1 / 60);
+ const handle = vi.mocked(backends[0].createStream).mock.results[0].value;
+ plugin.stopAll(); plugin.stopAll();
+ const pumps = vi.mocked(handle.pump).mock.calls.length;
+ api.update(null);
+ expect(handle.stop).toHaveBeenCalledOnce(); expect(handle.pump).toHaveBeenCalledTimes(pumps);
+ app.quit(); expect(handle.stop).toHaveBeenCalledOnce();
+});
+
+it('parameterless cleanup releases only the latest app and remains idempotent', () => {
+ const plugin = new VideoPlugin(), first = build(plugin); build(plugin);
+ plugin.cleanup(); plugin.cleanup();
+ expect(backends[0].dispose).not.toHaveBeenCalled();
+ expect(backends[1].dispose).toHaveBeenCalledOnce();
+ first.quit(); expect(backends[0].dispose).toHaveBeenCalledOnce();
+});
+
+it('cleanup detaches the world subscription and prevents an old system from starting streams', async () => {
+ const app = App.new(); apps.push(app);
+ const subscribe = app.world.onDespawn.bind(app.world);
+ const off = vi.fn();
+ vi.spyOn(app.world, 'onDespawn').mockImplementation(callback => {
+ const unsubscribe = subscribe(callback);
+ return () => { off(); unsubscribe(); };
+ });
+ const plugin = new VideoPlugin(); app.addPlugin(plugin);
+ plugin.cleanup(app);
+ const entity = app.world.spawn(); app.world.insert(entity, Video, { source: 'late.mp4' });
+ await app.tick(1 / 60);
+ expect(off).toHaveBeenCalledOnce(); expect(backends[0].createStream).not.toHaveBeenCalled();
+ app.quit(); expect(backends[0].dispose).toHaveBeenCalledOnce();
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 935bf0018..911612ce7 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(video): isolate plugin cleanup and stream ownership per app':
+ { note: 'Video plugin cleanup releases only the selected App.' },
'fix(video): replace live streams when component sources change':
{ note: 'Video components switch streams when their source changes.' },
'fix(export): reject failed video transcoding for wasm targets':