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): harden the pipeline per self-review — slot leak, start race, muted cost, CA audio identity

esengineb0aa6053bf7a
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 099abafca..4c9c399b7 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -373,7 +373,14 @@ export async function cookAssets(
continue;
}
try {
- let data: Uint8Array = await readFile(path.join(root, entry.path));
+ // Videos headed for transcode skip the eager read: ffmpeg streams the
+ // file itself, so slurping a (potentially huge) source here would double
+ // the I/O just to throw the bytes away.
+ const willTranscodeVideo =
+ videoEnc != null && entry.type === 'video' && path.extname(entry.path).toLowerCase() !== '.esv';
+ let data: Uint8Array = willTranscodeVideo
+ ? new Uint8Array(0)
+ : await readFile(path.join(root, entry.path));
let ext = path.extname(entry.path);
let compressedFormats: string[] | undefined;
// Encode raster textures (PNG) to GPU-compressed KTX2 — they stay compressed
@@ -401,7 +408,7 @@ export async function cookAssets(
// Video → `.esv` (MPEG-1 for the wasm decoder) + audio-track sibling.
// `.esv` sources are already in the cooked format and pass through.
let videoAudio: Uint8Array | null = null;
- if (videoEnc && entry.type === 'video' && ext.toLowerCase() !== '.esv') {
+ if (willTranscodeVideo && videoEnc) {
const settings = videoEnc.videoImportSettings(entry.importer);
const res = await videoEnc.transcodeVideoForWasm(path.join(root, entry.path), settings);
warnings.push(...res.warnings.map((w) => `${entry.path}: ${w}`));
@@ -410,6 +417,7 @@ export async function cookAssets(
ext = '.esv';
videoAudio = res.audio;
} else {
+ data = await readFile(path.join(root, entry.path));
warnings.push(`${entry.path}: shipped untranscoded — this video will NOT play on the wasm decode path (WeChat)`);
}
}
@@ -472,13 +480,17 @@ export async function cookAssets(
group,
...(compressedFormats ? { compressedFormats } : {}),
});
- // The video's audio track ships as an `<staged>.m4a` SIBLING of the
- // `.esv` — appended (not extension-swapped) so it can never collide with
- // a real project `.m4a`, and the runtime derives it from the resolved
- // video URL with no metadata channel. Its own manifest entry keeps
- // addressable/CDN flows aware of the file.
+ // The video's audio track ships as its own manifest entry addressed as
+ // `<source path>.m4a` / uuid `<video uuid>-audio` — the runtime resolves
+ // it through the same ref channel as everything else. The flat layout
+ // also keeps the `<staged>.m4a` sibling NAME (appended, not
+ // extension-swapped, so it can't collide with a real `.m4a` asset) as a
+ // resolver-free fallback; content addressing names it by ITS OWN bytes —
+ // two videos with identical footage but different audio must not dedup
+ // to one soundtrack.
if (videoAudio) {
- const audioOutRel = `${outRel}.m4a`;
+ const audioHash = contentHashHex(videoAudio);
+ const audioOutRel = useCA ? `${caBase}/${audioHash}.m4a` : `${outRel}.m4a`;
if (!staged.has(audioOutRel)) {
await writeFile(path.join(absOut, audioOutRel), videoAudio);
staged.add(audioOutRel);
@@ -488,7 +500,7 @@ export async function cookAssets(
path: audioOutRel,
sourcePath: `${entry.path}.m4a`,
type: 'audio',
- contentHash: contentHashHex(videoAudio),
+ contentHash: audioHash,
size: videoAudio.byteLength,
group,
});
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index 08e123bb2..3fca34d71 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -159,6 +159,9 @@ async function scanWeChatSideModules(
const ids = new Set<string>();
if (sceneDatas.some((s) => s && sceneUsesPhysics(s as Parameters<typeof sceneUsesPhysics>[0]))) ids.add('physics');
if (sceneDatas.some((s) => s && sceneUsesVideo(s as Parameters<typeof sceneUsesVideo>[0]))) ids.add('videodec');
+ // Any staged .esv also needs the decoder: script-driven playback
+ // (VideoPlayer.play) references cooked videos no scene component names.
+ if (cookEntries.some((e) => /\.esv(\.bin)?$/.test(e.path.toLowerCase()))) ids.add('videodec');
// Spine: the skeleton carries the version. Skeleton + atlas share the authored
// meta type `spine`, so discriminate by extension — `.skel` is a binary
// skeleton, `.json` a JSON one; the `.atlas` sibling is not a skeleton.
diff --git a/desktop/electron/videoCook.ts b/desktop/electron/videoCook.ts
index 4554f37b0..828f961fd 100644
--- a/desktop/electron/videoCook.ts
+++ b/desktop/electron/videoCook.ts
@@ -86,30 +86,34 @@ export async function transcodeVideoForWasm(
const tmp = await mkdtemp(path.join(tmpdir(), 'estella-video-'));
try {
const esvPath = path.join(tmp, 'out.esv');
+ const m4aPath = path.join(tmp, 'out.m4a');
const videoArgs = (extraFilter: string) => [
'-y', '-i', srcAbs, '-an',
'-c:v', 'mpeg1video', '-q:v', String(settings.quality),
'-vf', extraFilter ? `${EVEN_SCALE},${extraFilter}` : EVEN_SCALE,
'-f', 'mpeg', esvPath,
];
- let res = await run(ffmpeg, videoArgs(''));
- if (res.code !== 0 && /fps|frame ?rate/i.test(res.stderr)) {
- // Source frame rate is outside MPEG-1's table (or variable) — resample.
- res = await run(ffmpeg, videoArgs('fps=30'));
- }
+ // The two passes are independent (-an vs -vn, separate outputs) — overlap them.
+ const [res, audioRes] = await Promise.all([
+ (async () => {
+ const first = await run(ffmpeg, videoArgs(''));
+ if (first.code === 0 || !/fps|frame ?rate/i.test(first.stderr)) return first;
+ // Source frame rate is outside MPEG-1's table (or variable) — resample.
+ return run(ffmpeg, videoArgs('fps=30'));
+ })(),
+ run(ffmpeg, [
+ '-y', '-i', srcAbs, '-vn',
+ '-c:a', 'aac', '-b:a', `${settings.audioBitrateKbps}k`,
+ '-f', 'ipod', m4aPath,
+ ]),
+ ]);
+
let esv: Uint8Array | null = null;
if (res.code === 0) {
esv = new Uint8Array(await readFile(esvPath));
} else {
warnings.push(`video transcode failed: ${lastLine(res.stderr)}`);
}
-
- const m4aPath = path.join(tmp, 'out.m4a');
- const audioRes = await run(ffmpeg, [
- '-y', '-i', srcAbs, '-vn',
- '-c:a', 'aac', '-b:a', `${settings.audioBitrateKbps}k`,
- '-f', 'ipod', m4aPath,
- ]);
let audio: Uint8Array | null = null;
if (audioRes.code === 0) {
audio = new Uint8Array(await readFile(m4aPath));
diff --git a/desktop/tests/video-asset.test.ts b/desktop/tests/video-asset.test.ts
index 4e65e6db6..ef6fb406e 100644
--- a/desktop/tests/video-asset.test.ts
+++ b/desktop/tests/video-asset.test.ts
@@ -28,8 +28,11 @@ describe('video asset type', () => {
expect(metaTypeFor('sound.webm')).toBe('audio');
});
- it('exposes video import settings (playback defaults)', () => {
+ it('exposes video import settings (playback defaults + cook fields)', () => {
expect(hasImporterSettings('video')).toBe(true);
- expect(importerDefaults('video')).toEqual({ loop: true, autoplay: true, muted: true });
+ expect(importerDefaults('video')).toEqual({
+ loop: true, autoplay: true, muted: true,
+ quality: 4, audioBitrateKbps: 128,
+ });
});
});
diff --git a/desktop/tests/video-cook.test.ts b/desktop/tests/video-cook.test.ts
index 488953dce..39274c847 100644
--- a/desktop/tests/video-cook.test.ts
+++ b/desktop/tests/video-cook.test.ts
@@ -156,4 +156,22 @@ describe.skipIf(!ffmpeg)('cookAssets video wiring', () => {
expect(video.path).toBe('assets/videos/clip.mp4');
expect(manifest.entries.find((e: { uuid: string }) => e.uuid === `${VIDEO_UUID}-audio`)).toBeUndefined();
});
+
+ it('content-addressed staging names the audio sibling by ITS OWN hash', async () => {
+ const root = await makeProject();
+ await cookAssets(root, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build',
+ transcodeVideo: true, contentAddressed: true,
+ });
+ const manifest = JSON.parse(readFileSync(path.join(root, 'build/assets.manifest.json'), 'utf8'));
+ const video = manifest.entries.find((e: { uuid: string }) => e.uuid === VIDEO_UUID);
+ const audio = manifest.entries.find((e: { uuid: string }) => e.uuid === `${VIDEO_UUID}-audio`);
+ expect(video.path).toMatch(/^assets\/[0-9a-f]{16}\.esv$/);
+ expect(audio.path).toMatch(/^assets\/[0-9a-f]{16}\.m4a$/);
+ // Named by the AUDIO bytes, not the video's — different soundtracks over
+ // identical footage must not dedup to one file.
+ expect(audio.path).toBe(`assets/${audio.contentHash}.m4a`);
+ expect(audio.contentHash).not.toBe(video.contentHash);
+ expect(existsSync(path.join(root, 'build', audio.path))).toBe(true);
+ });
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d47bac42a..7162b4af8 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -7055,6 +7055,7 @@ width: number
## VideoStreamOptions — interface
```
+audioTrackUrl: string | undefined
autoplay: boolean | undefined
loop: boolean | undefined
muted: boolean | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fc5c6aaf1..6125834f8 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -7050,6 +7050,7 @@ width: number
## VideoStreamOptions — interface
```
+audioTrackUrl: string | undefined
autoplay: boolean | undefined
loop: boolean | undefined
muted: boolean | undefined
diff --git a/sdk/src/audio/Audio.ts b/sdk/src/audio/Audio.ts
index b965237a8..b4165e106 100644
--- a/sdk/src/audio/Audio.ts
+++ b/sdk/src/audio/Audio.ts
@@ -217,6 +217,14 @@ export class AudioAPI {
return `${this.baseUrl}/${url}`;
}
+ /** Load `url`'s buffer into the residency cache unless already there. The
+ * double `has()` check absorbs a concurrent load racing to insert first. */
+ private async ensureBuffer_(url: string, load: () => Promise<AudioBufferHandle>): Promise<void> {
+ if (this.bufferCache_.has(url)) return;
+ const buffer = await load();
+ if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
+ }
+
async preload(url: string): Promise<void> {
if (this.bufferCache_.has(url)) return;
if (this.assetResolver_) {
@@ -225,8 +233,7 @@ export class AudioAPI {
return this.preloadFromData(url, data);
}
}
- const buffer = await this.backend_.loadBuffer(this.resolveUrl_(url));
- if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
+ await this.ensureBuffer_(url, () => this.backend_.loadBuffer(this.resolveUrl_(url)));
}
async preloadAll(urls: string[]): Promise<void> {
@@ -234,9 +241,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);
- if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
+ await this.ensureBuffer_(url, () => this.backend_.loadBufferFromData(url, data));
}
/**
@@ -249,10 +254,7 @@ export class AudioAPI {
async playTrack(url: string, config: PlayConfig = {}): Promise<AudioHandle | null> {
if (this.disposed_) return null;
try {
- if (!this.bufferCache_.has(url)) {
- const buffer = await this.backend_.loadBuffer(url);
- if (!this.bufferCache_.has(url)) this.insertEntry_(url, buffer);
- }
+ await this.ensureBuffer_(url, () => this.backend_.loadBuffer(url));
} catch {
return null;
}
diff --git a/sdk/src/audio/WeChatAudioBackend.ts b/sdk/src/audio/WeChatAudioBackend.ts
index c1c74b301..f0a3e78e9 100644
--- a/sdk/src/audio/WeChatAudioBackend.ts
+++ b/sdk/src/audio/WeChatAudioBackend.ts
@@ -3,6 +3,7 @@
/// <reference types="minigame-api-typings" />
import type { AudioHandle, AudioBufferHandle, PlayConfig, PlatformAudioBackend, AudioBackendInitOptions } from './PlatformAudioBackend';
import type { AudioMixer } from './AudioMixer';
+import { scalar } from '../math/scalar';
import { log } from '../logger';
class WeChatAudioHandle implements AudioHandle {
@@ -33,7 +34,9 @@ class WeChatAudioHandle implements AudioHandle {
}
setVolume(volume: number): void {
- this.ctx_.volume = volume;
+ // InnerAudioContext.volume is only valid in [0,1] — out-of-range writes
+ // are rejected on-device rather than clamped.
+ this.ctx_.volume = scalar.clamp01(volume);
}
private panWarned_ = false;
@@ -111,7 +114,7 @@ export class WeChatAudioBackend implements PlatformAudioBackend {
const ctx: WechatMinigame.InnerAudioContext = wx.createInnerAudioContext();
ctx.loop = config.loop ?? false;
- ctx.volume = config.volume ?? 1.0;
+ ctx.volume = scalar.clamp01(config.volume ?? 1.0);
ctx.playbackRate = config.playbackRate ?? 1.0;
ctx.startTime = config.startOffset ?? 0;
ctx.obeyMuteSwitch = false;
diff --git a/sdk/src/video/PlatformVideoBackend.ts b/sdk/src/video/PlatformVideoBackend.ts
index 82f7f2d5c..fe918b56e 100644
--- a/sdk/src/video/PlatformVideoBackend.ts
+++ b/sdk/src/video/PlatformVideoBackend.ts
@@ -39,6 +39,11 @@ export interface VideoStreamOptions {
muted?: boolean;
volume?: number;
playbackRate?: number;
+ /** Resolved URL of the cook-demuxed audio-track sibling, when the realm's
+ * manifest knows one (content-addressed staging renames files, so it can't
+ * be derived from the video URL). Backends without out-of-band audio
+ * (HTMLVideoElement) ignore it. */
+ audioTrackUrl?: string;
}
export interface PlatformVideoBackend {
diff --git a/sdk/src/video/VideoAPI.ts b/sdk/src/video/VideoAPI.ts
index d73e91e57..c538fb362 100644
--- a/sdk/src/video/VideoAPI.ts
+++ b/sdk/src/video/VideoAPI.ts
@@ -5,6 +5,7 @@
import type { ESEngineModule } from '../wasm';
import type { PlatformVideoBackend, VideoStreamHandle, VideoStreamOptions } from './PlatformVideoBackend';
import { defineResource } from '../resource';
+import { log } from '../logger';
export type VideoHandle = VideoStreamHandle;
export type VideoPlayOptions = VideoStreamOptions;
@@ -35,14 +36,41 @@ export class VideoAPI {
}
play(source: string, options: VideoPlayOptions = {}): VideoStreamHandle {
- const handle = this.backend_.createStream(this.resolveUrl_(source), options);
+ const handle = this.backend_.createStream(this.resolveUrl_(source), {
+ ...options,
+ audioTrackUrl: options.audioTrackUrl ?? this.resolveAudioTrack_(source),
+ });
this.handles_.add(handle);
return handle;
}
+ /**
+ * Resolve the cook-demuxed audio-track sibling through the realm's ref
+ * resolver: the cook registers it as `<source path>.m4a` (path refs) or
+ * `<uuid>-audio` (uuid refs). A resolver miss returns the ref unchanged —
+ * treated as "no cooked sibling" so backends fall back to URL derivation.
+ */
+ private resolveAudioTrack_(source: string): string | undefined {
+ if (!this.refResolver_) return undefined;
+ const siblingRef = source.startsWith('@uuid:') ? `${source}-audio` : `${source}.m4a`;
+ const resolved = this.refResolver_(siblingRef);
+ return resolved !== siblingRef ? resolved : undefined;
+ }
+
update(module: ESEngineModule): void {
if (this.disposed_) return;
- for (const handle of this.handles_) handle.pump(module);
+ for (const handle of this.handles_) {
+ // One stream's decode failure (wasm abort, detached heap) must not
+ // stall every other video this tick.
+ try {
+ handle.pump(module);
+ } catch (err) {
+ log.error('video', `pump failed for stream #${handle.id} — stopping it`, err);
+ this.handles_.delete(handle);
+ try { handle.stop(); } catch { /* already broken */ }
+ handle.onError?.(err);
+ }
+ }
}
stop(handle: VideoStreamHandle): void {
diff --git a/sdk/src/video/WasmVideoBackend.ts b/sdk/src/video/WasmVideoBackend.ts
index 73a920f2b..0d02864ee 100644
--- a/sdk/src/video/WasmVideoBackend.ts
+++ b/sdk/src/video/WasmVideoBackend.ts
@@ -1,17 +1,23 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-// The engine-owned software video backend: the `videodec` side module (pl_mpeg)
-// decodes MPEG-1 (.esv/.mpg) to RGBA, uploaded through the same pathless texture
-// pump as every other backend. Runs wherever the engine's wasm runs — the
-// guaranteed path on platforms without a reliable native decoder (WeChat, headless)
-// — and owns the clock, so seek/currentTime/duration/rate all work uniformly.
-//
-// Audio: the cook demuxes the source's audio track into an `<staged>.m4a`
-// sibling played through the audio pipeline (bus-routed, so mixer/ducking
-// apply). When a track exists, IT is the clock — the video decodes toward the
-// track's playhead — since audio glitches are far more audible than a video
-// frame arriving late. Without a track (or when it ends first), the engine
-// wall clock drives.
+/**
+ * @file WasmVideoBackend.ts
+ * @brief The engine-owned software video backend (videodec side module).
+ *
+ * @details pl_mpeg decodes MPEG-1 (.esv/.mpg) to RGBA, uploaded through the same
+ * pathless texture pump as every other backend. Runs wherever the
+ * engine's wasm runs — the guaranteed path on platforms without a
+ * reliable native decoder (WeChat, headless) — and owns the clock, so
+ * seek/currentTime/duration/rate all work uniformly.
+ *
+ * Audio: the cook demuxes the source's audio track into an `.m4a`
+ * sibling played through the audio pipeline (bus-routed, so
+ * mixer/ducking apply). When a track exists and the stream is audible,
+ * IT is the clock — the video decodes toward the track's playhead —
+ * since audio glitches are far more audible than a video frame
+ * arriving late. Muted streams, silent videos, and a track that ends
+ * before the last frame all drive on the engine wall clock instead.
+ */
import type { ESEngineModule } from '../wasm';
import type { PlatformVideoBackend, VideoBackendContext, VideoStreamHandle, VideoStreamOptions } from './PlatformVideoBackend';
import type { SideModule } from '../sideModules/host';
@@ -60,12 +66,18 @@ const MAX_PUMP_DT = 0.25;
const CLOCK_BACK_JUMP = 0.25;
// Bus the audio track routes through (created on demand under master).
const VIDEO_AUDIO_BUS = 'video';
-// Video extensions whose cooked `.m4a` audio-track sibling is worth probing.
-// `.esv.bin` is the WeChat-export restaging of `.esv` (code-package suffix
-// whitelist); the sibling keeps the cook's `.esv.m4a` name, so derivation
-// strips the `.bin` first.
-const AUDIO_SIBLING_RE = /\.(esv|mpg|mpeg)(\.bin)?$/i;
-const audioSiblingUrl = (url: string): string => `${url.replace(/\.bin$/i, '')}.m4a`;
+
+/**
+ * Fallback derivation of the cooked `.m4a` audio-track sibling from a resolved
+ * video URL, used only when the source didn't resolve one through the manifest
+ * (VideoAPI passes `audioTrackUrl` when it did). One function owns the whole
+ * convention: strip the WeChat `.esv → .esv.bin` restaging suffix, then a
+ * wasm-decodable extension gains `.m4a`. Null = no sibling to probe.
+ */
+function deriveAudioSiblingUrl(url: string): string | null {
+ const base = url.replace(/\.bin$/i, '');
+ return /\.(esv|mpg|mpeg)$/i.test(base) ? `${base}.m4a` : null;
+}
class WasmVideoStreamHandle implements VideoStreamHandle {
readonly id = nextId_++;
@@ -81,7 +93,6 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
private width_ = 0;
private height_ = 0;
private duration_ = 0;
- private ready_ = false;
private disposed_ = false;
private ended_ = false;
private playing_: boolean;
@@ -95,7 +106,11 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
private audioApi_: AudioAPI | null = null;
private audioUrl_: string | null = null;
private audio_: AudioHandle | null = null;
+ private audioDuration_ = 0;
private audioGen_ = 0;
+ // While an audio-track start is in flight the engine clock must hold, or
+ // the video runs ahead and gets yanked back when the track attaches at 0.
+ private audioPendingGen_ = 0;
constructor(url: string, options: VideoStreamOptions, deps: WasmStreamDeps) {
this.playing_ = options.autoplay ?? true;
@@ -103,10 +118,10 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
this.rate_ = options.playbackRate ?? 1;
this.volume_ = options.volume ?? 1;
this.muted_ = options.muted ?? false;
- void this.start_(url, deps);
+ void this.start_(url, options, deps);
}
- private async start_(url: string, deps: WasmStreamDeps): Promise<void> {
+ private async start_(url: string, options: VideoStreamOptions, deps: WasmStreamDeps): Promise<void> {
try {
const [bytes, mod] = await Promise.all([this.loadBytes_(url), deps.acquire()]);
if (this.disposed_) return;
@@ -119,7 +134,27 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
video.HEAPU8.set(data, ptr);
// _es_video_open owns `ptr` from here (freed on close or on failure).
const decoder = video._es_video_open(ptr, data.length);
- if (!decoder) throw new Error(`not a decodable MPEG-1 stream: ${url}`);
+ if (!decoder) {
+ throw new Error(
+ `not a decodable MPEG-1 stream (or no free decoder slot): ${url} — ` +
+ 'the wasm path plays the cook\'s .esv; raw mp4 / un-transcoded remote URLs cannot decode here',
+ );
+ }
+ let framePtr = 0;
+ try {
+ framePtr = video._malloc(video._es_video_width(decoder) * video._es_video_height(decoder) * 4);
+ if (!framePtr) throw new Error('videodec out of memory');
+ } catch (err) {
+ video._es_video_close(decoder);
+ throw err;
+ }
+ // stop() may have run while we awaited — it saw null fields, so
+ // release what it couldn't.
+ if (this.disposed_) {
+ video._es_video_close(decoder);
+ video._free(framePtr);
+ return;
+ }
this.mod_ = video;
this.decoder_ = decoder;
@@ -127,8 +162,7 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
this.height_ = video._es_video_height(decoder);
this.duration_ = video._es_video_duration(decoder);
this.frameBytes_ = this.width_ * this.height_ * 4;
- this.framePtr_ = video._malloc(this.frameBytes_);
- if (!this.framePtr_) throw new Error('videodec out of memory');
+ this.framePtr_ = framePtr;
video._es_video_set_loop(decoder, this.loop_ ? 1 : 0);
let startAt = 0;
if (this.pendingSeek_ >= 0) {
@@ -138,8 +172,13 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
}
this.audioApi_ = deps.audio();
- if (this.audioApi_ && AUDIO_SIBLING_RE.test(url)) this.audioUrl_ = audioSiblingUrl(url);
- if (this.playing_) void this.startAudio_(startAt);
+ // Manifest-resolved track URL wins (content-addressed staging renames
+ // files, so URL surgery can't find it); URL derivation is the fallback
+ // for direct/hand-placed sources.
+ if (this.audioApi_) this.audioUrl_ = options.audioTrackUrl ?? deriveAudioSiblingUrl(url);
+ // Muted streams don't spin up an audio channel just to be a clock —
+ // the track attaches on the first unmute instead.
+ if (this.playing_ && !this.muted_) void this.startAudio_(startAt);
} catch (err) {
if (this.disposed_) return;
log.error('video', `wasm decode failed for "${url}"`, err);
@@ -166,48 +205,59 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
const api = this.audioApi_;
const url = this.audioUrl_;
if (!api || !url) return;
+ // Restarting a finished non-looping track from its tail would replay
+ // audio the design wants silent (the video outlives the track).
+ if (this.audioDuration_ > 0 && !this.loop_ && offset >= this.audioDuration_ - 0.05) return;
const gen = ++this.audioGen_;
- // A silent video has no cooked sibling — check local paths first so the
- // expected miss stays silent (the audio backend logs a load failure as
- // an error). Remote URLs can't be probed cheaply; playTrack's null
- // return covers them.
- if (!/^https?:\/\//.test(url) && !(await getPlatform().fileExists(url))) {
- if (gen === this.audioGen_) this.audioUrl_ = null;
- return;
- }
- if (this.disposed_ || gen !== this.audioGen_) return;
- const handle = await api.playTrack(url, {
- bus: VIDEO_AUDIO_BUS,
- volume: this.muted_ ? 0 : this.volume_,
- loop: this.loop_,
- playbackRate: this.rate_,
- startOffset: offset,
- });
- if (!handle) {
- if (gen === this.audioGen_) this.audioUrl_ = null; // no track — engine clock
- return;
- }
- if (this.disposed_ || gen !== this.audioGen_) {
- handle.stop();
- return;
- }
- // The audio track is the clock now; the video must not free-wrap on its
- // own (the wrap is driven by the track's playhead jumping back).
- this.mod_?._es_video_set_loop(this.decoder_, 0);
- // A non-looping track that ends BEFORE the last video frame hands the
- // clock back to the engine so the tail still plays out.
- handle.onEnd = () => {
- if (this.audio_ === handle && !this.loop_) {
- this.audio_ = null;
- this.lastNow_ = -1;
+ this.audioPendingGen_ = gen;
+ try {
+ // A silent video has no cooked sibling — check local paths first so
+ // the expected miss stays silent (the audio backend logs a load
+ // failure as an error). Remote URLs can't be probed cheaply;
+ // playTrack's null return covers them.
+ if (!/^https?:\/\//.test(url) && !(await getPlatform().fileExists(url))) {
+ if (gen === this.audioGen_) this.audioUrl_ = null;
+ return;
+ }
+ if (this.disposed_ || gen !== this.audioGen_) return;
+ const handle = await api.playTrack(url, {
+ bus: VIDEO_AUDIO_BUS,
+ volume: this.muted_ ? 0 : this.volume_,
+ loop: this.loop_,
+ playbackRate: this.rate_,
+ startOffset: offset,
+ });
+ if (!handle) {
+ if (gen === this.audioGen_) this.audioUrl_ = null; // no track — engine clock
+ return;
}
- };
- if (!this.playing_) handle.pause();
- this.audio_ = handle;
+ if (this.disposed_ || gen !== this.audioGen_) {
+ handle.stop();
+ return;
+ }
+ this.audioDuration_ = handle.duration || 0;
+ // The audio track is the clock now; the video must not free-wrap on
+ // its own (the wrap is driven by the track's playhead jumping back).
+ this.mod_?._es_video_set_loop(this.decoder_, 0);
+ // A non-looping track that ends BEFORE the last video frame hands the
+ // clock back to the engine so the tail still plays out.
+ handle.onEnd = () => {
+ if (this.audio_ === handle && !this.loop_) {
+ this.audioDuration_ = this.audioDuration_ || handle.currentTime;
+ this.audio_ = null;
+ this.lastNow_ = -1;
+ }
+ };
+ if (!this.playing_) handle.pause();
+ this.audio_ = handle;
+ } finally {
+ if (this.audioPendingGen_ === gen) this.audioPendingGen_ = 0;
+ }
}
private stopAudio_(): void {
this.audioGen_++;
+ this.audioPendingGen_ = 0;
if (this.audio_) {
this.audio_.stop();
this.audio_ = null;
@@ -220,7 +270,11 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
const video = this.mod_;
if (this.disposed_ || !video) return;
- if (this.playing_ && !this.ended_) {
+ if (this.playing_ && !this.ended_ && this.audioPendingGen_) {
+ // An audio-track start is in flight — hold the clock so the track
+ // doesn't attach behind an already-advanced picture.
+ this.lastNow_ = -1;
+ } else if (this.playing_ && !this.ended_) {
if (this.audio_) {
// Audio-track clock: decode toward the track's playhead.
const target = this.audio_.currentTime;
@@ -265,7 +319,6 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
/* flipY */ false,
{ filterMode: 'linear', wrapMode: 'clamp' },
);
- this.ready_ = true;
this.onReady?.();
} else {
updateTextureSubregion(module, this.texture_, 0, 0, this.width_, this.height_, pixels);
@@ -278,7 +331,7 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
get width(): number { return this.width_; }
get height(): number { return this.height_; }
get bytes(): number { return this.frameBytes_; }
- get isReady(): boolean { return this.ready_; }
+ get isReady(): boolean { return this.texture_ !== 0; }
get isPlaying(): boolean { return this.playing_ && !this.ended_; }
get currentTime(): number { return this.mod_ ? this.mod_._es_video_time(this.decoder_) : 0; }
get duration(): number { return this.duration_; }
@@ -292,7 +345,7 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
return;
}
if (this.audio_) this.audio_.resume();
- else if (this.mod_) void this.startAudio_(this.currentTime);
+ else if (this.mod_ && !this.muted_) void this.startAudio_(this.currentTime);
}
pause(): void {
@@ -310,7 +363,7 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
if (this.mod_._es_video_seek(this.decoder_, t)) this.frameDirty_ = true;
// AudioHandles have no in-place seek — restart the track at the offset.
this.stopAudio_();
- if (this.playing_) void this.startAudio_(t);
+ if (this.playing_ && !this.muted_) void this.startAudio_(t);
}
setVolume(volume: number): void {
@@ -320,7 +373,14 @@ class WasmVideoStreamHandle implements VideoStreamHandle {
setMuted(muted: boolean): void {
this.muted_ = muted;
- this.audio_?.setVolume(muted ? 0 : this.volume_);
+ if (this.audio_) {
+ // Already attached (unmuted at some point): mute = volume 0, keeping
+ // the clock authority stable instead of tearing the track down.
+ this.audio_.setVolume(muted ? 0 : this.volume_);
+ } else if (!muted && this.playing_ && this.mod_) {
+ // Muted-from-birth streams attach their track on the first unmute.
+ void this.startAudio_(this.currentTime);
+ }
}
setLoop(loop: boolean): void {
diff --git a/sdk/tests/wasm-video-backend.test.ts b/sdk/tests/wasm-video-backend.test.ts
index 77e1a13b0..95165cdd2 100644
--- a/sdk/tests/wasm-video-backend.test.ts
+++ b/sdk/tests/wasm-video-backend.test.ts
@@ -294,17 +294,47 @@ describe('WasmVideoBackend audio-track clock', () => {
expect(handles[0].stop).toHaveBeenCalled();
});
- it('muted stream starts its track at volume 0; volume/mute changes forward', async () => {
+ it('a muted stream defers its track until unmute, then attaches at the playhead', async () => {
const { mod } = mockVideoModule();
const { api, playTrack, handles } = mockAudio();
const backend = new WasmVideoBackend({ sideModules: () => hostFor(mod), audio: () => api });
const handle = backend.createStream('clip.esv', { muted: true, volume: 0.8 });
await flush();
- expect(playTrack).toHaveBeenCalledWith('clip.esv.m4a', expect.objectContaining({ volume: 0 }));
+ expect(playTrack).not.toHaveBeenCalled(); // no audio channel spent on a muted clock
+
handle.setMuted(false);
- expect(handles[0].setVolume).toHaveBeenLastCalledWith(0.8);
+ await flush();
+ expect(playTrack).toHaveBeenCalledWith('clip.esv.m4a', expect.objectContaining({ volume: 0.8 }));
handle.setVolume(0.3);
expect(handles[0].setVolume).toHaveBeenLastCalledWith(0.3);
+ handle.setMuted(true); // once attached, mute = volume 0 (clock stays)
+ expect(handles[0].setVolume).toHaveBeenLastCalledWith(0);
+ handle.stop();
+ });
+
+ it('a manifest-resolved audioTrackUrl overrides URL derivation', async () => {
+ const { mod } = mockVideoModule();
+ const { api, playTrack } = mockAudio();
+ const backend = new WasmVideoBackend({ sideModules: () => hostFor(mod), audio: () => api });
+ const handle = backend.createStream('assets/1f2e3d.esv.bin', { audioTrackUrl: 'assets/9a8b7c.m4a' });
+ await flush();
+ expect(playTrack).toHaveBeenCalledWith('assets/9a8b7c.m4a', expect.anything());
+ handle.stop();
+ });
+
+ it('does not restart a finished non-looping track from its tail', async () => {
+ const { mod, state } = mockVideoModule();
+ const { api, playTrack, handles } = mockAudio();
+ const backend = new WasmVideoBackend({ sideModules: () => hostFor(mod), audio: () => api });
+ const handle = backend.createStream('clip.esv', { loop: false });
+ await flush();
+ expect(playTrack).toHaveBeenCalledTimes(1);
+ handles[0].onEnd?.(); // track (duration 2.5) finished before the video
+ state.time = 2.48; // playhead inside the video tail, past the track
+ handle.pause();
+ handle.play();
+ await flush();
+ expect(playTrack).toHaveBeenCalledTimes(1); // no tail replay
handle.stop();
});
@@ -393,3 +423,83 @@ describe('WasmVideoBackend audio-track clock', () => {
handle.stop();
});
});
+
+// === VideoAPI ===============================================================
+
+import { VideoAPI } from '../src/video/VideoAPI';
+import type { VideoStreamOptions, VideoStreamHandle } from '../src/video/PlatformVideoBackend';
+
+function recordingBackend() {
+ const created: Array<{ url: string; options: VideoStreamOptions }> = [];
+ const handles: VideoStreamHandle[] = [];
+ return {
+ created,
+ handles,
+ backend: {
+ name: 'recording',
+ createStream(url: string, options: VideoStreamOptions): VideoStreamHandle {
+ created.push({ url, options });
+ const h = { id: handles.length + 1, textureHandle: 0, width: 0, height: 0, isReady: false, isPlaying: false, currentTime: 0, duration: 0, play() {}, pause() {}, stop() {}, seek() {}, setVolume() {}, setMuted() {}, setLoop() {}, setPlaybackRate() {}, pump() {} } as VideoStreamHandle;
+ handles.push(h);
+ return h;
+ },
+ dispose() {},
+ },
+ };
+}
+
+describe('VideoAPI audio-track resolution', () => {
+ it('resolves the cooked sibling ref (path and @uuid forms) and passes it to the backend', () => {
+ const { backend, created } = recordingBackend();
+ const api = new VideoAPI(backend);
+ const table: Record<string, string> = {
+ 'assets/video/clip.mp4': 'assets/1f2e3d.esv.bin',
+ 'assets/video/clip.mp4.m4a': 'assets/9a8b7c.m4a',
+ '@uuid:aaaa': 'assets/1f2e3d.esv.bin',
+ '@uuid:aaaa-audio': 'assets/9a8b7c.m4a',
+ };
+ api.setRefResolver((ref) => table[ref] ?? ref);
+
+ api.play('assets/video/clip.mp4');
+ expect(created[0].url).toBe('assets/1f2e3d.esv.bin');
+ expect(created[0].options.audioTrackUrl).toBe('assets/9a8b7c.m4a');
+
+ api.play('@uuid:aaaa');
+ expect(created[1].options.audioTrackUrl).toBe('assets/9a8b7c.m4a');
+ api.dispose();
+ });
+
+ it('a resolver miss leaves audioTrackUrl undefined (backend derivation fallback)', () => {
+ const { backend, created } = recordingBackend();
+ const api = new VideoAPI(backend);
+ api.setRefResolver((ref) => ref); // passthrough resolver
+ api.play('videos/raw.esv');
+ expect(created[0].options.audioTrackUrl).toBeUndefined();
+ api.dispose();
+ });
+
+ it('update isolates a throwing pump: the bad stream stops, others keep pumping', () => {
+ const { backend } = recordingBackend();
+ const api = new VideoAPI(backend as never);
+ const bad = api.play('a.esv');
+ const good = api.play('b.esv');
+ const goodPump = vi.fn();
+ (bad as { pump(m: unknown): void }).pump = () => { throw new Error('wasm abort'); };
+ (good as { pump(m: unknown): void }).pump = goodPump;
+ const badStop = vi.fn();
+ (bad as { stop(): void }).stop = badStop;
+ const onError = vi.fn();
+ bad.onError = onError;
+
+ expect(() => api.update({} as never)).not.toThrow();
+ expect(goodPump).toHaveBeenCalled();
+ expect(badStop).toHaveBeenCalled();
+ expect(onError).toHaveBeenCalled();
+
+ goodPump.mockClear();
+ api.update({} as never); // bad stream evicted — no repeat error spam
+ expect(goodPump).toHaveBeenCalledTimes(1);
+ expect(onError).toHaveBeenCalledTimes(1);
+ api.dispose();
+ });
+});