A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(playable): adapt asset quality to measured delivery budgets
yhh88408d1b8b3d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bb5ede47a..f84d33d3a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,13 +16,15 @@ published separately; it ships inside the editor.### Added+- **Playable asset quality adapts to the measured delivery budget.** Auto optimization tries lossless WebP, eligible lower MP3 bitrates and bounded WebP quality while preserving image dimensions and alpha. Each candidate is weighed as actual HTML/ZIP against the network, project and internal 3 MiB target; pixel art, font pages and data images stay lossless, and color-managed/animated/16-bit PNGs retain their original format. Reports and the editor show selected encodings, size changes and unmet targets; opt-outs and Skip are honored.+- **Playable creatives have a local container preview.** A CLI server simulates MRAID, Mintegral and page-visibility callbacks, records store gestures without opening a store, and switches portrait/landscape viewports. It opens no browser and preserves the delivered HTML; export-report hashes prevent mixing records from different builds. Logs remain marked as local mocks rather than network approval.- **Playable exports report static checks and pending acceptance.** Export results and the editor package dialog show actual HTML/delivery hashes, network size limits, literal resource references and orientation config checks. Mandatory network SDK scripts are allowed explicitly. CTA, lifecycle, dynamic requests and device/network acceptance remain pending runtime evidence, including when static checks pass.### Fixed-- **Playable exports honor authored image and audio optimization.** Automatic asset optimization applies PNG Max Size (including playable overrides) without loading a GPU texture encoder, and converts eligible WAV clips to MP3 at their authored bitrate. Per-clip opt-outs and the build's Skip setting preserve originals; failed asset cooking prevents a successful export. Network budget driven quality selection remains pending.+- **Playable exports honor authored image and audio optimization.** Automatic asset optimization applies PNG Max Size (including playable overrides) without loading a GPU texture encoder, and converts eligible WAV clips to MP3 at their authored bitrate. Per-clip opt-outs and the build's Skip setting preserve originals; failed asset cooking prevents a successful export.- **Playable preview records identify the delivered archive.** Full export reports verify the adjacent ZIP hash before previewing, catching config changes even when HTML stays identical. Downloaded logs retain HTML/delivery hashes and explicitly disclose omitted events; HTML-only previews remain labeled accordingly.diff --git a/desktop b/desktopindex 7ca8ed152..f70c9f8d2 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 7ca8ed1524cb7b8621acfb5a0e338dbd51379995+Subproject commit f70c9f8d2c939cfbb1ffa51d4153be57c29ef0e0diff --git a/docs/astro/src/content/docs/publishing/overview.mdx b/docs/astro/src/content/docs/publishing/overview.mdxindex 0f950c6c3..90cc36521 100644--- a/docs/astro/src/content/docs/publishing/overview.mdx+++ b/docs/astro/src/content/docs/publishing/overview.mdx@@ -85,7 +85,9 @@ Xcode, because only Apple can sign for a device.## Playable ad networks-With asset optimization set to **Auto**, playable exports honor PNG **Max Size**, including enabled `playable` import overrides, and compress eligible WAV clips to MP3 at the clip's authored bitrate. PNGs remain PNGs; no GPU texture decoder is added. A clip with compression disabled stays WAV, and **Skip** preserves source payloads. Sources and import settings are unchanged. These settings do not automatically reduce quality to meet a network budget; inspect the export's actual delivery size and check report.+With asset optimization set to **Auto**, playable exports first honor PNG **Max Size** (including enabled `playable` overrides) and each WAV clip's bitrate. If the assembled package exceeds the smallest of the network limit, project delivery budget and **3 MiB regression target**, the exporter tries lossless WebP, lower eligible audio bitrates (128 then 96 kbps), then WebP quality 90 and 80. Each candidate is measured as actual HTML and ZIP; optimization stops when both delivery and any HTML limit are met. Images retain their cooked dimensions and alpha; pixel art using nearest filtering, bitmap-font pages and data textures only use lossless encoding. PNGs with gamma/color-profile metadata, animation or 16-bit samples stay PNG, preserving their rendering semantics. Texture/audio compression opt-outs are honored, and **Skip** preserves source payloads.++The export's check report and editor result show baseline/selected sizes and each selected encoding. The 3 MiB target is an internal regression target, not a claim about a network's official limit. If the target cannot be met at the quality floor, the report says so; actual network HTML limits still fail export. WebP uses the bundled ffmpeg encoder, with a warning and unchanged images if unavailable. Sources and import settings remain unchanged. Review image/audio quality and test the delivered package in the official container before publishing; size success does not prove platform acceptance.Every network takes the same single HTML file but disagrees on three things: how bigit may be, what must sit in `<head>`, and which function sends the player to thediff --git a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdxindex 5960e37a3..1cfe57989 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/overview.mdx@@ -73,7 +73,9 @@ import { Aside, Steps } from '@astrojs/starlight/components';## 试玩广告平台-资产优化为 **Auto** 时,试玩导出应用 PNG 的 **Max Size**,包括已启用的 `playable` 导入覆盖,并按音频资源设置的码率将可压缩 WAV 转为 MP3。PNG 仍为 PNG,不增加 GPU 纹理解码器;音频禁用压缩时保留 WAV,**Skip** 保留源文件载荷。源文件和导入设置不被修改。这些设置尚不会按网络预算自动降低质量,请查看实际交付文件大小及自检报告。+资产优化为 **Auto** 时,试玩导出先应用 PNG 的 **Max Size**(含启用的 `playable` 覆盖)及各 WAV 资源的码率。实际包体超出网络上限、项目交付预算和 **3 MiB 回归目标** 的最小值时,依次尝试无损 WebP、允许压缩音频的较低码率(128、96 kbps),再尝试 WebP 质量 90 和 80。每个候选按实际 HTML、ZIP 测量;交付体积与 HTML 上限均达标即停止。纹理保持烘焙后的尺寸和透明度;nearest 过滤像素画、位图字体页和数据纹理仅使用无损编码;含 gamma/色彩配置、动画或 16 位采样的 PNG 保持原格式,以保留渲染语义。图片及音频的禁用压缩设置生效,**Skip** 保留源文件载荷。++导出自检报告和编辑器结果展示优化前后体积及每个资源选用的编码。3 MiB 是内部回归目标,不是平台官方上限;达到质量下限仍未满足目标会明确报告,实际平台 HTML 超限仍使导出失败。WebP 使用随产品提供的 ffmpeg 编码器;不可用时保留图片并给出警告。源文件和导入设置不被修改。发布前请检查图片、音频质量,并在官方容器验证交付包;体积达标不等同平台验收。各家平台收的都是同一个单文件 HTML,但在三件事上不一致:体积上限、`<head>` 里必须放什么、以及用哪个函数把玩家送去商店。在**打包项目**对话框里选平台(就在 Playable 目标自己的设置里),diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex 39ed183f8..b64ae6678 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -850,6 +850,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>minify: opts.minify,resizeTextures: opts.compressTextures,compressAudio: opts.compressAudio,+ sizeBudgetBytes: opts.sizeBudgetBytes,features: opts.features,modulesByPlatform: opts.modulesByPlatform,runtime,diff --git a/pipeline/src/export/exportPlayable.ts b/pipeline/src/export/exportPlayable.tsindex 8a0ba6ac4..88fcea4c3 100644--- a/pipeline/src/export/exportPlayable.ts+++ b/pipeline/src/export/exportPlayable.ts@@ -23,11 +23,13 @@ import { runtimeHostEntry } from '../bundle/runtimeHosts';import {DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, type RuntimeProjectConfig,} from '../project/runtimeConfig';-import { writeFile, mkdir, readFile, stat, rm } from 'node:fs/promises';+import { writeFile, mkdir, readFile, rm } from 'node:fs/promises';import { existsSync } from 'node:fs';import { deflateRawSync } from 'node:zlib';import path from 'node:path';import { cookAssets } from '../assets/cookAssets';+import { scanAssetDatabase } from '../assets/assetDb';+import { optimizePlayableAssets, type PlayableOptimizationAsset, type PlayablePayload } from './playableOptimization';import type { OnExportProgress } from './exportProgress';import { esengineAlias } from '../bundle/esengineResolve';import { officialPackagesPlugin } from '../bundle/officialPackages';@@ -220,6 +222,8 @@ export async function exportPlayable(opts: {resizeTextures?: boolean;/** WAV to MP3 at the authored bitrate, honoring each clip's compression opt-out. */compressAudio?: boolean;+ /** Project delivery budget, constrained by the network limit and 3 MiB regression target. */+ sizeBudgetBytes?: number;/** What the project says about its engine modules; see ProjectFeatures.modules. */features?: ProjectFeatures;/** Per-target overrides laid over those. */@@ -262,8 +266,8 @@ export async function exportPlayable(opts: {// data — the runtime aliases them in memory, so the payload carries each// data URL exactly once.progress({ phase: 'Encoding assets' });- const assets: Record<string, string> = {};const pathMap: Record<string, string> = {};+ const optimizationAssets: PlayableOptimizationAsset[] = [];let manifestEntries: CookManifest['entries'] = [];try {const manifest = JSON.parse(await readFile(path.join(cookDir, 'assets.manifest.json'), 'utf8')) as CookManifest;@@ -276,10 +280,11 @@ export async function exportPlayable(opts: {for (const e of manifest.entries) {const buf = await readFile(path.join(cookDir, e.path));const key = `@uuid:${e.uuid}`;- assets[key] = `data:${mimeOf(e.path)};base64,${buf.toString('base64')}`;+ const dataUrl = `data:${mimeOf(e.path)};base64,${buf.toString('base64')}`;pathMap[e.sourcePath ?? e.path] = key;// The data URL, not the file: base64 is what the asset costs the package.- spans.push({ path: e.path, bytes: assets[key].length });+ spans.push({ path: e.path, bytes: dataUrl.length });+ optimizationAssets.push({ key, path: e.sourcePath ?? e.path, data: buf, mime: mimeOf(e.path) });}} catch (err) {errors.push(`assets: ${err instanceof Error ? err.message : String(err)}`);@@ -367,75 +372,91 @@ export async function exportPlayable(opts: {forcedSideModules(moduleChoices(opts.features, opts.modulesByPlatform?.playable)),);- // 6. Assemble the single HTML, then drop the temp cook dir.+ // 6. Assemble once for each measured candidate, with fixed engine/script spans.progress({ phase: 'Assembling HTML' });const span = (p: string, text: string): string => {spans.push({ path: p, bytes: Buffer.byteLength(text, 'utf8') });return text;};- const globals =+ const beforeAssets =span('wasm/esengine.js', `window.__ENGINE_GLUE__=${JSON.stringify(glue)};`) +span('wasm/esengine.wasm', `window.__ENGINE_WASM__=${JSON.stringify(wasm)};`) +- span('wasm/side-modules', `window.__SIDE_MODULES__=${JSON.stringify(sideModules)};`) +- `window.__GAME_ASSETS__=${JSON.stringify(assets)};` ++ span('wasm/side-modules', `window.__SIDE_MODULES__=${JSON.stringify(sideModules)};`);+ const afterAssets =`window.__GAME_PATHMAP__=${JSON.stringify(pathMap)};` +span(`scenes/${sceneName}.json`, `window.__GAME_SCENES__=${JSON.stringify(scenes)};`) +`window.__GAME_FIRST__=${JSON.stringify(sceneName)};` +- // ONE global for the project's settings, in the same shape game.config.json- // carries them. Five separate globals meant the host and the export had to- // agree on five names, and a sixth setting simply never got a global.- // A playable is one file on an ad network's page: it takes the GL context- // its host hands over, so a WebGPU request has nowhere to land.`window.__GAME_RUNTIME__=${JSON.stringify(playableRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG))};` +- // Last of the globals: the loader script that follows them inflates this one- // and hands it to the page.span('game-bundle.js', `window.__GAME_BUNDLE__=${JSON.stringify(pack(Buffer.from(bundle, 'utf8')))};`);const adProfile = opts.adProfile ?? genericPlayableProfile;const network = playableAdInjection(adProfile, { title, orientation });const outFile = path.join(absOut, 'index.html');span('game-loader.js', loader);- await writeFile(outFile, indexHtml(title, globals, loader, network));- await rm(cookDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });-- const htmlBytes = (await stat(outFile)).size;- if (adProfile.maxHtmlBytes !== undefined && htmlBytes > adProfile.maxHtmlBytes) {- errors.push(`${adProfile.label}: index.html is ${htmlBytes} bytes, exceeding the uncompressed HTML limit of ${adProfile.maxHtmlBytes} bytes. ${adProfile.limitNote}`);- }- // The page, plus the JSON scaffolding around the spans. Derived rather than- // summed, so the parts add up to the file whatever the assembly gains later.- const inlined = spans.reduce((n, s) => n + s.bytes, 0);- spans.push({ path: 'index.html', bytes: Math.max(0, htmlBytes - inlined) });-- // A network that uploads an archive gets one, with index.html at the root. The HTML- // stays beside it: it is what "Preview over http" serves, and what a developer opens- // to look at the thing.let zipFile: string | undefined;- let archiveFiles: { name: string; content: string }[] = [];- let bytes = htmlBytes;+ const archiveFiles: { name: string; content: string }[] = [];if (adProfile.delivery === 'zip') {- progress({ phase: 'Archiving' });const zipName = adProfile.zipFileName ?? 'playable.zip';if (!isPlayableZipFileName(zipName)) errors.push('Playable ZIP filename must be a portable name ending in .zip, without directories.');else {zipFile = path.join(absOut, zipName);- const extraFiles = adProfile.emitZipFiles?.({ title, orientation }) ?? [];const names = new Set(['index.html']);- const files = [{ name: 'index.html', data: await readFile(outFile) }];- for (const file of extraFiles) {+ for (const file of adProfile.emitZipFiles?.({ title, orientation }) ?? []) {const name = typeof file?.name === 'string' ? file.name.toLowerCase() : '';if (!name || !/^[a-z0-9_]+\.[a-z0-9]+$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])\./.test(name) || names.has(name) || typeof file.content !== 'string') {errors.push('Playable ZIP extra files need unique portable root filenames and text content.');continue;}names.add(name);- files.push({ name: file.name, data: Buffer.from(file.content, 'utf8') });+ archiveFiles.push({ name: file.name, content: file.content });}- archiveFiles = files.filter(file => file.name !== 'index.html').map(file => ({ name: file.name, content: file.data.toString('utf8') }));- await writeFile(zipFile, makeZip(files));- // The archive is the file being sent, so it is the one the limit applies to.- bytes = (await stat(zipFile)).size;}}+ const assemble = (payloads: ReadonlyMap<string, PlayablePayload>) => {+ const urls: Record<string, string> = {};+ for (const [key, value] of payloads) urls[key] = `data:${value.mime};base64,${Buffer.from(value.data).toString('base64')}`;+ const html = Buffer.from(indexHtml(title, beforeAssets + `window.__GAME_ASSETS__=${JSON.stringify(urls)};` + afterAssets, loader, network));+ const delivery = zipFile ? makeZip([{ name: 'index.html', data: html },+ ...archiveFiles.map(file => ({ name: file.name, data: Buffer.from(file.content) }))]) : html;+ return { html, delivery, htmlBytes: html.byteLength, deliveryBytes: delivery.byteLength };+ };+ const targetDeliveryBytes = Math.min(adProfile.maxBytes, opts.sizeBudgetBytes ?? Infinity, 3 * 1024 * 1024);+ const baseline = assemble(new Map(optimizationAssets.map(asset => [asset.key, asset])));+ if (errors.length === 0 && (opts.resizeTextures || opts.compressAudio) &&+ (baseline.deliveryBytes > targetDeliveryBytes || baseline.htmlBytes > (adProfile.maxHtmlBytes ?? Infinity))) {+ progress({ phase: 'Optimizing playable budget' });+ const { index } = await scanAssetDatabase(opts.root, { write: false, adopt: false });+ const byUuid = new Map(index.entries.map(entry => [entry.uuid, entry]));+ const fontPages = new Set(index.entries.filter(entry => entry.path.toLowerCase().endsWith('.fnt'))+ .flatMap(entry => index.deps[entry.uuid] ?? []));+ for (const asset of optimizationAssets) {+ const uuid = asset.key.slice('@uuid:'.length);+ asset.importer = byUuid.get(uuid)?.importer;+ asset.losslessOnly = fontPages.has(uuid);+ if (opts.compressAudio && asset.path.toLowerCase().endsWith('.wav')) {+ asset.sourceWav = await readFile(path.join(opts.root, asset.path));+ }+ }+ }+ const optimized = await optimizePlayableAssets({ root: opts.root, assets: optimizationAssets,+ textures: errors.length === 0 && !!opts.resizeTextures, audio: errors.length === 0 && !!opts.compressAudio,+ targetDeliveryBytes, maxHtmlBytes: adProfile.maxHtmlBytes,+ measure: payloads => assemble(payloads), warnings });+ optimized.report.mode = opts.resizeTextures || opts.compressAudio ? 'auto' : 'skip';+ const final = assemble(optimized.payloads);+ await writeFile(outFile, final.html);+ if (zipFile) await writeFile(zipFile, final.delivery);+ await rm(cookDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ const htmlBytes = final.htmlBytes, bytes = final.deliveryBytes;+ for (let i = 0; i < optimizationAssets.length; i++) {+ const payload = optimized.payloads.get(optimizationAssets[i].key)!;+ spans[i].bytes = `data:${payload.mime};base64,${Buffer.from(payload.data).toString('base64')}`.length;+ }+ if (!optimized.report.meetsTarget) warnings.push(`Playable optimization target not met: delivery ${bytes}/${targetDeliveryBytes} bytes, HTML ${htmlBytes}/${adProfile.maxHtmlBytes ?? 'unlimited'} bytes. Reduce assets or engine modules; no quality below WebP 80 / MP3 96 kbps is selected.`);+ if (adProfile.maxHtmlBytes !== undefined && htmlBytes > adProfile.maxHtmlBytes) {+ errors.push(`${adProfile.label}: index.html is ${htmlBytes} bytes, exceeding the uncompressed HTML limit of ${adProfile.maxHtmlBytes} bytes. ${adProfile.limitNote}`);+ }+ const inlined = spans.reduce((n, s) => n + s.bytes, 0);+ spans.push({ path: 'index.html', bytes: Math.max(0, htmlBytes - inlined) });// A full WASM engine + assets routinely exceeds what a network accepts, and this// export used to say so in an English sentence it composed itself. It no longer@@ -446,6 +467,7 @@ export async function exportPlayable(opts: {if (adProfile.deliveryNote) warnings.push(adProfile.deliveryNote);const playableCheck = checkPlayable({ profile: adProfile, html: await readFile(outFile), delivery: await readFile(zipFile ?? outFile), archiveFiles });+ playableCheck.optimization = optimized.report;return {playableCheck,ok: errors.length === 0, platform: 'playable', outDir: absOut,diff --git a/pipeline/src/export/playableCheck.ts b/pipeline/src/export/playableCheck.tsindex 7acd72dbe..fbb67466b 100644--- a/pipeline/src/export/playableCheck.ts+++ b/pipeline/src/export/playableCheck.ts@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createHash } from 'node:crypto';import type { PlayableAdProfile } from './playableAdProfile';+import type { PlayableOptimizationReport } from './playableOptimization';export type PlayableCheckId = 'delivery-size' | 'html-size' | 'markup-resources' | 'host-sdk' | 'orientation-config' | 'cta-interaction' | 'host-lifecycle' | 'runtime-requests' | 'network-acceptance';@@ -18,6 +19,7 @@ export interface PlayableCheckReport {htmlSha256: string;deliverySha256: string;checks: PlayableCheckItem[];+ optimization?: PlayableOptimizationReport;}/** Mask raw text while preserving positions so JS strings are not HTML tags. */diff --git a/pipeline/src/export/playableOptimization.ts b/pipeline/src/export/playableOptimization.tsnew file mode 100644index 000000000..20ffa954f--- /dev/null+++ b/pipeline/src/export/playableOptimization.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { spawn } from 'node:child_process';+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { resolveFfmpeg } from '../assets/videoCook';+import { cookCached, encoderIdentity } from '../assets/cookCache';+import { audioImportSettings, encodeWavToMp3 } from '../assets/audioCook';+import { readTextureCookSettings } from '../project/importSettings';++export interface PlayablePayload { data: Uint8Array; mime: string }+export interface PlayableOptimizationAsset extends PlayablePayload {+ key: string;+ path: string;+ importer?: Record<string, unknown>;+ sourceWav?: Uint8Array;+ /** Font pages, nearest-filtered art and data textures must retain their samples. */+ losslessOnly?: boolean;+}+export interface PlayableMeasuredSize { deliveryBytes: number; htmlBytes: number }+export type PlayableSelectedCodec = 'webp-lossless' | 'webp-90' | 'webp-80' | 'mp3-128' | 'mp3-96';+export interface PlayableOptimizationReport {+ mode: 'auto' | 'skip';+ targetDeliveryBytes: number;+ maxHtmlBytes?: number;+ baseline: PlayableMeasuredSize;+ selected: PlayableMeasuredSize;+ meetsTarget: boolean;+ changes: { path: string; codec: PlayableSelectedCodec; inputBytes: number; outputBytes: number }[];+}++/** WebP cannot retain PNG gamma/profile chunks, animation or 16-bit samples. */+function canReencodePng(data: Uint8Array): boolean {+ const png = Buffer.from(data);+ if (png.length < 33 || !png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || png[24] === 16) return false;+ for (let offset = 8; offset + 12 <= png.length;) {+ const size = png.readUInt32BE(offset);+ if (size > png.length - offset - 12) return false;+ const tag = png.toString('ascii', offset + 4, offset + 8);+ if (['gAMA', 'iCCP', 'cHRM', 'acTL'].includes(tag)) return false;+ offset += 12 + size;+ }+ return true;+}++/** Encode one PNG with no resizing; alpha remains a full-resolution channel. */+async function webp(bin: string, png: Uint8Array, quality: 'lossless' | 90 | 80): Promise<Uint8Array> {+ const tempRoot = path.resolve(tmpdir());+ const dir = await mkdtemp(path.join(tempRoot, 'estella-playable-webp-'));+ try {+ const file = path.join(dir, 'texture.webp');+ // The WebP muxer must seek to finalize alpha chunks and RIFF length. Its+ // pipe output can decode in ffmpeg but is rejected by browsers.+ await new Promise<void>((resolve, reject) => {+ const child = spawn(bin, ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0', '-frames:v', '1',+ '-c:v', 'libwebp', '-lossless', quality === 'lossless' ? '1' : '0', '-quality',+ quality === 'lossless' ? '100' : String(quality), '-compression_level', '6',+ '-pix_fmt', 'bgra', '-f', 'webp', file], { windowsHide: true, stdio: ['pipe', 'ignore', 'pipe'] });+ let stderr = '';+ const timeout = setTimeout(() => { child.kill(); reject(new Error('WebP encoding timed out')); }, 30_000);+ child.stderr.on('data', (chunk: Buffer) => { stderr = (stderr + chunk.toString()).slice(-4096); });+ child.on('error', error => { clearTimeout(timeout); reject(error); });+ child.stdin.on('error', error => { clearTimeout(timeout); reject(error); child.kill(); });+ child.on('close', code => {+ clearTimeout(timeout);+ if (code !== 0) reject(new Error(stderr || `WebP encoder exited ${code}`));+ else resolve();+ });+ child.stdin.end(png);+ });+ const encoded = await readFile(file);+ if (encoded.length < 12 || encoded.toString('ascii', 0, 4) !== 'RIFF' || encoded.toString('ascii', 8, 12) !== 'WEBP'+ || encoded.readUInt32LE(4) !== encoded.byteLength - 8) throw new Error('WebP encoder returned an invalid container');+ return encoded;+ } finally {+ if (path.dirname(path.resolve(dir)) !== tempRoot || !path.basename(dir).startsWith('estella-playable-webp-')) throw new Error('Unexpected WebP temporary directory');+ await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+}++/**+ * Select against the actual assembled HTML/archive, rather than source file sizes.+ * Every candidate is derived from the authored cook, never an earlier lossy result.+ */+export async function optimizePlayableAssets(opts: {+ root: string;+ assets: PlayableOptimizationAsset[];+ textures: boolean;+ audio: boolean;+ targetDeliveryBytes: number;+ maxHtmlBytes?: number;+ measure: (payloads: ReadonlyMap<string, PlayablePayload>) => PlayableMeasuredSize;+ warnings: string[];+}): Promise<{ payloads: Map<string, PlayablePayload>; report: PlayableOptimizationReport }> {+ const payloads = new Map<string, PlayablePayload>(opts.assets.map(asset => [asset.key, { data: asset.data, mime: asset.mime }]));+ const measure = () => {+ const size = opts.measure(payloads);+ return { deliveryBytes: size.deliveryBytes, htmlBytes: size.htmlBytes };+ };+ const baseline = measure();+ let selected = baseline;+ const score = (size: PlayableMeasuredSize) => Math.max(size.deliveryBytes / opts.targetDeliveryBytes,+ opts.maxHtmlBytes === undefined ? 0 : size.htmlBytes / opts.maxHtmlBytes);+ const changes = new Map<string, PlayableOptimizationReport['changes'][number]>();+ const sorted = [...opts.assets].sort((a, b) => b.data.byteLength - a.data.byteLength || a.path.localeCompare(b.path));+ const protectedPngs = new Set<string>();+ if (opts.textures && score(selected) > 1) {+ for (const asset of sorted) {+ if (asset.mime === 'image/png' && readTextureCookSettings(asset.importer, 'playable').compress !== 'off' && !canReencodePng(asset.data)) {+ protectedPngs.add(asset.key);+ opts.warnings.push(`${asset.path}: kept PNG to preserve color-profile, animation or sample-depth semantics (or an unrecognized PNG layout).`);+ }+ }+ }+ let encoder: { bin: string; id: string } | null | undefined;+ const failures = new Set<string>();+ for (const stage of ['lossless', 'audio-128', 'audio-96', 90, 80] as const) {+ if (score(selected) <= 1) break;+ for (const asset of sorted) {+ if (score(selected) <= 1) break;+ const previous = payloads.get(asset.key)!;+ let candidate: PlayablePayload | undefined;+ let codec: PlayableSelectedCodec;+ try {+ if (stage === 'audio-128' || stage === 'audio-96') {+ const settings = audioImportSettings(asset.importer);+ const bitrate = stage === 'audio-128' ? 128 : 96;+ if (!opts.audio || !asset.sourceWav || !settings.compress || settings.bitrateKbps <= bitrate) continue;+ const bytes = await encodeWavToMp3(asset.sourceWav, bitrate);+ if (!bytes) continue;+ candidate = { data: bytes, mime: 'audio/mpeg' }; codec = stage === 'audio-128' ? 'mp3-128' : 'mp3-96';+ } else {+ const settings = readTextureCookSettings(asset.importer, 'playable');+ if (!opts.textures || asset.mime !== 'image/png' || settings.compress === 'off'+ || (stage !== 'lossless' && (asset.losslessOnly || asset.importer?.filterMode === 'nearest' || !settings.srgb))) continue;+ if (failures.has(asset.key) || protectedPngs.has(asset.key)) continue;+ if (encoder === undefined) {+ const bin = await resolveFfmpeg();+ encoder = bin ? { bin, id: encoderIdentity(bin) } : null;+ if (!encoder) opts.warnings.push('Playable WebP optimization unavailable: the bundled ffmpeg encoder was not found; images remain unchanged.');+ }+ if (!encoder) continue;+ const quality = stage;+ const bytes = (await cookCached(opts.root, [asset.data, `playable-webp:v3:${quality}`, encoder.id],+ () => webp(encoder!.bin, asset.data, quality))).bytes;+ candidate = { data: bytes, mime: 'image/webp' };+ codec = stage === 'lossless' ? 'webp-lossless' : stage === 90 ? 'webp-90' : 'webp-80';+ }+ payloads.set(asset.key, candidate);+ const measured = measure();+ if (score(measured) < score(selected)) {+ selected = measured;+ changes.set(asset.key, { path: asset.path, codec, inputBytes: asset.data.byteLength, outputBytes: candidate.data.byteLength });+ } else payloads.set(asset.key, previous);+ } catch (error) {+ payloads.set(asset.key, previous);+ failures.add(asset.key);+ opts.warnings.push(`${asset.path}: playable optimization retained the previous payload — ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ }+ const report: PlayableOptimizationReport = { mode: opts.textures || opts.audio ? 'auto' : 'skip',+ targetDeliveryBytes: opts.targetDeliveryBytes, maxHtmlBytes: opts.maxHtmlBytes,+ baseline, selected, meetsTarget: score(selected) <= 1, changes: [...changes.values()] };+ return { payloads, report };+}diff --git a/pipeline/tests/playable-optimization.test.ts b/pipeline/tests/playable-optimization.test.tsnew file mode 100644index 000000000..f92edf1f6--- /dev/null+++ b/pipeline/tests/playable-optimization.test.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { optimizePlayableAssets, type PlayablePayload, type PlayableOptimizationAsset } from '../src/export/playableOptimization';+import { makeZip } from '../../build-tools/utils/zip.js';+import { noisePng } from './fixtures/solidPng.mjs';+import { decodePngImage, encodeRgbaPng } from '../src/assets/atlasPacker';+import { resolveFfmpeg } from '../src/assets/videoCook';+import { encodeWavToMp3 } from '../src/assets/audioCook';+import { PNG } from 'pngjs';++let root: string;+beforeAll(() => { root = mkdtempSync(path.join(tmpdir(), 'estella-playable-budget-')); });+afterAll(() => {+ if (path.dirname(path.resolve(root)) !== path.resolve(tmpdir()) || !path.basename(root).startsWith('estella-playable-budget-')) throw new Error('Unexpected fixture directory');+ rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+});+function measure(payloads: ReadonlyMap<string, PlayablePayload>) {+ const html = Buffer.from(`<html><script>window.assets=${JSON.stringify(Object.fromEntries([...payloads].map(([key, payload]) =>+ [key, `data:${payload.mime};base64,${Buffer.from(payload.data).toString('base64')}`])))}</script></html>`);+ return { htmlBytes: html.byteLength, deliveryBytes: makeZip([{ name: 'index.html', data: html },+ { name: 'config.json', data: Buffer.from('{"orientation":0}') }]).byteLength };+}+const image = (importer: Record<string, unknown> = {}): PlayableOptimizationAsset => ({+ key: 'image', path: 'art.png', data: noisePng(128, 64), mime: 'image/png', importer,+});+const run = (assets: PlayableOptimizationAsset[], extra = {}) => optimizePlayableAssets({ root, assets, textures: true,+ audio: true, targetDeliveryBytes: 1, measure, warnings: [], ...extra });++describe('playable network budget optimization', () => {+ it('retains lossless dimensions, colors and every alpha sample', async () => {+ const original = decodePngImage('alpha', noisePng(128, 64));+ for (let i = 0; i < original.rgba.length; i += 4) original.rgba[i + 3] = (i / 4) % 256;+ const asset = { ...image(), data: encodeRgbaPng(128, 64, original.rgba), losslessOnly: true };+ const result = await run([asset]);+ expect(result.report.changes[0]?.codec).toBe('webp-lossless');+ const container = Buffer.from(result.payloads.get('image')!.data);+ expect(container.readUInt32LE(4)).toBe(container.length - 8);+ const bin = await resolveFfmpeg(); expect(bin).not.toBeNull();+ const decoded = decodePngImage('webp', execFileSync(bin!, ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0',+ '-frames:v', '1', '-f', 'image2pipe', '-c:v', 'png', 'pipe:1'], { input: result.payloads.get('image')!.data, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }));+ expect([decoded.width, decoded.height]).toEqual([128, 64]);+ for (let i = 0; i < original.rgba.length; i += 4) {+ expect(decoded.rgba[i + 3]).toBe(original.rgba[i + 3]);+ if (original.rgba[i + 3] !== 0) expect(Array.from(decoded.rgba.slice(i, i + 3))).toEqual(Array.from(original.rgba.slice(i, i + 3)));+ }+ expect(result.report.selected).toEqual(measure(result.payloads));+ }, 60_000);++ it('tries bounded lossy quality when needed, never resizes and reports an unmet target', async () => {+ const result = await run([image()]);+ expect(result.report.changes[0]?.codec).toBe('webp-80');+ const container = Buffer.from(result.payloads.get('image')!.data);+ expect(container.readUInt32LE(4)).toBe(container.length - 8);+ expect(result.report.selected.deliveryBytes).toBeLessThan(result.report.baseline.deliveryBytes);+ expect(result.report.meetsTarget).toBe(false);+ const bin = await resolveFfmpeg();+ const decoded = decodePngImage('webp', execFileSync(bin!, ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0',+ '-frames:v', '1', '-f', 'image2pipe', '-c:v', 'png', 'pipe:1'], { input: result.payloads.get('image')!.data, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }));+ expect([decoded.width, decoded.height]).toEqual([128, 64]);+ }, 60_000);++ it('keeps texture opt-outs and restricts pixel art, font pages and data images to lossless', async () => {+ const optedOut = image({ compress: 'off' });+ const untouched = await run([optedOut]);+ expect(untouched.report.changes).toEqual([]);+ expect(untouched.payloads.get('image')!.data).toEqual(optedOut.data);+ for (const asset of [image({ filterMode: 'nearest' }), image({ sRGB: false }), { ...image(), losslessOnly: true }]) {+ const result = await run([asset]);+ expect(result.report.changes.every(change => change.codec === 'webp-lossless')).toBe(true);+ }+ }, 60_000);+ it('preserves gamma-managed PNGs rather than labeling a color-profile conversion lossless', async () => {+ const png = PNG.sync.read(noisePng(128, 64));+ png.gamma = 0.45455;+ const asset = { ...image(), data: PNG.sync.write(png) };+ const warnings: string[] = [];+ const result = await run([asset], { warnings });+ expect(result.report.changes).toEqual([]);+ expect(result.payloads.get('image')!.data).toEqual(asset.data);+ expect(warnings.some(warning => warning.includes('color-profile'))).toBe(true);+ });++ it('does no quality work when under budget or when the build skips optimization', async () => {+ for (const extra of [{ targetDeliveryBytes: 1024 * 1024 }, { textures: false, audio: false }]) {+ const asset = image(); const result = await run([asset], extra);+ expect(result.report.changes).toEqual([]);+ expect(result.report.selected).toEqual(result.report.baseline);+ expect(result.payloads.get('image')!.data).toEqual(asset.data);+ }+ });+ it('keeps assembled binary buffers out of the persisted size report', async () => {+ const result = await run([image()], { targetDeliveryBytes: 1024 * 1024,+ measure: (payloads: ReadonlyMap<string, PlayablePayload>) => ({ ...measure(payloads), html: Buffer.alloc(1024), delivery: Buffer.alloc(1024) }) });+ expect(Object.keys(result.report.baseline).sort()).toEqual(['deliveryBytes', 'htmlBytes']);+ expect(Object.keys(result.report.selected).sort()).toEqual(['deliveryBytes', 'htmlBytes']);+ expect(JSON.stringify(result.report).length).toBeLessThan(1000);+ });++ it('observes the uncompressed HTML limit independently of the ZIP target', async () => {+ const result = await run([image()], { targetDeliveryBytes: 1024 * 1024, maxHtmlBytes: 10000 });+ expect(result.report.baseline.deliveryBytes).toBeLessThan(1024 * 1024);+ expect(result.report.baseline.htmlBytes).toBeGreaterThan(10000);+ expect(result.report.changes.length).toBeGreaterThan(0);+ expect(result.report.selected.htmlBytes).toBeLessThan(result.report.baseline.htmlBytes);+ expect(result.report.selected).toEqual(measure(result.payloads));+ });++ it('selects 96 kbps from source WAV and respects audio opt-outs and authored 96 kbps', async () => {+ const wav = Buffer.alloc(44 + 44100 * 2);+ wav.write('RIFF'); wav.writeUInt32LE(wav.length - 8, 4); wav.write('WAVE', 8);+ wav.write('fmt ', 12); wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22);+ wav.writeUInt32LE(44100, 24); wav.writeUInt32LE(88200, 28); wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34);+ wav.write('data', 36); wav.writeUInt32LE(wav.length - 44, 40);+ for (let i = 0; i < 44100; i++) wav.writeInt16LE(Math.round(Math.sin(i / 20) * 12000), 44 + i * 2);+ const asset = { key: 'audio', path: 'sound.wav', data: (await encodeWavToMp3(wav, 128))!, mime: 'audio/mpeg', sourceWav: wav };+ const selected = await run([asset]);+ expect(selected.report.changes[0]?.codec).toBe('mp3-96');+ expect(selected.report.selected.deliveryBytes).toBeLessThan(selected.report.baseline.deliveryBytes);+ const high = { ...asset, data: (await encodeWavToMp3(wav, 192))!, importer: { bitrateKbps: 192 } };+ const midBudget = measure(new Map([['audio', asset]])).deliveryBytes + 1;+ const moderate = await run([high], { targetDeliveryBytes: midBudget });+ expect(moderate.report.changes[0]?.codec).toBe('mp3-128');+ expect(moderate.report.meetsTarget).toBe(true);+ for (const importer of [{ compress: false }, { bitrateKbps: 96 }]) {+ const retained = await run([{ ...asset, importer }]);+ expect(retained.report.changes).toEqual([]);+ expect(retained.payloads.get('audio')!.data).toEqual(asset.data);+ }+ }, 60_000);+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d5309316b..aa8e2e36d 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,11 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(playable): adapt asset quality to measured delivery budgets':+ { note: 'Playable asset quality adapts to the measured delivery budget.' },+ 'feat(editor): show playable asset optimization decisions':+ { note: 'Playable asset quality adapts to the measured delivery budget.' },+'fix(playable): honor authored texture and audio optimization':{ note: 'Playable exports honor authored image and audio optimization.' },