Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Keep webcam tracking active when the live page is hidden
shinshin863e8ef65b9892
diff --git a/README.ja.md b/README.ja.mdindex 0bfe044..42ab1cb 100644--- a/README.ja.md+++ b/README.ja.md@@ -76,6 +76,8 @@ npm run devどちらの画面もローカルの開発サーバー(`npm run dev`)で使います。操作画面からの更新が止まると、配信用画面は待機動作に戻ります。+操作画面は専用のウィンドウで開いたままにしてください。OBS用URLはOBSの中か別のタブで開き、操作画面のタブには貼り付けないでください。画面が隠れて追跡が停止・低速になったという表示が出た場合は、操作画面のウィンドウを前面に戻してください。+## 詳しい資料- [エージェント向けの手順書](docs/agent-guide.md): エージェントが作業するときの手順diff --git a/README.md b/README.mdindex f1636e8..3a59e08 100644--- a/README.md+++ b/README.md@@ -107,6 +107,10 @@ directly in OBS. For other capture software, choose green and apply a chroma keyBoth pages use the local development server (`npm run dev`). The stream view shows idlemotion when the Live page stops sending updates.+Keep the Live page open in its own window. Open the OBS URL inside OBS or in another+tab; do not paste it into the tab running Live. If the page reports that tracking has+stopped or slowed while hidden, bring its window to the front.+## More- [Agent guide](docs/agent-guide.md): the step-by-step procedure agents followdiff --git a/e2e/agent-request.spec.ts b/e2e/agent-request.spec.tsindex ba04741..a07c403 100644--- a/e2e/agent-request.spec.ts+++ b/e2e/agent-request.spec.ts@@ -6,12 +6,23 @@ import { dismissGuide, samplePresent, sampleSkipReason } from './sample';test('paths stay hidden while copies keep full paths, folder buttons work and recipient changes persist', async ({ page, context }) => {test.skip(!samplePresent, sampleSkipReason); await context.grantPermissions(['clipboard-read', 'clipboard-write']);await page.goto('/'); await dismissGuide(page);+ let finishLoading!: () => void;+ const loading = new Promise<void>(resolve => { finishLoading = resolve; });+ const layersUrl = '**/__studio/projects/sample-miko-qipao/built/layers.json';+ await page.route(layersUrl, async route => { await loading; await route.continue(); }, { times: 1 });+ const opening = page.waitForRequest(layersUrl);await page.locator('.open-menu > summary').click(); await page.getByTestId('project-sample-miko-qipao').click();- await page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true }).check();- const card = page.getByTestId('ask-agent-variants');- await expect(card.locator('.root-path')).toHaveCount(0);+ await opening;+ // Checking Mouth before the project finishes loading must survive the load.+ const mouth = page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true });+ await mouth.check();+ finishLoading();const location = page.getByTestId('project-location');await expect(location.locator('strong')).toHaveText('Sample project');+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');+ await expect(mouth).toBeChecked();+ const card = page.getByTestId('ask-agent-variants');+ await expect(card.locator('.root-path')).toHaveCount(0);await expect(location.locator('.project-path')).toHaveCount(0);await expect(location).not.toContainText('~/'); await expect(location).not.toContainText('samples/miko-qipao');await location.getByRole('button', { name: 'Copy path', exact: true }).click();diff --git a/e2e/live-streaming.spec.ts b/e2e/live-streaming.spec.tsindex add8e6e..b76aaf0 100644--- a/e2e/live-streaming.spec.ts+++ b/e2e/live-streaming.spec.ts@@ -31,7 +31,7 @@ async function syntheticMedia(page: Page) {}const canvas = document.createElement('canvas'); canvas.width = 640; canvas.height = 480;const ctx = canvas.getContext('2d')!;- const draw = () => { ctx.fillStyle = '#999'; ctx.fillRect(0, 0, 640, 480); ctx.fillStyle = '#fff'; ctx.fillRect(Date.now() % 500, 100, 40, 40); };+ const draw = () => { if ((window as Window & { freezeVideo?: boolean }).freezeVideo) return; ctx.fillStyle = '#999'; ctx.fillRect(0, 0, 640, 480); ctx.fillStyle = '#fff'; ctx.fillRect(Date.now() % 500, 100, 40, 40); };draw(); const timer = window.setInterval(draw, 33);const stream = canvas.captureStream(30), track = stream.getTracks()[0], stop = track.stop.bind(track);track.stop = () => { clearInterval(timer); stop(); };@@ -39,13 +39,14 @@ async function syntheticMedia(page: Page) {} });});}-async function stubTracker(page: Page) {- await page.route('**/src/live/face-tracker.ts', route => route.fulfill({ contentType: 'application/javascript', body: `- export async function createFaceTracker() { return { delegate: 'GPU', close() {}, detect() {- const a = (window.__liveYaw ?? 24) * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);+async function stubTracker(page: Page, moving = false) {+ await page.context().route('**/mediapipe/vision_bundle.cjs', route => route.fulfill({ contentType: 'application/javascript', body: `+ self.exports.FilesetResolver = { forVisionTasks: async () => ({}) };+ self.exports.FaceLandmarker = { createFromOptions: async () => ({ close() {}, detectForVideo() {+ const a = ${moving ? 'Math.sin(performance.now() / 300) * 24' : '24'} * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);return { faceLandmarks: [[]], facialTransformationMatrixes: [{ data: [c,0,-s,0,0,1,0,0,s,0,c,0,0,0,0,1] }],faceBlendshapes: [{ categories: [{ categoryName: 'mouthPucker', score: .8 }, { categoryName: 'jawOpen', score: .1 }] }] };- } }; }` }));+ } }) };` }));}async function ready(page: Page, url: string) {await page.goto(url); await expect(page.locator('canvas[data-state="ready"]')).toBeVisible();@@ -137,7 +138,7 @@ test('camera denial is explained without starting capture', async ({ page }) =>test('real tracking runtime loads its model and WASM locally with synthetic video only', async ({ context, page }) => {test.setTimeout(60000);const outside = await guardNetwork(context), assets: string[] = [], errors: string[] = [];- page.on('request', request => { if (request.url().includes('/mediapipe/')) assets.push(request.url()); });+ context.on('request', request => { if (request.url().includes('/mediapipe/')) assets.push(request.url()); });page.on('pageerror', error => errors.push(error.message));await syntheticMedia(page); await ready(page, '/live.html');await page.getByRole('button', { name: 'Start camera', exact: true }).click();@@ -149,3 +150,55 @@ test('real tracking runtime loads its model and WASM locally with synthetic videexpect(assets.some(url => url.endsWith('.wasm'))).toBe(true);expect(errors).toEqual([]); expect(outside).toEqual([]);});++async function hideControls(page: Page) {+ await page.evaluate(() => {+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });+ // Visibility alone does not pause RAF in a headless test. Also stop both painting callbacks.+ window.requestAnimationFrame = () => 0;+ HTMLVideoElement.prototype.requestVideoFrameCallback = () => 0;+ document.dispatchEvent(new Event('visibilitychange'));+ });+}++for (const source of ['processor', 'video-callback', 'worker-timer']) {+ test(`hidden control page relays fresh poses at 15 fps or more using ${source}`, async ({ context, page }) => {+ const outside = await guardNetwork(context);+ if (source !== 'processor') await page.addInitScript(source => {+ Object.defineProperty(window, 'MediaStreamTrackProcessor', { value: undefined });+ if (source === 'worker-timer') Object.defineProperty(HTMLVideoElement.prototype, 'requestVideoFrameCallback', { value: undefined, writable: true });+ }, source);+ await syntheticMedia(page); await stubTracker(page, true); await ready(page, '/live.html');+ const stream = await context.newPage(); await ready(stream, '/stream.html');+ await page.getByRole('button', { name: 'Start camera', exact: true }).click();+ await expect(page.getByTestId('tracking-status')).toHaveAttribute('data-state', 'tracking');+ await hideControls(page); await stream.bringToFront();+ const metrics = await stream.evaluate(async () => {+ const path = '/src/live/relay.ts', { receiveLiveParameters } = await import(path);+ const samples: { time: number; angle: number }[] = [], start = performance.now();+ const off = receiveLiveParameters((data: { params: Record<string, number> }) => { samples.push({ time: performance.now(), angle: data.params.angleX }); });+ await new Promise(resolve => setTimeout(resolve, 4000)); off();+ return { fps: samples.length / ((performance.now() - start) / 1000), range: Math.max(...samples.map(p => p.angle)) - Math.min(...samples.map(p => p.angle)), maxGap: Math.max(...samples.slice(1).map((p, i) => p.time - samples[i].time)) };+ });+ expect(metrics.fps).toBeGreaterThanOrEqual(15); expect(metrics.range).toBeGreaterThan(15); expect(metrics.maxGap).toBeLessThan(1000);+ await expect(stream.locator('#avatar')).toHaveAttribute('data-live', 'active');+ await expect(page.getByTestId('background-status')).toHaveCount(0);+ expect(outside).toEqual([]);+ console.log(`Hidden ${source}: ${JSON.stringify(metrics)}`);+ });+}++test('hidden tracking stall warns in all languages and clears when fresh frames resume', async ({ page }) => {+ await syntheticMedia(page); await stubTracker(page); await ready(page, '/live.html');+ await page.getByRole('button', { name: 'Start camera', exact: true }).click();+ await expect(page.getByTestId('tracking-status')).toHaveAttribute('data-state', 'tracking');+ await hideControls(page);+ await page.evaluate(() => { (window as Window & { freezeVideo?: boolean }).freezeVideo = true; });+ await expect(page.getByTestId('background-status')).toContainText('Tracking has stopped', { timeout: 5000 });+ await page.getByRole('button', { name: '日本語', exact: true }).click();+ await expect(page.getByTestId('background-status')).toContainText('この画面が隠れているため追跡が止まっています');+ await page.getByRole('button', { name: '简体中文', exact: true }).click();+ await expect(page.getByTestId('background-status')).toContainText('面部追踪已停止');+ await page.evaluate(() => { (window as Window & { freezeVideo?: boolean }).freezeVideo = false; });+ await expect(page.getByTestId('background-status')).toHaveCount(0, { timeout: 5000 });+});diff --git a/e2e/workflow.spec.ts b/e2e/workflow.spec.tsindex cfe1634..e6e862f 100644--- a/e2e/workflow.spec.ts+++ b/e2e/workflow.spec.ts@@ -152,6 +152,8 @@ test('the read-only sample still gives a mouth request and keeps its source prot});test('external sprite updates load automatically while keeping edited outlines, selection, zoom and undo', async ({ page, request }) => {test.setTimeout(90000); await page.setViewportSize({ width: 1440, height: 900 }); await open(page); await editEye(page);+ const mouth = page.getByTestId('variants-panel').getByRole('checkbox', { name: 'Mouth', exact: true });+ await mouth.check();const point = page.getByRole('spinbutton', { name: 'eyes.0.opening.0.0', exact: true });const initialScale = Number(await page.getByTestId('editor').getAttribute('data-scale'));await page.getByTestId('editor').hover(); await page.mouse.wheel(0, -200);@@ -167,6 +169,7 @@ test('external sprite updates load automatically while keeping edited outlines,await runTool(resolve('.'), directory, 'build-sprites');await expect(page.getByTestId('variants-panel').locator('.variant-count').last()).toHaveText('1 of 4 images', { timeout: 20000 });await expect(page.getByRole('status').filter({ hasText: 'Drawn variants loaded.' })).toBeVisible();+ await expect(mouth).toBeChecked();await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready'); await page.waitForTimeout(300);expect(await pixels(page)).not.toBe(before); await expect(page.locator('.mouth-fallback')).toHaveCount(0);await page.screenshot({ path: 'docs/screenshots/ui4-auto-after-en-1440x900.png' });@@ -181,6 +184,9 @@ test('external sprite updates load automatically while keeping edited outlines,await expect(point).toHaveValue('451'); await expect(page.getByTestId('stale-banner')).toBeVisible();await expect(page.getByTestId('editor')).toHaveAttribute('data-focus-group', 'eyes'); await expect(page.getByTestId('zoom-value')).toHaveText(zoomText!);await page.getByRole('button', { name: 'Undo', exact: true }).click(); await expect(point).toHaveValue('446');+ await page.locator('.open-menu > summary').click(); await page.getByTestId('project-sample-miko-qipao').click();+ await expect(page.getByTestId('project-location').locator('strong')).toHaveText('Sample project');+ await expect(mouth).not.toBeChecked();});test('pose and lip tabs keep a large preview at 1440 by 900 in both languages', async ({ page }) => {await page.setViewportSize({ width: 1440, height: 900 }); await open(page);diff --git a/src/editor/VariantsPanel.tsx b/src/editor/VariantsPanel.tsxindex 849eaf6..9401cab 100644--- a/src/editor/VariantsPanel.tsx+++ b/src/editor/VariantsPanel.tsx@@ -25,7 +25,9 @@ export function VariantsPanel({ project, projectPath, assets, rootPath, busy, stconst [lastAction, setLastAction] = useState<ProjectJob>('variant-requests');const input = useRef<HTMLInputElement>(null), current = useRef(0);const writable = !!project && !project.readOnly;- useEffect(() => { setEyes(false); setMouth(false); setError(null); setLog(''); setAccepted(false); setNotice(''); }, [project?.name, projectPath]);+ // Loading metadata for the current project must not reset choices made during loading.+ const identity = project?.relativePath ?? projectPath;+ useEffect(() => { setEyes(false); setMouth(false); setError(null); setLog(''); setAccepted(false); setNotice(''); }, [identity]);useEffect(() => {const revision = ++current.current;setPresent([]); setRequests([]);diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.jsindex d6616d2..c8614cd 100644--- a/src/engine/createMeshAvatar.js+++ b/src/engine/createMeshAvatar.js@@ -141,7 +141,7 @@ export async function createMeshAvatarImpl(canvas, options) {let parameters = {}, parameterWeight = 1, lastParameters = {};const tmp = [0, 0];- function tick(dt) {+ function updateParameters(dt) {const P = { ...motion.update(dt) };for (const [key, value] of Object.entries(parameters)) P[key] = parameterWeight === 1 ? value : (P[key] ?? 0) + (value - (P[key] ?? 0)) * parameterWeight;// Speech owns the mouth while active; explicit pose sliders still own all other parameters.@@ -150,6 +150,10 @@ export async function createMeshAvatarImpl(canvas, options) {if (!options.preserveMouthForm || parameters.mouthForm === undefined) P.mouthForm = motion.P.mouthForm;}lastParameters = P;+ return P;+ }+ function tick(dt) {+ const P = updateParameters(dt);const phys = physics.step(P, dt);const bp = baseMesh.pos, br = baseMesh.rest;@@ -239,6 +243,8 @@ export async function createMeshAvatarImpl(canvas, options) {if (sec === 0) tick(0);else for (let i = 0; i < Math.round(sec * fps); i++) tick(1 / fps);},+ /** Update motion and lip sync without drawing a hidden preview. */+ advanceParameters(sec) { if (!destroyed) updateParameters(sec); },destroy() {if (destroyed) return;destroyed = true;diff --git a/src/engine/index.ts b/src/engine/index.tsindex 485dbd4..c40956f 100644--- a/src/engine/index.ts+++ b/src/engine/index.ts@@ -30,6 +30,7 @@ export interface MeshAvatar {setSwayGain(gain: number): void;onMotion(listener: (id: string | null) => void): () => void;advance(seconds: number, fps?: number): void;+ advanceParameters(seconds: number): void;destroy(): void;}diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsxindex d8004a2..dea177a 100644--- a/src/live/LiveApp.tsx+++ b/src/live/LiveApp.tsx@@ -3,7 +3,7 @@ import { useI18n } from '../editor/i18n';import { createAvatarView } from './avatar-view';import { viewSettings, streamUrl, backgroundColor } from './settings';import { FacePose, type TrackingOptions } from './tracking';-import { CameraCapture, MicrophoneCapture, type CameraState, type MicState } from './media';+import { CameraCapture, MicrophoneCapture, type CameraState, type MicState, type BackgroundTracking } from './media';import { liveText } from './i18n';import { createLiveSender } from './relay';@@ -18,6 +18,7 @@ export function LiveApp() {const [gain, setGain] = useState(1), [calibrated, setCalibrated] = useState(false);const [copyState, setCopyState] = useState<'copied' | 'copyError' | null>(null);const [viewState, setViewState] = useState<'loading' | 'ready' | 'projectError'>('loading');+ const [backgroundStatus, setBackgroundStatus] = useState<BackgroundTracking>(null);const canvas = useRef<HTMLCanvasElement>(null), video = useRef<HTMLVideoElement>(null);const camera = useRef<CameraCapture | null>(null), microphone = useRef<MicrophoneCapture | null>(null);const pose = useRef(new FacePose());@@ -34,6 +35,12 @@ export function LiveApp() {}, []);useEffect(() => {let cancelled = false, view: Awaited<ReturnType<typeof createAvatarView>> | undefined;+ const clock = new Worker(new URL('./clock-worker.ts', import.meta.url), { type: 'module' });+ clock.onmessage = () => {+ const now = performance.now();+ view?.updateIfStalled(now);+ setBackgroundStatus(camera.current?.backgroundStatus(document.visibilityState === 'hidden' || !!view?.paintPaused(now), now) ?? null);+ };const send = createLiveSender(settings.project);setViewState('loading');void createAvatarView(canvas.current!, settings, (avatar, now, dt) => {@@ -46,7 +53,7 @@ export function LiveApp() {}, (avatar, now) => {if (controls.current.cameraState === 'running' || controls.current.micState === 'micOn') send(avatar.getParameters(), now);}).then(value => { if (cancelled) value.destroy(); else { view = value; setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });- return () => { cancelled = true; view?.destroy(); };+ return () => { cancelled = true; clock.terminate(); view?.destroy(); };}, [settings.project, settings.fit]);const cameraActive = cameraState === 'starting' || cameraState === 'running';const micActive = micState === 'micStarting' || micState === 'micOn';@@ -66,6 +73,7 @@ export function LiveApp() {if (cameraActive) camera.current?.stop(); else void camera.current?.start(cameraId).then(refreshDevices);}}>{cameraActive ? t.stop : t.start}</button><button disabled={!tracking} onClick={() => setCalibrated(pose.current.calibrate(performance.now()))}>{t.calibrate}</button></div><p role="status" data-testid="tracking-status" data-state={status}>{t[status]}</p>+ {backgroundStatus && <p role="alert" className="live-error" data-testid="background-status">{t[backgroundStatus]}</p>}<small>{calibrated ? t.calibrated : t.calibrateHint}</small><label className="live-check"><input type="checkbox" checked={options.mirror} onChange={event => setOptions(current => ({ ...current, mirror: event.target.checked }))} />{t.mirror}</label><label>{t.sensitivity}<input type="range" min="0.25" max="2" step="0.05" value={options.sensitivity} onChange={event => setOptions(current => ({ ...current, sensitivity: Number(event.target.value) }))} /></label>diff --git a/src/live/avatar-view.ts b/src/live/avatar-view.tsindex de07f9d..e4c6420 100644--- a/src/live/avatar-view.ts+++ b/src/live/avatar-view.ts@@ -18,17 +18,20 @@ export async function createAvatarView(canvas: HTMLCanvasElement, settings: Viewif (!settings.idle) avatar.setParameters(neutralParameters);canvas.dataset.state = 'ready';const timing: FrameTiming = { frames: 0, totalMs: 0, maxMs: 0 };- let raf = 0, previous = performance.now();- const frame = (now: number) => {+ let raf = 0, previous = performance.now(), lastPaint = previous;+ const update = (now: number, draw = true) => {const dt = Math.min(0.05, Math.max(0.001, (now - previous) / 1000)); previous = now;beforeFrame?.(avatar, now, dt);const start = performance.now();- avatar.advance(dt, 1 / dt);+ if (draw) avatar.advance(dt, 1 / dt); else avatar.advanceParameters(dt);const elapsed = performance.now() - start;- timing.frames++; timing.totalMs += elapsed; timing.maxMs = Math.max(timing.maxMs, elapsed);+ if (draw) { timing.frames++; timing.totalMs += elapsed; timing.maxMs = Math.max(timing.maxMs, elapsed); }afterFrame?.(avatar, now);- raf = requestAnimationFrame(frame);};+ const frame = (now: number) => { lastPaint = now; update(now); raf = requestAnimationFrame(frame); };raf = requestAnimationFrame(frame);- return { avatar, timing, destroy() { cancelAnimationFrame(raf); avatar.destroy(); } };+ return { avatar, timing,+ paintPaused(now: number) { return now - lastPaint > 1000; },+ updateIfStalled(now: number) { if (now - previous >= 1000 / 30 - 2) update(now, false); },+ destroy() { cancelAnimationFrame(raf); avatar.destroy(); } };}diff --git a/src/live/clock-worker.ts b/src/live/clock-worker.tsnew file mode 100644index 0000000..e9a3aff--- /dev/null+++ b/src/live/clock-worker.ts@@ -0,0 +1,2 @@+// A worker clock keeps relay updates and health checks independent of page painting.+setInterval(() => self.postMessage(null), 1000 / 30);diff --git a/src/live/face-tracker.ts b/src/live/face-tracker.tsindex b4d10e0..7a4ea2c 100644--- a/src/live/face-tracker.ts+++ b/src/live/face-tracker.ts@@ -1,14 +1,9 @@-import { FaceLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';+import type { FaceResult } from './tracking';-export async function createFaceTracker() {- const files = await FilesetResolver.forVisionTasks('/mediapipe');- const options = { runningMode: 'VIDEO' as const, numFaces: 1, outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true };- let tracker: FaceLandmarker;- let delegate: 'GPU' | 'CPU' = 'GPU';- try { tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: '/mediapipe/face_landmarker.task', delegate } }); }- catch {- delegate = 'CPU';- tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: '/mediapipe/face_landmarker.task', delegate } });- }- return { delegate, detect: (video: HTMLVideoElement, now: number) => tracker.detectForVideo(video, now), close: () => tracker.close() };-}+export type TrackingWorkerMessage =+ | { type: 'ready' | 'delegate'; delegate: 'GPU' | 'CPU' }+ | { type: 'result'; result: FaceResult; elapsed: number }+ | { type: 'consumed' | 'tick' | 'error' };++// Classic worker: the pinned MediaPipe runtime loads its local WASM glue with importScripts.+export function createTrackingWorker() { return new Worker('/mediapipe/tracking-worker.js'); }diff --git a/src/live/i18n.ts b/src/live/i18n.tsindex a442ee5..70e08ee 100644--- a/src/live/i18n.ts+++ b/src/live/i18n.ts@@ -9,6 +9,8 @@ export const liveEn = {obsHelp: 'Keep this page open. Add the URL as a Browser Source in OBS, for example at 1080 × 1080.',loading: 'Loading avatar…', ready: 'Avatar ready', projectError: 'Could not load this project. Open a readable local project in the editor first.',stopped: 'Camera stopped', starting: 'Starting camera…', running: 'Camera ready', tracking: 'Tracking face', lost: 'Face lost · returning to idle',+ backgroundStopped: 'Tracking has stopped while this page is hidden. Bring this window to the front.',+ backgroundSlow: 'Tracking is slow while this page is hidden. Bring this window to the front.',cameraBlocked: 'Camera access was blocked. Allow access in your browser and try again.',cameraUnavailable: 'Camera unavailable. Check the device and whether another app is using it.',modelError: 'Could not start face tracking. Check the local model files and WebGL support, then try again.',@@ -27,6 +29,8 @@ const liveJa: typeof liveEn = {obsHelp: 'この画面を開いたまま、OBSの「ブラウザ」ソースにURLを追加してください。サイズは1080 × 1080などに設定します。',loading: 'アバターを読み込み中…', ready: 'アバターの準備完了', projectError: 'プロジェクトを読み込めませんでした。エディタの一覧から、読み取り可能なローカルプロジェクトを開いてください。',stopped: 'カメラ停止中', starting: 'カメラを開始中…', running: 'カメラの準備完了', tracking: '顔を追跡中', lost: '顔が見つかりません・待機動作に戻ります',+ backgroundStopped: 'この画面が隠れているため追跡が止まっています。このウィンドウを前面に戻してください。',+ backgroundSlow: 'この画面が隠れているため追跡が遅くなっています。このウィンドウを前面に戻してください。',cameraBlocked: 'カメラへのアクセスが拒否されました。ブラウザで許可してから、もう一度お試しください。',cameraUnavailable: 'カメラを使用できません。接続や、別のアプリで使用中でないかを確認してください。',modelError: '顔の追跡を開始できません。ローカルのモデルファイルとWebGLの対応状況を確認してください。',@@ -45,6 +49,8 @@ const liveZh: typeof liveEn = {obsHelp: '保持此页面打开,在OBS中添加“浏览器”来源并粘贴地址,例如将尺寸设为1080 × 1080。',loading: '正在加载形象…', ready: '形象已就绪', projectError: '无法加载项目。请先从编辑器的列表中打开可读取的本地项目。',stopped: '摄像头已停止', starting: '正在启动摄像头…', running: '摄像头已就绪', tracking: '正在追踪面部', lost: '未检测到面部,正在恢复待机动作',+ backgroundStopped: '此页面被隐藏,面部追踪已停止。请将此窗口切换到前台。',+ backgroundSlow: '此页面被隐藏,面部追踪变慢。请将此窗口切换到前台。',cameraBlocked: '摄像头访问被拒绝。请在浏览器中允许访问后重试。',cameraUnavailable: '摄像头不可用。请检查设备连接,或是否被其他应用占用。',modelError: '无法启动面部追踪。请检查本地模型文件和WebGL支持情况,然后重试。',diff --git a/src/live/media.ts b/src/live/media.tsindex 19479dd..cc1ef5c 100644--- a/src/live/media.ts+++ b/src/live/media.ts@@ -1,21 +1,41 @@-import { createFaceTracker } from './face-tracker';+import { createTrackingWorker, type TrackingWorkerMessage } from './face-tracker';import { rmsLevel, type FaceResult } from './tracking';export type CameraState = 'stopped' | 'starting' | 'running' | 'cameraBlocked' | 'cameraUnavailable' | 'modelError';+export type BackgroundTracking = 'backgroundStopped' | 'backgroundSlow' | null;+type TrackProcessor = new (options: { track: MediaStreamTrack; maxBufferSize: number }) => { readable: ReadableStream<VideoFrame> };export class CameraCapture {private generation = 0;private stream?: MediaStream;- private tracker?: Awaited<ReturnType<typeof createFaceTracker>>;- private raf = 0;- readonly timing = { frames: 0, totalMs: 0, maxMs: 0, delegate: '' };+ private worker?: Worker;+ private reader?: ReadableStreamDefaultReader<VideoFrame>;+ private pendingFrame?: VideoFrame;+ private videoCallback = 0;+ private busy = false;+ private lastVideo = -1;+ private lastCallback = -Infinity;+ private started = Infinity;+ private results: number[] = [];+ readonly timing = { frames: 0, totalMs: 0, maxMs: 0, delegate: '', source: '' };constructor(private video: HTMLVideoElement, private onResult: (result: FaceResult, now: number) => void, private onState: (state: CameraState) => void) {}stop() {- this.generation++; cancelAnimationFrame(this.raf);+ this.generation++;+ if (this.videoCallback) this.video.cancelVideoFrameCallback?.(this.videoCallback);+ this.videoCallback = 0;+ void this.reader?.cancel().catch(() => undefined); this.reader = undefined;+ this.pendingFrame?.close(); this.pendingFrame = undefined;+ this.worker?.terminate(); this.worker = undefined;this.stream?.getTracks().forEach(track => track.stop()); this.stream = undefined;- this.tracker?.close(); this.tracker = undefined;this.video.srcObject = null;+ this.busy = false; this.started = Infinity; this.results = [];this.onState('stopped');}+ backgroundStatus(hidden: boolean, now: number): BackgroundTracking {+ this.results = this.results.filter(time => now - time < 2000);+ if (!hidden || now - this.started < 2000) return null;+ if (!this.results.length || now - this.results[this.results.length - 1] > 1000) return 'backgroundStopped';+ return this.results.length / 2 < 15 ? 'backgroundSlow' : null;+ }async start(deviceId: string) {this.stop(); const generation = this.generation;this.onState('starting');@@ -25,34 +45,93 @@ export class CameraCapture {const stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: { width: { ideal: 640 }, height: { ideal: 480 }, frameRate: { ideal: 30, max: 30 }, ...(deviceId ? { deviceId: { exact: deviceId } } : {}) } });if (generation !== this.generation) { stream.getTracks().forEach(track => track.stop()); return; }this.stream = stream; this.video.srcObject = stream;- stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (this.stream === stream) { this.stop(); this.onState('cameraUnavailable'); } }, { once: true });- await this.video.play();- if (generation !== this.generation) return;+ const track = stream.getVideoTracks()[0];+ if (!track) throw new Error('Camera unavailable');+ track.addEventListener('ended', () => { if (this.stream === stream) { this.stop(); this.onState('cameraUnavailable'); } }, { once: true });+ // Preview playback must not gate track processing when the document is hidden.+ void this.video.play().catch(() => undefined);loadingModel = true;- const tracker = await createFaceTracker();- if (generation !== this.generation) { tracker.close(); return; }- this.tracker = tracker; this.timing.delegate = tracker.delegate;- this.onState('running');- let lastFrame = -Infinity, lastVideo = -1;- const frame = (now: number) => {+ const worker = createTrackingWorker(); this.worker = worker;+ const fail = () => { if (generation === this.generation) { this.stop(); this.onState('modelError'); } };+ worker.onerror = fail;+ worker.onmessage = ({ data }: MessageEvent<TrackingWorkerMessage>) => {if (generation !== this.generation) return;- if (now - lastFrame >= 1000 / 30 && this.video.readyState >= 2 && this.video.currentTime !== lastVideo) {- lastFrame = now; lastVideo = this.video.currentTime;- try {- const start = performance.now(), result = tracker.detect(this.video, now), elapsed = performance.now() - start;- this.timing.frames++; this.timing.totalMs += elapsed; this.timing.maxMs = Math.max(this.timing.maxMs, elapsed);- this.onResult(result, now);- } catch { this.stop(); this.onState('modelError'); return; }+ if (data.type === 'ready') {+ this.timing.delegate = data.delegate; this.started = performance.now();+ this.onState('running'); this.startFrames(track, generation);+ } else if (data.type === 'delegate') this.timing.delegate = data.delegate;+ else if (data.type === 'result') {+ const now = performance.now(); this.results.push(now);+ this.results = this.results.filter(time => now - time < 2000);+ this.timing.frames++; this.timing.totalMs += data.elapsed; this.timing.maxMs = Math.max(this.timing.maxMs, data.elapsed);+ this.onResult(data.result, now);+ } else if (data.type === 'consumed') {+ this.busy = false;+ if (this.pendingFrame) { const frame = this.pendingFrame; this.pendingFrame = undefined; this.sendFrame(frame); }}- this.raf = requestAnimationFrame(frame);+ else if (data.type === 'tick' && !this.reader && performance.now() - this.lastCallback > 100) void this.sendBitmap(generation);+ else if (data.type === 'error') fail();};- this.raf = requestAnimationFrame(frame);+ worker.postMessage({ type: 'init' });} catch (error) {if (generation !== this.generation) return;this.stop();this.onState(loadingModel ? 'modelError' : error instanceof DOMException && ['NotAllowedError', 'SecurityError'].includes(error.name) ? 'cameraBlocked' : 'cameraUnavailable');}}+ private startFrames(track: MediaStreamTrack, generation: number) {+ this.lastVideo = -1; this.lastCallback = -Infinity;+ const Processor = (globalThis as typeof globalThis & { MediaStreamTrackProcessor?: TrackProcessor }).MediaStreamTrackProcessor;+ if (Processor) {+ try {+ this.reader = new Processor({ track, maxBufferSize: 1 }).readable.getReader();+ this.timing.source = 'track-processor';+ void this.readFrames(this.reader, generation); return;+ } catch { /* Fall back on browsers that expose an unusable processor. */ }+ }+ this.startVideoCallbacks(generation);+ }+ private async readFrames(reader: ReadableStreamDefaultReader<VideoFrame>, generation: number) {+ try {+ while (generation === this.generation) {+ const { value, done } = await reader.read();+ if (done) break;+ if (generation !== this.generation) { value.close(); continue; }+ if (this.busy) { this.pendingFrame?.close(); this.pendingFrame = value; continue; }+ this.sendFrame(value);+ }+ } catch { /* A failed track processor can still have a playable video preview. */ }+ finally {+ reader.releaseLock();+ if (generation === this.generation) { this.reader = undefined; this.startVideoCallbacks(generation); }+ }+ }+ private startVideoCallbacks(generation: number) {+ if (generation !== this.generation) return;+ this.timing.source = typeof this.video.requestVideoFrameCallback === 'function' ? 'video-frame-callback' : 'worker-timer';+ if (typeof this.video.requestVideoFrameCallback !== 'function') return;+ const frame = () => {+ if (generation !== this.generation) return;+ this.lastCallback = performance.now();+ void this.sendBitmap(generation);+ this.videoCallback = this.video.requestVideoFrameCallback(frame);+ };+ this.videoCallback = this.video.requestVideoFrameCallback(frame);+ }+ private sendFrame(frame: VideoFrame | ImageBitmap) {+ this.busy = true;+ try { this.worker!.postMessage({ type: 'frame', frame, timestamp: 'timestamp' in frame ? frame.timestamp / 1000 : this.video.currentTime * 1000 }, [frame]); }+ catch { frame.close(); this.busy = false; this.stop(); this.onState('modelError'); }+ }+ private async sendBitmap(generation: number) {+ if (this.busy || this.video.readyState < 2 || this.video.currentTime === this.lastVideo) return;+ this.busy = true; this.lastVideo = this.video.currentTime;+ try {+ const bitmap = await createImageBitmap(this.video);+ if (generation !== this.generation) { bitmap.close(); return; }+ this.sendFrame(bitmap);+ } catch { if (generation === this.generation) this.busy = false; }+ }}export type MicState = 'micOff' | 'micStarting' | 'micOn' | 'micBlocked' | 'micUnavailable';diff --git a/src/live/tracking-worker.js b/src/live/tracking-worker.jsnew file mode 100644index 0000000..e3accda--- /dev/null+++ b/src/live/tracking-worker.js@@ -0,0 +1,47 @@+// Camera frames stay in this worker. Only the face pose and timing return to the page.+self.exports = {};+self.importScripts('/mediapipe/vision_bundle.cjs');+const { FaceLandmarker, FilesetResolver } = self.exports;+let tracker, lastFrame = -Infinity, delegate = 'GPU', frames = 0, gpuSamples = 0, gpuMs = 0;+self.onmessage = async ({ data }) => {+ if (data.type === 'init') {+ try {+ const files = await FilesetResolver.forVisionTasks('/mediapipe');+ const options = { runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true };+ try { tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: '/mediapipe/face_landmarker.task', delegate } }); }+ catch {+ delegate = 'CPU';+ tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: '/mediapipe/face_landmarker.task', delegate } });+ }+ self.postMessage({ type: 'ready', delegate });+ // Also wakes the ImageBitmap fallback when video frame callbacks stop in a hidden tab.+ self.setInterval(() => self.postMessage({ type: 'tick' }), 1000 / 30);+ } catch { self.postMessage({ type: 'error' }); }+ } else if (data.type === 'frame') {+ try {+ const now = performance.now();+ if (tracker && data.timestamp - lastFrame >= 1000 / 30 - 2) {+ lastFrame = data.timestamp;+ const start = performance.now(), result = tracker.detectForVideo(data.frame, now), elapsed = performance.now() - start;+ self.postMessage({ type: 'result', elapsed, result: {+ faceLandmarks: result.faceLandmarks.length ? [[]] : [],+ faceBlendshapes: result.faceBlendshapes,+ facialTransformationMatrixes: result.facialTransformationMatrixes,+ } });+ // Some worker GPU backends initialize but run too slowly. Ignore warm-up, then+ // try CPU if sustained inference alone cannot meet the 15 fps target.+ if (delegate === 'GPU' && ++frames > 5) {+ gpuMs += elapsed;+ if (++gpuSamples === 8) {+ if (gpuMs / gpuSamples > 1000 / 15) {+ await tracker.setOptions({ baseOptions: { delegate: 'CPU' } });+ delegate = 'CPU'; self.postMessage({ type: 'delegate', delegate });+ }+ gpuMs = 0; gpuSamples = 0;+ }+ }+ }+ } catch { self.postMessage({ type: 'error' }); }+ finally { data.frame.close(); self.postMessage({ type: 'consumed' }); }+ }+};diff --git a/src/server/mediapipe-assets.ts b/src/server/mediapipe-assets.tsindex b3fb28c..040c664 100644--- a/src/server/mediapipe-assets.ts+++ b/src/server/mediapipe-assets.ts@@ -4,6 +4,8 @@ import type { Plugin } from 'vite';export function mediapipeAssets(root: string): Plugin {const files = new Map([+ ['tracking-worker.js', resolve(root, 'src/live/tracking-worker.js')],+ ['vision_bundle.cjs', resolve(root, 'node_modules/@mediapipe/tasks-vision/vision_bundle.cjs')],...['vision_wasm_internal.js', 'vision_wasm_internal.wasm', 'vision_wasm_nosimd_internal.js', 'vision_wasm_nosimd_internal.wasm'].map(name => [name, resolve(root, 'node_modules/@mediapipe/tasks-vision/wasm', name)] as const),['face_landmarker.task', resolve(root, 'vendor/mediapipe/face_landmarker.task')],@@ -18,7 +20,7 @@ export function mediapipeAssets(root: string): Plugin {if (!path || !['GET', 'HEAD'].includes(req.method ?? '')) { res.writeHead(404); res.end(); return; }try {const data = await readFile(path);- res.writeHead(200, { 'Content-Type': name.endsWith('.js') ? 'text/javascript' : name.endsWith('.wasm') ? 'application/wasm' : 'application/octet-stream', 'X-Content-Type-Options': 'nosniff' });+ res.writeHead(200, { 'Content-Type': /\.(?:js|cjs)$/.test(name) ? 'text/javascript' : name.endsWith('.wasm') ? 'application/wasm' : 'application/octet-stream', 'X-Content-Type-Options': 'nosniff' });res.end(req.method === 'HEAD' ? undefined : data);} catch { res.writeHead(404); res.end(); }});diff --git a/tests/live-media.test.ts b/tests/live-media.test.tsindex 6d9d44b..e77d36e 100644--- a/tests/live-media.test.ts+++ b/tests/live-media.test.ts@@ -1,50 +1,89 @@import { afterEach, beforeEach, expect, test, vi } from 'vitest';import { CameraCapture, MicrophoneCapture } from '../src/live/media';-const createTracker = vi.hoisted(() => vi.fn());-vi.mock('../src/live/face-tracker', () => ({ createFaceTracker: createTracker }));+const createWorker = vi.hoisted(() => vi.fn());+vi.mock('../src/live/face-tracker', () => ({ createTrackingWorker: createWorker }));const empty = { faceLandmarks: [], faceBlendshapes: [], facialTransformationMatrixes: [] };const media = () => {const track = { stop: vi.fn(), addEventListener: vi.fn() };return { track, stream: { getTracks: () => [track], getVideoTracks: () => [track], getAudioTracks: () => [track] } as unknown as MediaStream };};-const video = () => ({ play: vi.fn(async () => undefined), srcObject: null, readyState: 2, currentTime: 0 }) as unknown as HTMLVideoElement;-beforeEach(() => { createTracker.mockReset(); vi.stubGlobal('cancelAnimationFrame', vi.fn()); vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)); });-afterEach(() => vi.unstubAllGlobals());+const video = () => ({ play: vi.fn(async () => undefined), srcObject: null, readyState: 2, currentTime: 0, cancelVideoFrameCallback: vi.fn() }) as unknown as HTMLVideoElement;+const worker = () => ({ postMessage: vi.fn(), terminate: vi.fn(), onmessage: (_event: { data: Record<string, unknown> }) => {}, onerror: () => {} });+beforeEach(() => { createWorker.mockReset(); vi.stubGlobal('MediaStreamTrackProcessor', undefined); });+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });test('stopping while camera permission is pending releases the eventual stream', async () => {const { stream, track } = media(); let resolve!: (stream: MediaStream) => void;vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: () => new Promise<MediaStream>(done => { resolve = done; }) } });const capture = new CameraCapture(video(), vi.fn(), vi.fn());const pending = capture.start(''); capture.stop(); resolve(stream); await pending;- expect(track.stop).toHaveBeenCalledOnce(); expect(createTracker).not.toHaveBeenCalled();+ expect(track.stop).toHaveBeenCalledOnce(); expect(createWorker).not.toHaveBeenCalled();});-test('stopping while the model loads releases camera immediately and closes a late tracker', async () => {- const { stream, track } = media(), close = vi.fn();+test('stopping during model loading terminates the worker and ignores late results', async () => {+ const { stream, track } = media(), thread = worker(), result = vi.fn();vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => stream) } });- let resolve!: (value: unknown) => void;- createTracker.mockImplementation(() => new Promise(done => { resolve = done; }));- const capture = new CameraCapture(video(), vi.fn(), vi.fn());- const pending = capture.start(''); await vi.waitFor(() => expect(createTracker).toHaveBeenCalled());- capture.stop(); expect(track.stop).toHaveBeenCalledOnce();- resolve({ close }); await pending; expect(close).toHaveBeenCalledOnce();+ createWorker.mockReturnValue(thread);+ const source = video(), capture = new CameraCapture(source, result, vi.fn());+ await capture.start(''); expect(thread.postMessage).toHaveBeenCalledWith({ type: 'init' });+ capture.stop(); thread.onmessage({ data: { type: 'result', result: empty, elapsed: 1 } });+ expect(track.stop).toHaveBeenCalledOnce(); expect(thread.terminate).toHaveBeenCalledOnce(); expect(result).not.toHaveBeenCalled(); expect(source.srcObject).toBeNull();+});+test('track processing continues without animation frames, keeps only the latest busy frame and cancels its reader', async () => {+ const { stream, track } = media(), thread = worker();+ vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => stream) } });+ let controller!: ReadableStreamDefaultController<VideoFrame>;+ const cancel = vi.fn(), readable = new ReadableStream<VideoFrame>({ start(value) { controller = value; }, cancel });+ vi.stubGlobal('MediaStreamTrackProcessor', class { readable = readable; });+ createWorker.mockReturnValue(thread);+ const capture = new CameraCapture(video(), vi.fn(), vi.fn()); await capture.start('');+ thread.onmessage({ data: { type: 'ready', delegate: 'CPU' } });+ const first = { close: vi.fn() } as unknown as VideoFrame, dropped = { close: vi.fn() } as unknown as VideoFrame;+ controller.enqueue(first); await vi.waitFor(() => expect(thread.postMessage).toHaveBeenCalledWith({ type: 'frame', frame: first, timestamp: 0 }, [first]));+ controller.enqueue(dropped);+ const latest = { close: vi.fn() } as unknown as VideoFrame;+ controller.enqueue(latest); await vi.waitFor(() => expect(dropped.close).toHaveBeenCalledOnce());+ thread.onmessage({ data: { type: 'consumed' } });+ expect(thread.postMessage).toHaveBeenLastCalledWith({ type: 'frame', frame: latest, timestamp: 0 }, [latest]);+ expect(capture.timing.source).toBe('track-processor');+ capture.stop(); expect(cancel).toHaveBeenCalledOnce(); expect(track.stop).toHaveBeenCalledOnce();+});+test('worker timer backs up stalled video callbacks and releases late bitmaps after stop', async () => {+ const { stream } = media(), thread = worker(), source = video();+ vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => stream) } });+ source.requestVideoFrameCallback = vi.fn(() => 7);+ let resolve!: (frame: ImageBitmap) => void;+ vi.stubGlobal('createImageBitmap', vi.fn(() => new Promise<ImageBitmap>(done => { resolve = done; })));+ createWorker.mockReturnValue(thread);+ const capture = new CameraCapture(source, vi.fn(), vi.fn()); await capture.start('');+ thread.onmessage({ data: { type: 'ready', delegate: 'GPU' } });+ thread.onmessage({ data: { type: 'tick' } }); thread.onmessage({ data: { type: 'tick' } });+ expect(createImageBitmap).toHaveBeenCalledOnce();+ capture.stop(); const bitmap = { close: vi.fn() } as unknown as ImageBitmap; resolve(bitmap);+ await vi.waitFor(() => expect(bitmap.close).toHaveBeenCalledOnce());+ expect(source.cancelVideoFrameCallback).toHaveBeenCalledWith(7);+ expect(thread.postMessage).toHaveBeenCalledTimes(1);});-test('camera inference is capped at 30 Hz, skips repeated frames and closes resources', async () => {- const { stream, track } = media(), close = vi.fn(), detect = vi.fn(() => empty), state = vi.fn();- let frame!: FrameRequestCallback;- vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { frame = callback; return 1; });+test('hidden-page warnings depend on actual inference frequency and clear on recovery or stop', async () => {+ const { stream } = media(), thread = worker(), result = vi.fn();vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => stream) } });- createTracker.mockResolvedValue({ close, detect, delegate: 'CPU' });- const source = video(), capture = new CameraCapture(source, vi.fn(), state);- await capture.start('device'); frame(0); source.currentTime = 1; frame(10); frame(34); frame(68);- expect(detect).toHaveBeenCalledTimes(2); expect(capture.timing.delegate).toBe('CPU');- capture.stop(); expect(track.stop).toHaveBeenCalledOnce(); expect(close).toHaveBeenCalledOnce(); expect(source.srcObject).toBeNull();+ createWorker.mockReturnValue(thread); const clock = vi.spyOn(performance, 'now').mockReturnValue(0);+ const capture = new CameraCapture(video(), result, vi.fn()); await capture.start('');+ thread.onmessage({ data: { type: 'ready', delegate: 'CPU' } });+ expect(capture.backgroundStatus(true, 1000)).toBeNull();+ expect(capture.backgroundStatus(true, 2100)).toBe('backgroundStopped');+ clock.mockReturnValue(2200); thread.onmessage({ data: { type: 'result', result: empty, elapsed: 2 } });+ expect(capture.backgroundStatus(true, 2200)).toBe('backgroundSlow');+ expect(capture.backgroundStatus(false, 2200)).toBeNull();+ for (let now = 2233; now <= 4200; now += 33) { clock.mockReturnValue(now); thread.onmessage({ data: { type: 'result', result: empty, elapsed: 2 } }); }+ expect(capture.backgroundStatus(true, 4200)).toBeNull();+ capture.stop(); expect(capture.backgroundStatus(true, 9000)).toBeNull();});-test('permission denial produces a distinct camera status without creating a tracker', async () => {+test('permission denial produces a distinct camera status without starting a worker', async () => {const state = vi.fn();vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => { throw new DOMException('', 'NotAllowedError'); }) } });await new CameraCapture(video(), vi.fn(), state).start('');- expect(state).toHaveBeenLastCalledWith('cameraBlocked'); expect(createTracker).not.toHaveBeenCalled();+ expect(state).toHaveBeenLastCalledWith('cameraBlocked'); expect(createWorker).not.toHaveBeenCalled();});test('microphone permission cancellation releases tracks and permission denial is reported', async () => {const { stream, track } = media(); let resolve!: (stream: MediaStream) => void;diff --git a/tests/live-worker.test.ts b/tests/live-worker.test.tsnew file mode 100644index 0000000..04007c0--- /dev/null+++ b/tests/live-worker.test.ts@@ -0,0 +1,50 @@+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+import { expect, test, vi } from 'vitest';++const source = readFileSync(new URL('../src/live/tracking-worker.js', import.meta.url), 'utf8');+test('worker falls back from GPU to CPU, keeps frames local and closes both accepted and skipped frames', async () => {+ const result = { faceLandmarks: [[{ x: 0.5, y: 0.5 }]], faceBlendshapes: [], facialTransformationMatrixes: [] };+ const detectForVideo = vi.fn(() => result), create = vi.fn().mockRejectedValueOnce(new Error('GPU unavailable')).mockResolvedValue({ detectForVideo });+ const postMessage = vi.fn(), now = vi.fn(() => 0), tick = vi.fn();+ const scope = {+ exports: {}, postMessage, setInterval: tick,+ importScripts: vi.fn((url: string) => {+ expect(url).toBe('/mediapipe/vision_bundle.cjs');+ scope.exports = { FaceLandmarker: { createFromOptions: create }, FilesetResolver: { forVisionTasks: async (path: string) => { expect(path).toBe('/mediapipe'); return {}; } } };+ }),+ onmessage: async (_event: { data: Record<string, unknown> }) => {},+ };+ runInNewContext(source, { self: scope, performance: { now } });+ await scope.onmessage({ data: { type: 'init' } });+ expect(create.mock.calls.map(call => call[1].baseOptions.delegate)).toEqual(['GPU', 'CPU']);+ expect(create.mock.calls[1][1].baseOptions.modelAssetPath).toBe('/mediapipe/face_landmarker.task');+ expect(postMessage).toHaveBeenCalledWith({ type: 'ready', delegate: 'CPU' });+ const frame = { close: vi.fn() };+ await scope.onmessage({ data: { type: 'frame', frame, timestamp: 0 } });+ await scope.onmessage({ data: { type: 'frame', frame, timestamp: 0 } });+ expect(detectForVideo).toHaveBeenCalledTimes(1); expect(frame.close).toHaveBeenCalledTimes(2);+ expect(postMessage).toHaveBeenCalledWith({ type: 'result', elapsed: 0, result: { ...result, faceLandmarks: [[]] } });+ detectForVideo.mockImplementation(() => { throw new Error('Bad frame'); }); now.mockReturnValue(40);+ await scope.onmessage({ data: { type: 'frame', frame, timestamp: 40 } });+ expect(frame.close).toHaveBeenCalledTimes(3); expect(postMessage).toHaveBeenCalledWith({ type: 'error' });+ expect(postMessage).toHaveBeenLastCalledWith({ type: 'consumed' });+ tick.mock.calls[0][0](); expect(postMessage).toHaveBeenLastCalledWith({ type: 'tick' });+});++test('worker changes an initialized but persistently slow GPU to CPU once after warm-up', async () => {+ let now = 0;+ const setOptions = vi.fn(async () => undefined), postMessage = vi.fn();+ const tracker = { setOptions, detectForVideo: () => { now += 100; return { faceLandmarks: [], faceBlendshapes: [], facialTransformationMatrixes: [] }; } };+ const scope = { exports: {}, postMessage, setInterval: vi.fn(),+ importScripts: () => { scope.exports = { FaceLandmarker: { createFromOptions: async () => tracker }, FilesetResolver: { forVisionTasks: async () => ({}) } }; },+ onmessage: async (_event: { data: Record<string, unknown> }) => {},+ };+ runInNewContext(source, { self: scope, performance: { now: () => now } });+ await scope.onmessage({ data: { type: 'init' } });+ for (let i = 0; i < 12; i++) await scope.onmessage({ data: { type: 'frame', frame: { close() {} }, timestamp: i * 100 } });+ expect(setOptions).not.toHaveBeenCalled();+ for (let i = 12; i < 30; i++) await scope.onmessage({ data: { type: 'frame', frame: { close() {} }, timestamp: i * 100 } });+ expect(setOptions).toHaveBeenCalledExactlyOnceWith({ baseOptions: { delegate: 'CPU' } });+ expect(postMessage).toHaveBeenCalledWith({ type: 'delegate', delegate: 'CPU' });+});