Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add local webcam tracking and microphone controls
shinshin8694e9a077010b
diff --git a/live.html b/live.htmlnew file mode 100644index 0000000..528155d--- /dev/null+++ b/live.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'">+ <title>Mesh Avatar Studio · Live</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/live/main.tsx"></script>+ </body>+</html>diff --git a/package-lock.json b/package-lock.jsonindex d729a34..05dc174 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,6 +8,7 @@"name": "mesh-avatar-studio","version": "0.1.0","dependencies": {+ "@mediapipe/tasks-vision": "0.10.21","react": "^19.1.0","react-dom": "^19.1.0"},@@ -1025,6 +1026,12 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@mediapipe/tasks-vision": {+ "version": "0.10.21",+ "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.21.tgz",+ "integrity": "sha512-TuhKH+credq4zLksGbYrnvJ1aLIWMc5r0UHwzxzql4BHECJwIAoBR61ZrqwGOW6ZmSBIzU1t4VtKj8hbxFaKeA==",+ "license": "Apache-2.0"+ },"node_modules/@napi-rs/lzma-linux-x64-gnu": {"version": "1.5.1","resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",diff --git a/package.json b/package.jsonindex 94146a4..b503d4e 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"render-poses": "node --experimental-strip-types tools/render-poses.mjs"},"dependencies": {+ "@mediapipe/tasks-vision": "0.10.21","react": "^19.1.0","react-dom": "^19.1.0"},@@ -21,16 +22,16 @@"@eslint/js": "^9.0.0","@playwright/test": "^1.55.0","@types/node": "^24.0.0",+ "@types/pngjs": "^6.0.0","@types/react": "^19.0.0","@types/react-dom": "^19.0.0","@vitejs/plugin-react": "^5.0.0","eslint": "^9.0.0","globals": "^16.0.0",+ "pngjs": "^7.0.0","typescript": "^5.9.0","typescript-eslint": "^8.0.0","vite": "^7.0.0",- "vitest": "^3.2.0",- "pngjs": "^7.0.0",- "@types/pngjs": "^6.0.0"+ "vitest": "^3.2.0"}}diff --git a/src/editor/App.tsx b/src/editor/App.tsxindex 13eca10..b08ccb9 100644--- a/src/editor/App.tsx+++ b/src/editor/App.tsx@@ -23,6 +23,7 @@ import { CopyButton } from './CopyButton';import { readRecent, addRecent, saveRecent, REOPEN_KEY, pickDirectory, hasDirectoryPicker, directoryFiles,keepDirectory, restoreDirectory, forgetDirectory, clearDirectories, type RecentProject, type ProjectDirectory } from './recent-projects';import './style.css';+import { liveText } from '../live/i18n';type EditorError = { kind: 'invalidRig' | 'invalidFolder' | 'missingFolderFiles' | 'unreadableFolder' | 'unreadableProject' | 'invalidValue' | 'saveError' | 'revealError' | 'copyError' | 'continueError'; paths: string[] };function errorPaths(value: string) { return [...new Set(value.match(/rig(?:\.[\w]+|\[\d+\])+/g) ?? [])]; }@@ -357,6 +358,9 @@ function Workspace() {<button className="icon-button" aria-label={t.undo} title={`${t.undo} · ⌘Z`} disabled={!history.canUndo || job !== null || opening} onClick={() => setRig(history.undo())}><Icon name="undo" /></button><button className="icon-button" aria-label={t.redo} title={`${t.redo} · ⇧⌘Z`} disabled={!history.canRedo || job !== null || opening} onClick={() => setRig(history.redo())}><Icon name="redo" /></button><span className="toolbar-divider" />+ <a className="live-link" href={localProject || listedProject || !pickedName ? `/live.html?project=${encodeURIComponent(localProject?.name ?? listedProject?.name ?? 'sample-miko-qipao')}` : undefined}+ target="_blank" rel="noreferrer" aria-disabled={!!pickedName && !localProject && !listedProject}+ title={pickedName && !localProject && !listedProject ? liveText[language].liveUnavailable : liveText[language].title}>{liveText[language].title}</a><button className="icon-button" aria-label={t.help} title={t.help} aria-expanded={help} onClick={() => setHelp(current => !current)}><Icon name="help" /></button><div className="language-toggle" role="group" aria-label={t.language}><button aria-label={t.english} aria-pressed={language === 'en'} onClick={() => setLanguage('en')}>{t.enCode}</button>diff --git a/src/editor/style.css b/src/editor/style.cssindex d64e7ea..06ba305 100644--- a/src/editor/style.css+++ b/src/editor/style.css@@ -27,6 +27,8 @@ button.primary:hover { color: white; background: #1d4ed8; }.brand p { margin: 2px 0 0; color: var(--muted); font-size: 12px; }.toolbar nav { display: flex; align-items: center; gap: 8px; }.toolbar-divider { height: 24px; width: 1px; background: var(--line); }+.live-link { color: var(--accent); text-decoration: none; padding: 6px; white-space: nowrap; }+.live-link[aria-disabled="true"] { color: var(--muted); cursor: default; }.language-toggle { display: flex; border: 1px solid var(--line); border-radius: 8px; padding: 2px; background: var(--surface); }.language-toggle button { border: 0; padding: 6px 10px; border-radius: 6px; font-size: 12px; }.language-toggle button[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); font-weight: 600; }diff --git a/src/engine/createMeshAvatar.js b/src/engine/createMeshAvatar.jsindex d7d83a5..d6616d2 100644--- a/src/engine/createMeshAvatar.js+++ b/src/engine/createMeshAvatar.js@@ -139,15 +139,17 @@ export async function createMeshAvatarImpl(canvas, options) {const listeners = new Set();motion.onMotion = id => { for (const fn of listeners) fn(id); };- let parameters = {};+ let parameters = {}, parameterWeight = 1, lastParameters = {};const tmp = [0, 0];function tick(dt) {- const P = { ...motion.update(dt), ...parameters };+ 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.if (motion.lipOpen !== null) {P.mouthOpen = motion.P.mouthOpen;- P.mouthForm = motion.P.mouthForm;+ if (!options.preserveMouthForm || parameters.mouthForm === undefined) P.mouthForm = motion.P.mouthForm;}+ lastParameters = P;const phys = physics.step(P, dt);const bp = baseMesh.pos, br = baseMesh.rest;@@ -208,7 +210,8 @@ export async function createMeshAvatarImpl(canvas, options) {return {motions: motionList,- setParameters(values) { parameters = { ...values }; },+ setParameters(values, weight = 1) { parameters = { ...values }; parameterWeight = Math.min(1, Math.max(0, Number(weight) || 0)); },+ getParameters() { return { ...lastParameters }; },/** 0..1 loudness of the voice being played (e.g. normalised RMS). */setVoiceLevel(v) { motion.setVoiceLevel(v); },/** true while TTS audio is playing: idle motions pause and the head nods along. */diff --git a/src/engine/index.ts b/src/engine/index.tsindex 01cf9a8..485dbd4 100644--- a/src/engine/index.ts+++ b/src/engine/index.ts@@ -10,10 +10,12 @@ export interface MeshAvatarOptions {padTop?: number;padSide?: number;fit?: 'contain' | 'cover';+ preserveMouthForm?: boolean;}export interface MeshAvatar {readonly motions: { id: string; label: string; idle: boolean }[];- setParameters(parameters: Record<string, number>): void;+ setParameters(parameters: Record<string, number>, weight?: number): void;+ getParameters(): Record<string, number>;setVoiceLevel(value: number): void;setSpeaking(on: boolean): void;setEmotion(tag: string | null, options?: { playMotion?: boolean }): void;diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsxnew file mode 100644index 0000000..55e2913--- /dev/null+++ b/src/live/LiveApp.tsx@@ -0,0 +1,85 @@+import { useEffect, useRef, useState } from 'react';+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 { liveText } from './i18n';++export function LiveApp() {+ const { language, setLanguage } = useI18n(), t = liveText[language];+ const [settings, setSettings] = useState(() => viewSettings(location.search));+ const [options, setOptions] = useState<TrackingOptions>({ mirror: true, sensitivity: 1, smoothing: 0.35 });+ const [cameraState, setCameraState] = useState<CameraState>('stopped');+ const [micState, setMicState] = useState<MicState>('micOff');+ const [tracking, setTracking] = useState(false), [showCamera, setShowCamera] = useState(true);+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]), [cameraId, setCameraId] = useState(''), [micId, setMicId] = useState('');+ 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 canvas = useRef<HTMLCanvasElement>(null), video = useRef<HTMLVideoElement>(null);+ const camera = useRef<CameraCapture | null>(null), microphone = useRef<MicrophoneCapture | null>(null);+ const pose = useRef(new FacePose());+ const controls = useRef({ options, gain, micState, cameraState }); controls.current = { options, gain, micState, cameraState };+ const refreshDevices = () => { void navigator.mediaDevices?.enumerateDevices().then(setDevices).catch(() => undefined); };+ useEffect(() => {+ const capture = new CameraCapture(video.current!, (result, now) => pose.current.update(result, now), state => { setCameraState(state); if (state !== 'running') setTracking(false); });+ const mic = new MicrophoneCapture(setMicState);+ camera.current = capture; microphone.current = mic;+ refreshDevices(); navigator.mediaDevices?.addEventListener('devicechange', refreshDevices);+ const stop = () => { capture.stop(); mic.stop(); pose.current.reset(); };+ window.addEventListener('pagehide', stop);+ return () => { stop(); navigator.mediaDevices?.removeEventListener('devicechange', refreshDevices); window.removeEventListener('pagehide', stop); };+ }, []);+ useEffect(() => {+ let cancelled = false, view: Awaited<ReturnType<typeof createAvatarView>> | undefined;+ setViewState('loading');+ void createAvatarView(canvas.current!, settings, (avatar, now, dt) => {+ const control = controls.current, sampled = pose.current.sample(now, dt, control.options);+ setTracking(sampled.tracking);+ avatar.setAutoIdle(!sampled.tracking); avatar.setAutoMotion(!sampled.tracking);+ avatar.setParameters(sampled.params, sampled.weight);+ const micOn = control.micState === 'micOn';+ avatar.setSpeaking(micOn); avatar.setVoiceLevel(micOn ? microphone.current?.level(control.gain) ?? 0 : 0);+ }).then(value => { if (cancelled) value.destroy(); else { view = value; setViewState('ready'); } }).catch(() => { if (!cancelled) setViewState('projectError'); });+ return () => { cancelled = true; view?.destroy(); };+ }, [settings.project, settings.fit]);+ const cameraActive = cameraState === 'starting' || cameraState === 'running';+ const micActive = micState === 'micStarting' || micState === 'micOn';+ const url = streamUrl(settings, location.origin);+ const status = cameraState === 'running' ? tracking ? 'tracking' : 'lost' : cameraState;+ return <main className="live-app">+ <header className="live-header"><div><a href="/">{t.back}</a><h1>Mesh Avatar Studio <span>{t.title}</span></h1></div>+ <div className="live-languages">{(['en', 'ja', 'zh'] as const).map(lang => <button key={lang} aria-pressed={language === lang} onClick={() => setLanguage(lang)}>{({ en: 'English', ja: '日本語', zh: '简体中文' })[lang]}</button>)}</div>+ </header>+ <div className="live-layout"><section className="live-view"><div className="live-preview checkerboard" style={{ backgroundColor: settings.background, backgroundImage: settings.background === 'transparent' ? undefined : 'none' }}>+ <canvas ref={canvas} data-testid="live-avatar" />+ </div><p role="status" className={viewState === 'projectError' ? 'live-error' : ''}>{t[viewState]} · {settings.project}</p></section>+ <aside className="live-controls">+ <section><h2>{t.camera}</h2><label>{t.device}<select aria-label={t.camera} value={cameraId} disabled={cameraActive} onChange={event => setCameraId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'videoinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.camera} ${i + 1}`}</option>)}</select></label>+ <div className="live-buttons"><button className="live-primary" disabled={!cameraActive && viewState !== 'ready'} onClick={() => {+ setCalibrated(false); pose.current.reset();+ 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>+ <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>+ <label>{t.smoothing}<input type="range" min="0" max="1" step="0.05" value={options.smoothing} onChange={event => setOptions(current => ({ ...current, smoothing: Number(event.target.value) }))} /></label>+ <label className="live-check"><input type="checkbox" checked={showCamera} onChange={event => setShowCamera(event.target.checked)} />{t.cameraPreview}</label>+ <video ref={video} autoPlay muted playsInline className={showCamera ? 'camera-preview' : 'camera-preview camera-hidden'} style={{ transform: options.mirror ? 'scaleX(-1)' : undefined }} aria-label={t.cameraPreview} />+ </section>+ <section><h2>{t.microphone}</h2><label className="live-check"><input type="checkbox" checked={micActive} disabled={!micActive && viewState !== 'ready'} onChange={event => { if (event.target.checked) void microphone.current?.start(micId).then(refreshDevices); else microphone.current?.stop(); }} />{t.microphone}</label>+ <select aria-label={t.microphone} value={micId} disabled={micActive} onChange={event => setMicId(event.target.value)}><option value="">{t.defaultDevice}</option>{devices.filter(device => device.kind === 'audioinput' && device.deviceId).map((device, i) => <option key={device.deviceId} value={device.deviceId}>{device.label || `${t.microphone} ${i + 1}`}</option>)}</select>+ <label>{t.gain}<input type="range" min="0.25" max="5" step="0.05" value={gain} onChange={event => setGain(Number(event.target.value))} /></label><small role="status">{t[micState]}</small>+ </section>+ <section><h2>{t.background}</h2><select aria-label={t.background} value={settings.background} onChange={event => setSettings(current => ({ ...current, background: backgroundColor(event.target.value) }))}>+ <option value="transparent">{t.transparent}</option><option value="#00ff00">{t.green}</option><option value="#0000ff">{t.blue}</option>{!['transparent', '#00ff00', '#0000ff'].includes(settings.background) && <option value={settings.background}>{t.custom}</option>}+ </select><label>{t.custom}<input type="color" value={settings.background === 'transparent' ? '#ffffff' : settings.background} onChange={event => setSettings(current => ({ ...current, background: event.target.value }))} /></label>+ <label>{t.fit}<select value={settings.fit} onChange={event => setSettings(current => ({ ...current, fit: event.target.value as 'contain' | 'cover' }))}><option value="contain">{t.contain}</option><option value="cover">{t.cover}</option></select></label>+ <button className="live-primary" onClick={() => { void navigator.clipboard.writeText(url).then(() => setCopyState('copied')).catch(() => setCopyState('copyError')); }}>{t.obs}</button>+ {copyState && <p role="status">{t[copyState]}</p>}<input className="obs-url" aria-label={t.obs} readOnly value={url} onFocus={event => event.target.select()} /><small>{t.obsHelp}</small>+ </section><p className="live-privacy">{t.privacy}</p>+ </aside></div>+ </main>;+}diff --git a/src/live/avatar-view.ts b/src/live/avatar-view.tsindex d4a4b27..de07f9d 100644--- a/src/live/avatar-view.ts+++ b/src/live/avatar-view.ts@@ -7,12 +7,13 @@ import { SAMPLE_PROJECT, type ViewSettings } from './settings';export const neutralParameters: Record<string, number> = Object.fromEntries(PARAMS.map(param => [param.id, param.def]));export interface FrameTiming { frames: number; totalMs: number; maxMs: number }export async function createAvatarView(canvas: HTMLCanvasElement, settings: ViewSettings,- beforeFrame?: (avatar: MeshAvatar, now: number, dt: number) => void) {+ beforeFrame?: (avatar: MeshAvatar, now: number, dt: number) => void,+ afterFrame?: (avatar: MeshAvatar, now: number) => void) {canvas.dataset.state = 'loading';const projects = await localProjects(), project = projects?.find(entry => entry.name === settings.project);if (project?.error || (!project && settings.project !== SAMPLE_PROJECT)) throw new Error('Project unavailable');const loaded = project ? await openLocalProject(project) : { rig: fixture, assets: undefined };- const avatar = await createMeshAvatar(canvas, { rig: loaded.rig!, assets: loaded.assets, manual: true, fit: settings.fit });+ const avatar = await createMeshAvatar(canvas, { rig: loaded.rig!, assets: loaded.assets, manual: true, fit: settings.fit, preserveMouthForm: true });avatar.setAutoIdle(settings.idle); avatar.setAutoMotion(settings.idle);if (!settings.idle) avatar.setParameters(neutralParameters);canvas.dataset.state = 'ready';@@ -25,6 +26,7 @@ export async function createAvatarView(canvas: HTMLCanvasElement, settings: Viewavatar.advance(dt, 1 / dt);const elapsed = performance.now() - start;timing.frames++; timing.totalMs += elapsed; timing.maxMs = Math.max(timing.maxMs, elapsed);+ afterFrame?.(avatar, now);raf = requestAnimationFrame(frame);};raf = requestAnimationFrame(frame);diff --git a/src/live/face-tracker.ts b/src/live/face-tracker.tsnew file mode 100644index 0000000..b4d10e0--- /dev/null+++ b/src/live/face-tracker.ts@@ -0,0 +1,14 @@+import { FaceLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';++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() };+}diff --git a/src/live/i18n.ts b/src/live/i18n.tsnew file mode 100644index 0000000..a442ee5--- /dev/null+++ b/src/live/i18n.ts@@ -0,0 +1,55 @@+export const liveEn = {+ title: 'Live', back: 'Back to editor', camera: 'Camera', device: 'Device', defaultDevice: 'Default device',+ start: 'Start camera', stop: 'Stop camera', calibrate: 'Calibrate', calibrated: 'Neutral pose saved',+ calibrateHint: 'Look straight at the camera with relaxed eyes and a closed mouth, then calibrate.',+ mirror: 'Mirror', sensitivity: 'Sensitivity', smoothing: 'Smoothing', cameraPreview: 'Show camera preview',+ microphone: 'Microphone lip sync', gain: 'Microphone gain', privacy: 'Camera video and microphone audio stay on this machine. Only avatar motion values are shared with the stream view.',+ background: 'Background', transparent: 'Transparent', green: 'Green', blue: 'Blue', custom: 'Custom color',+ fit: 'Framing', contain: 'Fit whole avatar', cover: 'Fill frame', obs: 'Copy OBS URL', copied: 'URL copied', copyError: 'Could not copy. Select and copy the URL below.',+ 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',+ 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.',+ micOff: 'Microphone off', micStarting: 'Starting microphone…', micOn: 'Microphone on',+ micBlocked: 'Microphone access was blocked. Allow access in your browser and try again.', micUnavailable: 'Microphone unavailable. Check the selected device.',+ liveUnavailable: 'Open this project from the local project list before using Live.',+};+const liveJa: typeof liveEn = {+ title: '配信', back: 'エディタに戻る', camera: 'カメラ', device: 'デバイス', defaultDevice: '既定のデバイス',+ start: 'カメラを開始', stop: 'カメラを停止', calibrate: '正面の姿勢を登録', calibrated: '正面の姿勢を登録しました',+ calibrateHint: '目と口の力を抜き、口を閉じてカメラに正面を向いた状態で登録してください。',+ mirror: '左右反転', sensitivity: '感度', smoothing: '動きをなめらかにする', cameraPreview: 'カメラ映像を表示',+ microphone: 'マイクで口を動かす', gain: 'マイクの感度', privacy: 'カメラ映像とマイクの音声は、この端末内で処理します。配信用画面に渡すのはアバターの動きの数値だけです。',+ background: '背景', transparent: '透明', green: '緑', blue: '青', custom: '指定した色',+ fit: '画面への収め方', contain: '全体を表示', cover: '画面を埋める', obs: 'OBS用URLをコピー', copied: 'URLをコピーしました', copyError: 'コピーできませんでした。下のURLを選択してコピーしてください。',+ obsHelp: 'この画面を開いたまま、OBSの「ブラウザ」ソースにURLを追加してください。サイズは1080 × 1080などに設定します。',+ loading: 'アバターを読み込み中…', ready: 'アバターの準備完了', projectError: 'プロジェクトを読み込めませんでした。エディタの一覧から、読み取り可能なローカルプロジェクトを開いてください。',+ stopped: 'カメラ停止中', starting: 'カメラを開始中…', running: 'カメラの準備完了', tracking: '顔を追跡中', lost: '顔が見つかりません・待機動作に戻ります',+ cameraBlocked: 'カメラへのアクセスが拒否されました。ブラウザで許可してから、もう一度お試しください。',+ cameraUnavailable: 'カメラを使用できません。接続や、別のアプリで使用中でないかを確認してください。',+ modelError: '顔の追跡を開始できません。ローカルのモデルファイルとWebGLの対応状況を確認してください。',+ micOff: 'マイク停止中', micStarting: 'マイクを開始中…', micOn: 'マイク使用中',+ micBlocked: 'マイクへのアクセスが拒否されました。ブラウザで許可してから、もう一度お試しください。', micUnavailable: 'マイクを使用できません。選択したデバイスを確認してください。',+ liveUnavailable: '配信するには、エディタのローカルプロジェクト一覧からこのプロジェクトを開いてください。',+};+const liveZh: typeof liveEn = {+ title: '直播', back: '返回编辑器', camera: '摄像头', device: '设备', defaultDevice: '默认设备',+ start: '启动摄像头', stop: '停止摄像头', calibrate: '校准', calibrated: '已保存中立姿态',+ calibrateHint: '正视摄像头,放松眼睛并闭上嘴,然后校准。',+ mirror: '镜像', sensitivity: '灵敏度', smoothing: '动作平滑度', cameraPreview: '显示摄像头画面',+ microphone: '麦克风口型同步', gain: '麦克风增益', privacy: '摄像头画面和麦克风音频仅在本机处理。直播画面只接收虚拟形象的动作数值。',+ background: '背景', transparent: '透明', green: '绿色', blue: '蓝色', custom: '自定义颜色',+ fit: '画面适配', contain: '显示完整形象', cover: '填满画面', obs: '复制OBS地址', copied: '地址已复制', copyError: '复制失败。请选中并复制下方地址。',+ obsHelp: '保持此页面打开,在OBS中添加“浏览器”来源并粘贴地址,例如将尺寸设为1080 × 1080。',+ loading: '正在加载形象…', ready: '形象已就绪', projectError: '无法加载项目。请先从编辑器的列表中打开可读取的本地项目。',+ stopped: '摄像头已停止', starting: '正在启动摄像头…', running: '摄像头已就绪', tracking: '正在追踪面部', lost: '未检测到面部,正在恢复待机动作',+ cameraBlocked: '摄像头访问被拒绝。请在浏览器中允许访问后重试。',+ cameraUnavailable: '摄像头不可用。请检查设备连接,或是否被其他应用占用。',+ modelError: '无法启动面部追踪。请检查本地模型文件和WebGL支持情况,然后重试。',+ micOff: '麦克风已关闭', micStarting: '正在启动麦克风…', micOn: '麦克风已开启',+ micBlocked: '麦克风访问被拒绝。请在浏览器中允许访问后重试。', micUnavailable: '麦克风不可用。请检查所选设备。',+ liveUnavailable: '请先从本地项目列表打开此项目,再使用直播功能。',+};+export const liveText = { en: liveEn, ja: liveJa, zh: liveZh };diff --git a/src/live/live.css b/src/live/live.cssnew file mode 100644index 0000000..f2ed276--- /dev/null+++ b/src/live/live.css@@ -0,0 +1,36 @@+:root { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #22344d; background: #f3f5f8; font-size: 14px; }+* { box-sizing: border-box; }+body { margin: 0; }+button, select, input { font: inherit; }+button, select, .obs-url { border: 1px solid #c8d3e2; border-radius: 7px; background: white; color: inherit; padding: 8px 10px; }+button { cursor: pointer; }+button:disabled { opacity: .5; cursor: default; }+button:focus-visible, select:focus-visible, input:focus-visible { outline: 2px solid #3977d8; outline-offset: 2px; }+button[aria-pressed="true"] { color: #175db8; background: #e6efff; }+a { color: #235fae; }+h1 { margin: 6px 0 0; font-size: 20px; } h1 span { color: #61799a; margin-left: 8px; font-weight: 500; }+h2 { font-size: 15px; margin: 0 0 12px; }+p { line-height: 1.5; } small { display: block; color: #546a87; line-height: 1.5; }+.live-app { padding: 18px 24px; max-width: 1800px; margin: auto; }+.live-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; gap: 12px; }+.live-languages { display: flex; gap: 4px; }+.live-layout { display: grid; grid-template-columns: minmax(0, 1fr) 330px; gap: 22px; align-items: start; }+.live-view { position: sticky; top: 18px; min-width: 0; }+.live-preview { height: calc(100dvh - 150px); min-height: 320px; border: 1px solid #d5dfeb; border-radius: 12px; overflow: hidden; }+.checkerboard { background-image: conic-gradient(#e1e5eb 25%, #f8f9fb 0 50%, #e1e5eb 0 75%, #f8f9fb 0); background-size: 24px 24px; }+.live-preview canvas { display: block; width: 100%; height: 100%; }+.live-controls { display: flex; flex-direction: column; gap: 14px; }+.live-controls section { padding: 16px; border: 1px solid #d5dfeb; border-radius: 12px; background: white; }+.live-controls label { display: flex; flex-direction: column; gap: 7px; margin: 12px 0; }+.live-controls select, .obs-url { width: 100%; min-width: 0; }+.live-controls .live-check { flex-direction: row; align-items: center; }+input[type="range"] { width: 100%; accent-color: #3977d8; }+input[type="color"] { width: 100%; height: 32px; border: 0; padding: 0; }+.live-buttons { display: flex; flex-wrap: wrap; gap: 8px; }+.live-primary { background: #2d67b2; color: white; border-color: #2d67b2; }+.camera-preview { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: 7px; background: #162132; }+.camera-hidden { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }+.obs-url { font-size: 11px; margin: 10px 0; }+.live-privacy { color: #546a87; font-size: 12px; margin: 0 4px; }+.live-error { color: #aa2020; }+@media (max-width: 800px) { .live-app { padding: 12px; } .live-layout { grid-template-columns: 1fr; } .live-view { position: static; } .live-preview { height: 55dvh; } .live-header { flex-wrap: wrap; } }diff --git a/src/live/main.tsx b/src/live/main.tsxnew file mode 100644index 0000000..bf6a4f5--- /dev/null+++ b/src/live/main.tsx@@ -0,0 +1,5 @@+import { createRoot } from 'react-dom/client';+import { I18nProvider } from '../editor/i18n';+import { LiveApp } from './LiveApp';+import './live.css';+createRoot(document.getElementById('root')!).render(<I18nProvider><LiveApp /></I18nProvider>);diff --git a/src/live/media.ts b/src/live/media.tsnew file mode 100644index 0000000..19479dd--- /dev/null+++ b/src/live/media.ts@@ -0,0 +1,96 @@+import { createFaceTracker } from './face-tracker';+import { rmsLevel, type FaceResult } from './tracking';++export type CameraState = 'stopped' | 'starting' | 'running' | 'cameraBlocked' | 'cameraUnavailable' | 'modelError';+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: '' };+ constructor(private video: HTMLVideoElement, private onResult: (result: FaceResult, now: number) => void, private onState: (state: CameraState) => void) {}+ stop() {+ this.generation++; cancelAnimationFrame(this.raf);+ this.stream?.getTracks().forEach(track => track.stop()); this.stream = undefined;+ this.tracker?.close(); this.tracker = undefined;+ this.video.srcObject = null;+ this.onState('stopped');+ }+ async start(deviceId: string) {+ this.stop(); const generation = this.generation;+ this.onState('starting');+ let loadingModel = false;+ try {+ if (!navigator.mediaDevices?.getUserMedia) throw new Error('Camera unavailable');+ 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;+ 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) => {+ 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; }+ }+ this.raf = requestAnimationFrame(frame);+ };+ this.raf = requestAnimationFrame(frame);+ } catch (error) {+ if (generation !== this.generation) return;+ this.stop();+ this.onState(loadingModel ? 'modelError' : error instanceof DOMException && ['NotAllowedError', 'SecurityError'].includes(error.name) ? 'cameraBlocked' : 'cameraUnavailable');+ }+ }+}++export type MicState = 'micOff' | 'micStarting' | 'micOn' | 'micBlocked' | 'micUnavailable';+export class MicrophoneCapture {+ private generation = 0;+ private stream?: MediaStream;+ private context?: AudioContext;+ private analyser?: AnalyserNode;+ private samples = new Float32Array(1024);+ constructor(private onState: (state: MicState) => void) {}+ stop() {+ this.generation++;+ this.stream?.getTracks().forEach(track => track.stop()); this.stream = undefined;+ void this.context?.close().catch(() => undefined); this.context = undefined; this.analyser = undefined;+ this.onState('micOff');+ }+ async start(deviceId: string) {+ this.stop(); const generation = this.generation; this.onState('micStarting');+ try {+ const stream = await navigator.mediaDevices.getUserMedia({ video: false, audio: { echoCancellation: true, noiseSuppression: true, ...(deviceId ? { deviceId: { exact: deviceId } } : {}) } });+ if (generation !== this.generation) { stream.getTracks().forEach(track => track.stop()); return; }+ this.stream = stream;+ stream.getAudioTracks()[0]?.addEventListener('ended', () => { if (this.stream === stream) { this.stop(); this.onState('micUnavailable'); } }, { once: true });+ const context = new AudioContext(); this.context = context;+ await context.resume();+ if (generation !== this.generation) return;+ this.analyser = context.createAnalyser(); this.analyser.fftSize = this.samples.length;+ context.createMediaStreamSource(stream).connect(this.analyser);+ // Never connect to the audio output or record the captured samples.+ this.onState('micOn');+ } catch (error) {+ if (generation !== this.generation) return;+ this.stop(); this.onState(error instanceof DOMException && error.name === 'NotAllowedError' ? 'micBlocked' : 'micUnavailable');+ }+ }+ level(gain: number) {+ if (!this.analyser) return 0;+ this.analyser.getFloatTimeDomainData(this.samples);+ return rmsLevel(this.samples, gain);+ }+}diff --git a/src/live/tracking.ts b/src/live/tracking.tsnew file mode 100644index 0000000..9fa4692--- /dev/null+++ b/src/live/tracking.ts@@ -0,0 +1,89 @@+import { PARAMS } from '../engine/rig.js';++export interface FaceResult {+ faceLandmarks: unknown[][];+ faceBlendshapes: { categories: { categoryName: string; score: number }[] }[];+ facialTransformationMatrixes: { data: number[] }[];+}+export interface RawFace { yaw: number; pitch: number; roll: number; shapes: Record<string, number> }+export interface TrackingOptions { mirror: boolean; sensitivity: number; smoothing: number }+export const clamp = (value: number, min = 0, max = 1) => Math.max(min, Math.min(max, Number.isFinite(value) ? value : min));+export const faceNeutral: Record<string, number> = {+ angleX: 0, angleY: 0, angleZ: 0, bodyAngleX: 0, bodyAngleZ: 0,+ eyeLOpen: 1, eyeROpen: 1, gazeX: 0, gazeY: 0, mouthOpen: 0, mouthForm: 0, browY: 0, eyeSmile: 0, eyeSmileL: 0,+};+export function readFace(result: FaceResult): RawFace | null {+ const matrix = result.facialTransformationMatrixes[0]?.data;+ if (!result.faceLandmarks.length || !matrix || matrix.length !== 16 || !matrix.every(Number.isFinite)) return null;+ // MediaPipe matrices are column-major. Remove scale before extracting Y-X-Z rotation.+ const m = [...matrix];+ for (const offset of [0, 4, 8]) {+ const length = Math.hypot(m[offset], m[offset + 1], m[offset + 2]);+ if (length < 1e-6) return null;+ for (let i = 0; i < 3; i++) m[offset + i] /= length;+ }+ const degrees = 180 / Math.PI;+ return { yaw: Math.atan2(m[8], m[10]) * degrees, pitch: Math.asin(clamp(-m[9], -1, 1)) * degrees,+ roll: Math.atan2(m[1], m[5]) * degrees,+ shapes: Object.fromEntries((result.faceBlendshapes[0]?.categories ?? []).map(shape => [shape.categoryName, clamp(shape.score)])) };+}+const angleDelta = (value: number, neutral: number) => ((value - neutral + 540) % 360) - 180;+export function mapFace(face: RawFace, neutral: RawFace | null, options: TrackingOptions): Record<string, number> {+ const s = (key: string) => face.shapes[key] ?? 0;+ const n = (key: string) => neutral?.shapes[key] ?? 0;+ const d = (key: string) => s(key) - n(key);+ const mean = (a: string, b: string) => (d(a) + d(b)) / 2;+ const mirror = options.mirror ? -1 : 1, gain = clamp(options.sensitivity, 0.25, 2);+ const x = clamp(angleDelta(face.yaw, neutral?.yaw ?? 0) * gain * mirror, -30, 30);+ const y = clamp(angleDelta(face.pitch, neutral?.pitch ?? 0) * gain, -30, 30);+ const z = clamp(angleDelta(face.roll, neutral?.roll ?? 0) * gain * mirror, -30, 30);+ const open = (side: string) => {+ const blink = s(`eyeBlink${side}`);+ return blink >= 0.85 ? 0 : clamp((1 - blink) / Math.max(0.2, 1 - n(`eyeBlink${side}`)), 0, 1.25);+ };+ const smile = clamp((mean('mouthSmileLeft', 'mouthSmileRight') + mean('cheekSquintLeft', 'cheekSquintRight')) * 0.3);+ return { angleX: x, angleY: y, angleZ: z, bodyAngleX: x * 0.2, bodyAngleZ: z * 0.2,+ eyeLOpen: open(options.mirror ? 'Right' : 'Left'), eyeROpen: open(options.mirror ? 'Left' : 'Right'),+ gazeX: clamp((d('eyeLookOutRight') - d('eyeLookInRight') + d('eyeLookInLeft') - d('eyeLookOutLeft')) * mirror, -1, 1),+ gazeY: clamp(mean('eyeLookUpLeft', 'eyeLookUpRight') - mean('eyeLookDownLeft', 'eyeLookDownRight'), -1, 1),+ mouthOpen: clamp((d('jawOpen') - Math.max(0, d('mouthClose'))) * gain / Math.max(0.2, 1 - n('jawOpen'))),+ mouthForm: clamp((d('mouthPucker') + d('mouthFunnel') - mean('mouthSmileLeft', 'mouthSmileRight') - mean('mouthStretchLeft', 'mouthStretchRight')) * gain, -1, 1),+ browY: clamp((d('browInnerUp') + mean('browOuterUpLeft', 'browOuterUpRight') - mean('browDownLeft', 'browDownRight')) * gain, -1, 1),+ eyeSmile: smile, eyeSmileL: smile };+}+export function smoothParameters(current: Record<string, number>, target: Record<string, number>, dt: number, smoothing: number) {+ const tau = clamp(smoothing) * 0.25;+ const alpha = tau === 0 ? 1 : 1 - Math.exp(-Math.max(0, dt) / tau);+ return Object.fromEntries(Object.entries(target).map(([key, value]) => [key, (current[key] ?? value) + (value - (current[key] ?? value)) * alpha]));+}+export class FacePose {+ private face: RawFace | null = null;+ private neutral: RawFace | null = null;+ private seen = -Infinity;+ private params = { ...faceNeutral };+ private weight = 0;+ update(result: FaceResult, now: number) {+ const face = readFace(result);+ if (face) { this.face = face; this.seen = now; }+ }+ calibrate(now: number) {+ if (!this.face || now - this.seen > 500) return false;+ this.neutral = structuredClone(this.face); this.params = { ...faceNeutral }; return true;+ }+ reset() { this.face = null; this.neutral = null; this.seen = -Infinity; }+ sample(now: number, dt: number, options: TrackingOptions) {+ const tracking = !!this.face && now - this.seen <= 500;+ this.params = smoothParameters(this.params, tracking ? mapFace(this.face!, this.neutral, options) : faceNeutral, dt, tracking ? options.smoothing : 0.7);+ this.weight = tracking ? 1 : this.weight * Math.exp(-dt / 0.2);+ if (this.weight < 0.005) this.weight = 0;+ return { tracking, params: { ...this.params }, weight: this.weight };+ }+}+export function rmsLevel(samples: Float32Array, gain: number): number {+ if (!samples.length) return 0;+ let sum = 0;+ for (const sample of samples) sum += sample * sample;+ return clamp((Math.sqrt(sum / samples.length) - 0.008) * clamp(gain, 0, 10) * 5);+}+export const parameterRanges = new Map(PARAMS.map(param => [param.id, [param.min, param.max] as const]));+parameterRanges.set('eyeSmileL', [0, 1]);diff --git a/src/server/mediapipe-assets.ts b/src/server/mediapipe-assets.tsnew file mode 100644index 0000000..b3fb28c--- /dev/null+++ b/src/server/mediapipe-assets.ts@@ -0,0 +1,28 @@+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import type { Plugin } from 'vite';++export function mediapipeAssets(root: string): Plugin {+ const files = new Map([+ ...['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')],+ ['LICENSE', resolve(root, 'vendor/mediapipe/LICENSE')],+ ['README.md', resolve(root, 'vendor/mediapipe/README.md')],+ ]);+ return { name: 'local-mediapipe-assets', configureServer(server) {+ server.middlewares.use(async (req, res, next) => {+ const url = req.url?.split('?')[0];+ if (!url?.startsWith('/mediapipe/')) { next(); return; }+ const name = url.slice('/mediapipe/'.length), path = files.get(name);+ 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.end(req.method === 'HEAD' ? undefined : data);+ } catch { res.writeHead(404); res.end(); }+ });+ }, async generateBundle() {+ for (const [name, path] of files) this.emitFile({ type: 'asset', fileName: `mediapipe/${name}`, source: await readFile(path) });+ } };+}diff --git a/tests/live-media.test.ts b/tests/live-media.test.tsnew file mode 100644index 0000000..6d9d44b--- /dev/null+++ b/tests/live-media.test.ts@@ -0,0 +1,57 @@+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 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());++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();+});+test('stopping while the model loads releases camera immediately and closes a late tracker', async () => {+ const { stream, track } = media(), close = 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();+});+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; });+ 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();+});+test('permission denial produces a distinct camera status without creating a tracker', 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();+});+test('microphone permission cancellation releases tracks and permission denial is reported', async () => {+ const { stream, track } = media(); let resolve!: (stream: MediaStream) => void;+ vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: () => new Promise<MediaStream>(done => { resolve = done; }) } });+ const state = vi.fn(), mic = new MicrophoneCapture(state);+ const pending = mic.start(''); mic.stop(); resolve(stream); await pending;+ expect(track.stop).toHaveBeenCalledOnce(); expect(mic.level(1)).toBe(0);+ vi.stubGlobal('navigator', { mediaDevices: { getUserMedia: vi.fn(async () => { throw new DOMException('', 'NotAllowedError'); }) } });+ await mic.start(''); expect(state).toHaveBeenLastCalledWith('micBlocked');+});diff --git a/tests/live-tracking.test.ts b/tests/live-tracking.test.tsnew file mode 100644index 0000000..0ac9332--- /dev/null+++ b/tests/live-tracking.test.ts@@ -0,0 +1,63 @@+import { expect, test } from 'vitest';+import { FacePose, mapFace, readFace, smoothParameters, rmsLevel, faceNeutral, type FaceResult } from '../src/live/tracking';+const options = { mirror: false, sensitivity: 1, smoothing: 0 };+function result(yaw = 0, shapes: Record<string, number> = {}): FaceResult {+ const a = yaw * 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: Object.entries(shapes).map(([categoryName, score]) => ({ categoryName, score })) }] };+}+test('matrix rotation maps to degrees, neutral calibration and clamped engine limits', () => {+ const face = readFace(result(25))!;+ expect(face.yaw).toBeCloseTo(25);+ expect(mapFace(face, null, options).angleX).toBeCloseTo(25);+ expect(mapFace(face, readFace(result(10)), options).angleX).toBeCloseTo(15);+ expect(mapFace(face, null, { ...options, sensitivity: 2 }).angleX).toBe(30);+ const matrix = result().facialTransformationMatrixes[0].data;+ // 30 degrees around X, then independently around Z.+ const a = Math.PI / 6, c = Math.cos(a), s = Math.sin(a);+ matrix.splice(0, 16, 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1);+ const input = result(); input.facialTransformationMatrixes[0].data = matrix;+ expect(readFace(input)!.pitch).toBeCloseTo(30);+ input.facialTransformationMatrixes[0].data = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+ expect(readFace(input)!.roll).toBeCloseTo(30);+ input.facialTransformationMatrixes[0].data[0] = NaN; expect(readFace(input)).toBeNull();+});+test('mirror flips horizontal pose and gaze, swaps eyes, and blink closes fully', () => {+ const face = readFace(result(20, { eyeBlinkLeft: 0.9, eyeLookOutRight: 0.8 }))!;+ const normal = mapFace(face, null, options), mirror = mapFace(face, null, { ...options, mirror: true });+ expect(normal.eyeLOpen).toBe(0); expect(normal.eyeROpen).toBe(1);+ expect(mirror.eyeROpen).toBe(0); expect(mirror.eyeLOpen).toBe(1);+ expect(mirror.angleX).toBe(-normal.angleX); expect(mirror.gazeX).toBe(-normal.gazeX);+});+test('calibration normalizes relaxed eyes, mouth shapes, eyebrows and smile', () => {+ const neutral = readFace(result(0, { eyeBlinkLeft: 0.2, jawOpen: 0.1 }))!;+ const calm = mapFace(neutral, neutral, options);+ expect(calm.eyeLOpen).toBe(1); expect(calm.mouthOpen).toBe(0);+ const face = readFace(result(0, { jawOpen: 0.7, mouthPucker: 0.8, browInnerUp: 0.9, mouthSmileLeft: 0.3, cheekSquintRight: 0.4 }))!;+ const mapped = mapFace(face, neutral, options);+ expect(mapped.mouthOpen).toBeGreaterThan(0.6); expect(mapped.mouthForm).toBeGreaterThan(0);+ expect(mapped.browY).toBeGreaterThan(0); expect(mapped.eyeSmile).toBeGreaterThan(0);+ expect(mapFace(readFace(result(0, { mouthStretchLeft: 1, mouthStretchRight: 1 }))!, null, options).mouthForm).toBe(-1);+ expect(mapFace(readFace(result(0, { jawOpen: 0.5, mouthClose: 1 }))!, null, options).mouthOpen).toBe(0);+});+test('smoothing is time-based and face loss waits 500 ms before easing back to idle', () => {+ const full = smoothParameters({ angleX: 0 }, { angleX: 30 }, 0.1, 0.5);+ const half = smoothParameters(smoothParameters({ angleX: 0 }, { angleX: 30 }, 0.05, 0.5), { angleX: 30 }, 0.05, 0.5);+ expect(full.angleX).toBeCloseTo(half.angleX); expect(full.angleX).toBeGreaterThan(0); expect(full.angleX).toBeLessThan(30);+ const pose = new FacePose(); pose.update(result(30), 0);+ expect(pose.sample(499, 0.016, options)).toMatchObject({ tracking: true, weight: 1 });+ const lost = pose.sample(501, 0.016, options);+ expect(lost.tracking).toBe(false); expect(lost.weight).toBeLessThan(1); expect(lost.params.angleX).toBeGreaterThan(0);+ let last = lost;+ for (let i = 0; i < 200; i++) last = pose.sample(600 + i * 16, 0.016, options);+ expect(last.weight).toBe(0); expect(last.params.angleX).toBeCloseTo(faceNeutral.angleX);+ expect(pose.calibrate(5000)).toBe(false);+ pose.update(result(15), 5001); expect(pose.calibrate(5001)).toBe(true);+ expect(pose.sample(5001, 0.016, options).params.angleX).toBe(0);+});+test('microphone RMS has a noise floor, gain and a finite 0–1 output', () => {+ expect(rmsLevel(new Float32Array(128), 1)).toBe(0);+ const samples = new Float32Array([0.1, -0.1]);+ expect(rmsLevel(samples, 2)).toBeCloseTo(rmsLevel(samples, 1) * 2);+ expect(rmsLevel(new Float32Array([1, -1]), 5)).toBe(1);+ expect(rmsLevel(new Float32Array([NaN]), 1)).toBe(0);+});diff --git a/vendor/mediapipe/LICENSE b/vendor/mediapipe/LICENSEnew file mode 100644index 0000000..edc24fd--- /dev/null+++ b/vendor/mediapipe/LICENSE@@ -0,0 +1,55 @@+Apache License++Version 2.0, January 2004++http://www.apache.org/licenses/++TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++1. Definitions.++"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.++"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.++"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.++"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.++"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.++"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.++"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).++"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.++"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."++"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.++2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.++3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.++4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:++You must give any other recipients of the Work or Derivative Works a copy of this License; and++You must cause any modified files to carry prominent notices stating that You changed the files; and++You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and++If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.++5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.++6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.++7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.++8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.++9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.++END OF TERMS AND CONDITIONSdiff --git a/vendor/mediapipe/README.md b/vendor/mediapipe/README.mdnew file mode 100644index 0000000..1de77fc--- /dev/null+++ b/vendor/mediapipe/README.md@@ -0,0 +1,17 @@+# MediaPipe Face Landmarker++- Asset: `face_landmarker.task`, Face Landmarker float16, model version 1.+- Source: https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task+- SHA-256: `64184e229b263107bc2b804c6625db1341ff2bb731874b0bcc2fe6544e0bc9ff`+- Downloaded: 2026-10-05. The model is unmodified.+- Copyright: The MediaPipe Authors. Licensed under the Apache License, Version 2.0;+ see [LICENSE](LICENSE). Distributed without warranties or conditions of any kind.++The runtime uses `@mediapipe/tasks-vision` version **0.10.21**, pinned in `package.json`+and `package-lock.json`. Its JavaScript and WASM are licensed under Apache-2.0.+Vite serves the installed WASM files at `/mediapipe/` and includes them, this model,+and these notices in builds. No CDN or remote model request is needed at runtime.++This version is retained to avoid the metrics reporting present in newer releases.+Check runtime network behavior before updating it. Camera frames and microphone audio+are processed locally and are never included in relay messages.diff --git a/vendor/mediapipe/face_landmarker.task b/vendor/mediapipe/face_landmarker.tasknew file mode 100644index 0000000..c50c845Binary files /dev/null and b/vendor/mediapipe/face_landmarker.task differdiff --git a/vite.config.ts b/vite.config.tsindex 65e5f11..27e8e83 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -3,9 +3,10 @@ import react from '@vitejs/plugin-react';import { readFileSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { localProjectsPlugin } from './src/server/local-projects';+import { mediapipeAssets } from './src/server/mediapipe-assets';export default defineConfig({server: { host: '127.0.0.1' },- plugins: [react(), localProjectsPlugin(fileURLToPath(new URL('.', import.meta.url))), {+ plugins: [react(), localProjectsPlugin(fileURLToPath(new URL('.', import.meta.url))), mediapipeAssets(fileURLToPath(new URL('.', import.meta.url))), {name: 'sample-rig',resolveId(id) {if (id === 'virtual:sample-rig') return '\0sample-rig';@@ -18,6 +19,6 @@ export default defineConfig({},}],publicDir: 'samples',- build: { rollupOptions: { input: { editor: 'index.html', stream: 'stream.html' } } },+ build: { rollupOptions: { input: { editor: 'index.html', stream: 'stream.html', live: 'live.html' } } },test: { include: ['tests/**/*.test.ts'] },});