Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add optional camera body tracking to Live
shinshin86063f8364e2e3
diff --git a/.changeset/body-tracking-blend.md b/.changeset/body-tracking-blend.mdnew file mode 100644index 0000000..7c37aa3--- /dev/null+++ b/.changeset/body-tracking-blend.md@@ -0,0 +1,8 @@+---+"mesh-avatar": minor+---++Allow an optional third `setParameters` argument to blend individual parameters with+underlying motion. Omitted or null per-parameter weights clear previous overrides+and use the global weight. Existing calls retain their behavior. Studio uses this to fade+body tracking's weight shift back to idle without fading face tracking.diff --git a/e2e/live-streaming.spec.ts b/e2e/live-streaming.spec.tsindex 03e03cc..2c980ae 100644--- a/e2e/live-streaming.spec.ts+++ b/e2e/live-streaming.spec.ts@@ -259,3 +259,68 @@ test('overlay switches on the Live page reach the stream view and its OBS URL',} finally { await rm(directory, { recursive: true, force: true }); }expect(outside).toEqual([]);});++test('optional body tracking loads lazily, maps movement, calibrates and returns smoothly to face/idle', async ({ context, page }, testInfo) => {+ const outside = await guardNetwork(context), errors: string[] = [];+ page.on('pageerror', e => errors.push(e.message));+ await syntheticMedia(page);+ await page.addInitScript(() => {+ const NativeWorker = window.Worker;+ const stats = { poses: 0, closed: 0, results: 0 };+ Object.assign(window, { bodyWorkerStats: stats });+ window.Worker = class extends NativeWorker {+ constructor(url: string | URL, options?: WorkerOptions) {+ super(url, options); this.addEventListener('message', ({ data }) => {+ if (!data || typeof data.type !== 'string') return;+ if(data.type === 'pose-test') stats.poses++;+ if(data.type === 'pose-close-test') stats.closed++;+ if(data.type === 'result') stats.results++;+ });+ }+ };+ });+ await context.route('**/mediapipe/vision_bundle.js', route => route.fulfill({contentType:'application/javascript', body: `+ self.exports.FilesetResolver={forVisionTasks:async()=>({})};+ self.exports.FaceLandmarker={createFromOptions:async()=>({close(){},setOptions:async()=>{},detectForVideo(){+ const a=(self.bodyTestClosed?34:24)*Math.PI/180,c=Math.cos(a),s=Math.sin(a);return {faceLandmarks:[[]],faceBlendshapes:[],facialTransformationMatrixes:[{data:[c,0,-s,0,0,1,0,0,s,0,c,0,0,0,0,1]}]};+ }})};+ self.exports.PoseLandmarker={createFromOptions:async()=>{let calls=0;return {close(){self.bodyTestClosed=true;self.postMessage({type:'pose-close-test'});},setOptions:async()=>{},detectForVideo(){+ calls++;self.postMessage({type:'pose-test'});const shift=calls>2?.1:0;+ const l=Array.from({length:33},()=>({x:.5,y:.5,visibility:0,presence:1}));+ l[11]={x:.35+shift,y:.3,visibility:1,presence:1};l[12]={x:.65+shift,y:.3,visibility:1,presence:1};return {landmarks:[l]};+ }};}};` }));+ await ready(page, '/live.html');+ const toggle=page.getByTestId('body-tracking-toggle'); await expect(toggle).not.toBeChecked();+ await page.getByRole('checkbox',{name:'Mirror',exact:true}).uncheck();+ await page.getByRole('button',{name:'Start camera',exact:true}).click();+ await expect(page.getByTestId('tracking-status')).toHaveAttribute('data-state','tracking');+ const stats=()=>page.evaluate(()=> (window as Window & {bodyWorkerStats?: {poses:number;closed:number;results:number}}).bodyWorkerStats!);+ await expect.poll(async()=>(await stats()).results).toBeGreaterThan(5); expect((await stats()).poses).toBe(0);+ const nextParams=()=>page.evaluate(async()=>{+ const path='/src/live/relay.ts';const {receiveLiveParameters}=await import(path);+ return new Promise<Record<string,number>>(resolve=>{const off=receiveLiveParameters((d:{params:Record<string,number>})=>{off();resolve(d.params);});});+ });+ await toggle.check();+ await expect.poll(async()=>(await nextParams()).weightShift).toBeGreaterThan(.35);+ await expect.poll(async()=>(await nextParams()).bodyAngleX).toBeGreaterThan(6);+ expect((await nextParams()).bodyAngleX).toBeLessThan(7);+ const s=await stats();expect(s.poses).toBeLessThan(s.results*.6);+ await page.getByRole('button',{name:'Calibrate',exact:true}).click();+ await expect.poll(async()=>Math.abs((await nextParams()).bodyAngleX)).toBeLessThan(.5);+ await page.evaluate(async()=>{+ const path='/src/live/relay.ts';const {receiveLiveParameters}=await import(path);+ const values: {t:number;value:number}[]=[];Object.assign(window,{bodyReturnValues:values});const start=performance.now();+ receiveLiveParameters((d:{params:Record<string,number>})=>{if(performance.now()-start<600)values.push({t:performance.now()-start,value:d.params.weightShift});});+ });+ await toggle.uncheck();await expect.poll(async()=>(await stats()).closed).toBe(1);+ await expect.poll(async()=>(await nextParams()).bodyAngleX).toBeGreaterThan(1.8);+ const fade=await page.evaluate(()=> (window as Window & {bodyReturnValues?:{t:number;value:number}[]}).bodyReturnValues!);+ expect(fade.length).toBeGreaterThan(3);expect(Math.max(...fade.map(x=>Math.abs(x.value)))).toBeGreaterThan(.02);+ expect(Math.max(...fade.slice(1).map((x,i)=>Math.abs(x.value-fade[i].value)))).toBeLessThan(.45);+ await page.screenshot({path:testInfo.outputPath('body-controls-en.png')});+ await page.getByRole('button',{name:'日本語',exact:true}).click();await expect(page.getByRole('checkbox',{name:'体の動きを認識',exact:true})).toBeVisible();+ await page.screenshot({path:testInfo.outputPath('body-controls-ja.png')});+ await page.getByRole('button',{name:'简体中文',exact:true}).click();await expect(page.getByRole('checkbox',{name:'追踪身体动作',exact:true})).toBeVisible();+ await page.getByRole('button',{name:'停止摄像头',exact:true}).click();+ expect(errors).toEqual([]);expect(outside).toEqual([]);+});diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.jsindex c10e356..14237bb 100644--- a/packages/runtime/src/engine/createMeshAvatar.js+++ b/packages/runtime/src/engine/createMeshAvatar.js@@ -182,12 +182,15 @@ export async function createMeshAvatarImpl(canvas, options) {const listeners = new Set();motion.onMotion = id => { for (const fn of listeners) fn(id); };- let parameters = {}, parameterWeight = 1, lastParameters = {};+ let parameters = {}, parameterWeight = 1, parameterWeights = {}, lastParameters = {};const expression = new ExpressionOverlay();const tmp = [0, 0];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;+ for (const [key, value] of Object.entries(parameters)) {+ const weight = parameterWeight * (parameterWeights[key] ?? 1);+ P[key] = weight === 1 ? value : (P[key] ?? 0) + (value - (P[key] ?? 0)) * weight;+ }// Speech owns the mouth while active; explicit pose sliders still own all other parameters.if (motion.lipOpen !== null) {P.mouthOpen = motion.P.mouthOpen;@@ -264,7 +267,10 @@ export async function createMeshAvatarImpl(canvas, options) {return {motions: motionList,- setParameters(values, weight = 1) { parameters = { ...values }; parameterWeight = Math.min(1, Math.max(0, Number(weight) || 0)); },+ setParameters(values, weight = 1, weights = {}) {+ parameters = { ...values }; parameterWeight = Math.min(1, Math.max(0, Number(weight) || 0));+ parameterWeights = Object.fromEntries(Object.entries(weights ?? {}).map(([key, value]) => [key, Math.min(1, Math.max(0, Number(value) || 0))]));+ },getParameters() { return { ...lastParameters }; },/** 0..1 loudness of the voice being played (e.g. normalised RMS). */setVoiceLevel(v) { motion.setVoiceLevel(v); },diff --git a/packages/runtime/src/engine/index.ts b/packages/runtime/src/engine/index.tsindex 65e9b2f..1d683b5 100644--- a/packages/runtime/src/engine/index.ts+++ b/packages/runtime/src/engine/index.ts@@ -23,7 +23,8 @@ export interface MeshAvatar {readonly motions: { id: string; label: string; idle: boolean }[];setLighting(settings: Partial<LightingSettings>): void;getLightingStats(): { normalMs: number; computedLayers: number; cachedLayers: number };- setParameters(parameters: Record<string, number>, weight?: number): void;+ /** Optional per-parameter weights multiply weight and blend against underlying motion; null clears them. */+ setParameters(parameters: Record<string, number>, weight?: number, weights?: Record<string, number> | null): void;getParameters(): Record<string, number>;setVoiceLevel(value: number): void;/** Partial mouth-movement settings; omitted fields retain their current values. */diff --git a/packages/runtime/tests/parameters.test.ts b/packages/runtime/tests/parameters.test.tsnew file mode 100644index 0000000..d532ad7--- /dev/null+++ b/packages/runtime/tests/parameters.test.ts@@ -0,0 +1,42 @@+import { afterEach, expect, test, vi } from 'vitest';+import { createMeshAvatar, parseRig } from 'mesh-avatar';+import fixture from '../../../samples/miko-qipao/rig.json';++// Parameter blending runs without drawing; only the browser's asset/canvas boundary is stubbed.+vi.mock('../src/engine/renderer.js', () => ({ createRenderer: () => ({+ buildGrid: () => ({ rest: [], pos: [] }),+ Renderer: class {+ addLayer(_name: string, _image: unknown, mesh: unknown) { return { mesh }; }+ destroy() {}+ },+}) }));+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });++test('null parameter weights clear previous overrides and retain global blending, like omitted weights', async () => {+ vi.stubGlobal('Image', class {+ width = 1; height = 1; onload = () => {};+ set src(_value: string) { queueMicrotask(() => this.onload()); }+ });+ vi.stubGlobal('document', { createElement: () => ({ getContext: () => ({+ drawImage() {}, getImageData: () => ({ data: new Uint8Array(4) }),+ }) }) });+ vi.stubGlobal('fetch', vi.fn(async (url: string) => url.endsWith('layers.json')+ ? new Response(JSON.stringify({ layers: {} })) : new Response('', { status: 404 })));+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const avatar = await createMeshAvatar({} as HTMLCanvasElement,+ { rig: parseRig(fixture), assetsBase: 'https://example.test/parameters/', manual: true });+ try {+ avatar.setAutoIdle(false); avatar.setAutoMotion(false);+ avatar.advanceParameters(0); const underlying = avatar.getParameters().angleX;+ avatar.setParameters({ angleX: 10 }, .5, { angleX: 0 });+ avatar.advanceParameters(0); expect(avatar.getParameters().angleX).toBe(underlying);+ avatar.setParameters({ angleX: 10 }, .5, null);+ avatar.advanceParameters(0); const cleared = avatar.getParameters().angleX;+ expect(cleared).toBeCloseTo(underlying + (10 - underlying) * .5);+ avatar.setParameters({ angleX: 10 }, .5);+ avatar.advanceParameters(0); expect(avatar.getParameters().angleX).toBe(cleared);+ avatar.setParameters({ angleX: 10 }, .5, {});+ avatar.advanceParameters(0); expect(avatar.getParameters().angleX).toBe(cleared);+ } finally { avatar.destroy(); }+});diff --git a/src/live/LiveApp.tsx b/src/live/LiveApp.tsxindex b2bf7c0..0083acd 100644--- a/src/live/LiveApp.tsx+++ b/src/live/LiveApp.tsx@@ -65,7 +65,7 @@ export function LiveApp() {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);+ avatar.setParameters(sampled.params, sampled.weight, sampled.parameterWeights);const micOn = control.micState === 'micOn';avatar.setSpeaking(micOn); avatar.setVoiceLevel(micOn ? microphone.current?.level(control.gain) ?? 0 : 0);}, (avatar, now) => {@@ -152,6 +152,9 @@ export function LiveApp() {<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 data-testid="body-tracking-toggle" type="checkbox" checked={!!options.bodyTracking} onChange={event => {+ const enabled = event.target.checked; setOptions(current => ({ ...current, bodyTracking: enabled })); camera.current?.setBodyTracking(enabled);+ }} />{t.bodyTracking}</label><small>{t.bodyTrackingHint}</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>diff --git a/src/live/body-tracking.ts b/src/live/body-tracking.tsnew file mode 100644index 0000000..9b3622d--- /dev/null+++ b/src/live/body-tracking.ts@@ -0,0 +1,51 @@+import type { TrackingOptions } from './tracking';+const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, Number.isFinite(value) ? value : min));+export interface BodyPoint { x: number; y: number; visibility: number; presence?: number }+export interface BodyResult { shoulders: [BodyPoint, BodyPoint]; hips: [BodyPoint, BodyPoint]; aspect: number }+export interface BodyNeutral { shoulderX: number; width: number; roll: number; hipX?: number }+const usable = (p: BodyPoint, threshold: number) => p && [p.x, p.y, p.visibility, p.presence ?? 1].every(Number.isFinite) && p.visibility >= threshold && (p.presence ?? 1) >= 0.5;+export function readBody(body: BodyResult | null | undefined): BodyNeutral | null {+ if (!body || !Number.isFinite(body.aspect) || body.aspect <= 0 || body.shoulders?.length !== 2 || !body.shoulders?.every(p => usable(p, 0.55))) return null;+ const [a, b] = [...body.shoulders].sort((a, b) => a.x - b.x), dx = (b.x - a.x) * body.aspect, dy = b.y - a.y;+ const width = Math.hypot(dx, dy); if (width < 0.03) return null;+ return { shoulderX: (a.x + b.x) / 2 * body.aspect, width, roll: Math.atan2(dy, dx) * 180 / Math.PI,+ ...(body.hips?.length === 2 && body.hips.every(p => usable(p, 0.65)) ? { hipX: (body.hips[0].x + body.hips[1].x) / 2 * body.aspect } : {}) };+}+export function mapBody(body: BodyNeutral, neutral: BodyNeutral, options: TrackingOptions) {+ const gain = clamp(options.sensitivity, 0.25, 2) * (options.mirror ? -1 : 1);+ const shoulders = (body.shoulderX - neutral.shoulderX) / neutral.width;+ const hips = body.hipX !== undefined && neutral.hipX !== undefined ? (body.hipX - neutral.hipX) / neutral.width : shoulders;+ return { bodyAngleX: clamp(shoulders * gain * 20, -10, 10), bodyAngleZ: clamp((body.roll - neutral.roll) * gain, -10, 10), weightShift: clamp(hips * gain * 1.4, -1, 1) };+}+export class BodyPose {+ private body: BodyNeutral | null = null;+ private neutral: BodyNeutral | null = null;+ private seen = -Infinity;+ private weight = 0;+ private params = { bodyAngleX: 0, bodyAngleZ: 0, weightShift: 0 };+ update(result: BodyResult | null, now: number) {+ this.body = readBody(result); this.seen = this.body ? now : -Infinity;+ if (!this.neutral && this.body) this.neutral = { ...this.body };+ // Hips may first appear after a seated calibration. Keep the current shoulder+ // displacement as their initial offset, avoiding a new calibration jump.+ if (this.body?.hipX !== undefined && this.neutral && this.neutral.hipX === undefined)+ this.neutral.hipX = this.body.hipX - (this.body.shoulderX - this.neutral.shoulderX);+ }+ calibrate(now: number) {+ if (!this.body || now - this.seen > 500) return false;+ this.neutral = { ...this.body }; this.params = { bodyAngleX: 0, bodyAngleZ: 0, weightShift: 0 }; return true;+ }+ reset() { this.body = null; this.neutral = null; this.seen = -Infinity; }+ sample(now: number, dt: number, options: TrackingOptions) {+ const active = !!options.bodyTracking && !!this.body && !!this.neutral && now - this.seen <= 500;+ const alpha = 1 - Math.exp(-Math.max(0, dt) / 0.2);+ this.weight += ((active ? 1 : 0) - this.weight) * alpha;+ if (!active && this.weight < 0.005) this.weight = 0;+ if (active) {+ const target = mapBody(this.body!, this.neutral!, options), tau = options.smoothing * 0.25;+ const a = tau <= 0 ? 1 : 1 - Math.exp(-Math.max(0, dt) / tau);+ for (const key of ['bodyAngleX', 'bodyAngleZ', 'weightShift'] as const) this.params[key] += (target[key] - this.params[key]) * a;+ }+ return { active, weight: this.weight, params: { ...this.params } };+ }+}diff --git a/src/live/i18n.ts b/src/live/i18n.tsindex 5151ddc..ad74acd 100644--- a/src/live/i18n.ts+++ b/src/live/i18n.ts@@ -2,6 +2,7 @@ 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.',+ bodyTracking: 'Track body movement', bodyTrackingHint: 'Tracks shoulders and visible hips. When unavailable, face tracking and idle weight transfer continue.',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',@@ -35,6 +36,7 @@ const liveJa: typeof liveEn = {title: '配信', back: 'エディタに戻る', camera: 'カメラ', device: 'デバイス', defaultDevice: '既定のデバイス',start: 'カメラを開始', stop: 'カメラを停止', calibrate: '正面の姿勢を登録', calibrated: '正面の姿勢を登録しました',calibrateHint: '目と口の力を抜き、口を閉じてカメラに正面を向いた状態で登録してください。',+ bodyTracking: '体の動きを認識', bodyTrackingHint: '肩と、映っている腰の動きを使います。検出できないときは顔の認識と自動の体重移動に戻ります。',mirror: '左右反転', sensitivity: '感度', smoothing: '動きをなめらかにする', cameraPreview: 'カメラ映像を表示',microphone: 'マイクで口を動かす', gain: 'マイクの感度', privacy: 'カメラ映像とマイクの音声は、この端末内で処理します。配信用画面に渡すのはアバターの動きの数値だけです。',background: '背景', transparent: '透明', green: '緑', blue: '青', custom: '指定した色',@@ -68,6 +70,7 @@ const liveZh: typeof liveEn = {title: '直播', back: '返回编辑器', camera: '摄像头', device: '设备', defaultDevice: '默认设备',start: '启动摄像头', stop: '停止摄像头', calibrate: '校准', calibrated: '已保存中立姿态',calibrateHint: '正视摄像头,放松眼睛并闭上嘴,然后校准。',+ bodyTracking: '追踪身体动作', bodyTrackingHint: '追踪肩膀和可见的髋部。无法检测时恢复面部追踪与自动重心移动。',mirror: '镜像', sensitivity: '灵敏度', smoothing: '动作平滑度', cameraPreview: '显示摄像头画面',microphone: '麦克风口型同步', gain: '麦克风增益', privacy: '摄像头画面和麦克风音频仅在本机处理。直播画面只接收虚拟形象的动作数值。',background: '背景', transparent: '透明', green: '绿色', blue: '蓝色', custom: '自定义颜色',diff --git a/src/live/media.ts b/src/live/media.tsindex 9ae5796..42f12fa 100644--- a/src/live/media.ts+++ b/src/live/media.ts@@ -5,6 +5,8 @@ export type CameraState = 'stopped' | 'starting' | 'running' | 'cameraBlocked' |export type BackgroundTracking = 'backgroundStopped' | 'backgroundSlow' | null;type TrackProcessor = new (options: { track: MediaStreamTrack; maxBufferSize: number }) => { readable: ReadableStream<VideoFrame> };export class CameraCapture {+ private bodyTracking = false;+ setBodyTracking(enabled: boolean) { this.bodyTracking = enabled; this.worker?.postMessage({ type: 'body', enabled }); }private generation = 0;private stream?: MediaStream;private worker?: Worker;@@ -73,7 +75,7 @@ export class CameraCapture {else if (data.type === 'tick' && !this.reader && performance.now() - this.lastCallback > 100) void this.sendBitmap(generation);else if (data.type === 'error') fail();};- worker.postMessage({ type: 'init' });+ worker.postMessage({ type: 'init', ...(this.bodyTracking ? { bodyTracking: true } : {}) });} catch (error) {if (generation !== this.generation) return;this.stop();diff --git a/src/live/tracking-budget.js b/src/live/tracking-budget.jsnew file mode 100644index 0000000..6564a03--- /dev/null+++ b/src/live/tracking-budget.js@@ -0,0 +1,24 @@+// Classic-worker helper, deliberately free of browser/model dependencies.+// Two bad GPU windows trigger one CPU trial; a failed trial cannot cause flapping.+self.TrackingBudget = class TrackingBudget {+ constructor() { this.reset(); }+ reset() { this.mode = 'GPU'; this.frames = 0; this.bad = 0; this.samples = []; this.start = null; this.cooldown = -Infinity; this.gpu = null; }+ sample(total, poseRan, now) {+ if (now < this.cooldown || ++this.frames <= 5) return null;+ if (this.start === null) this.start = now;+ this.samples.push({ total, poseRan });+ if (this.samples.length < 16 || this.samples.filter(s => s.poseRan).length < 8 || now - this.start < 1000) return null;+ const value = { mean: this.samples.reduce((s, x) => s + x.total, 0) / this.samples.length, fps: (this.samples.length - 1) * 1000 / (now - this.start) };+ this.samples = []; this.start = null;+ if (this.mode === 'trial') {+ const better = value.mean < this.gpu.mean * 0.85 && value.fps > this.gpu.fps * 1.1;+ this.mode = better ? 'CPU' : 'GPU'; this.cooldown = now + 30000; this.frames = 0; this.bad = 0;+ return better ? 'keepCPU' : 'restoreGPU';+ }+ if (this.mode === 'CPU') return null;+ this.bad = value.mean > 1000 / 30 || value.fps < 15 ? this.bad + 1 : 0;+ if (this.bad < 2) return null;+ this.gpu = value; this.mode = 'trial'; this.frames = 0; return 'tryCPU';+ }+ failed(now) { this.mode = 'GPU'; this.cooldown = now + 30000; this.frames = 0; this.bad = 0; this.samples = []; this.start = null; }+};diff --git a/src/live/tracking-worker.js b/src/live/tracking-worker.jsindex 7c65dc7..ddd2435 100644--- a/src/live/tracking-worker.js+++ b/src/live/tracking-worker.js@@ -3,37 +3,84 @@const base = new URL('.', self.location.href).href.replace(/\/$/, '');self.exports = {};self.importScripts(`${base}/vision_bundle.js`);-const { FaceLandmarker, FilesetResolver } = self.exports;+const { FaceLandmarker, PoseLandmarker, FilesetResolver } = self.exports;+let pose, files, bodyEnabled = false, bodyFrame = 0, faceOnlyDelegate = 'GPU', configuration = Promise.resolve();+let budget;let tracker, lastFrame = -Infinity, delegate = 'GPU', frames = 0, gpuSamples = 0, gpuMs = 0;-self.onmessage = async ({ data }) => {+async function pairDelegate(value) {+ await tracker.setOptions({ baseOptions: { delegate: value } });+ if (pose) await pose.setOptions({ baseOptions: { delegate: value } });+ delegate = value; self.postMessage({ type: 'delegate', delegate });+}+async function configureBody(enabled) {+ if (enabled && !budget) { self.importScripts(`${base}/tracking-budget.js`); budget = new self.TrackingBudget(); }+ bodyFrame = 0; budget?.reset(); frames = 0; gpuSamples = 0; gpuMs = 0;+ if (!enabled) {+ bodyEnabled = false; pose?.close(); pose = null;+ if (delegate !== faceOnlyDelegate) await pairDelegate(faceOnlyDelegate);+ return;+ }+ if (pose && bodyEnabled) return;+ faceOnlyDelegate = delegate; bodyEnabled = true;+ try {+ if (delegate !== 'GPU') await pairDelegate('GPU');+ pose = await PoseLandmarker.createFromOptions(files, { runningMode: 'VIDEO', numPoses: 1, outputSegmentationMasks: false,+ baseOptions: { modelAssetPath: `${base}/pose_landmarker_lite.task`, delegate: 'GPU' } });+ } catch {+ pose?.close(); pose = null;+ // Face tracking remains available when optional body initialization fails.+ if (delegate !== faceOnlyDelegate) await pairDelegate(faceOnlyDelegate);+ }+}+async function handleMessage({ data }) {if (data.type === 'init') {try {- const files = await FilesetResolver.forVisionTasks(base);+ files = await FilesetResolver.forVisionTasks(base);const options = { runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true };try { tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: `${base}/face_landmarker.task`, delegate } }); }catch {delegate = 'CPU';tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: `${base}/face_landmarker.task`, delegate } });}+ if (data.bodyTracking) await configureBody(true);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 === 'body') {+ try { await configureBody(!!data.enabled); } catch { bodyEnabled = false; pose?.close(); pose = null; }} 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;+ const start = performance.now(), result = tracker.detectForVideo(data.frame, now);+ const faceElapsed = performance.now() - start;+ const poseRan = bodyEnabled && !!pose && bodyFrame++ % 2 === 0;+ let body = null;+ if (poseRan) {+ try { body = pose.detectForVideo(data.frame, now); }+ catch { pose.close(); pose = null; if (delegate !== faceOnlyDelegate) await pairDelegate(faceOnlyDelegate); }+ }+ const elapsed = performance.now() - start;+ const landmarks = body?.landmarks[0];+ const point = i => ({ x: landmarks[i].x, y: landmarks[i].y, visibility: landmarks[i].visibility ?? 0, presence: landmarks[i].presence ?? 1 });self.postMessage({ type: 'result', elapsed, result: {faceLandmarks: result.faceLandmarks.length ? [[]] : [],faceBlendshapes: result.faceBlendshapes,facialTransformationMatrixes: result.facialTransformationMatrixes,+ ...(bodyEnabled && (!pose || poseRan) ? { body: landmarks?.length >= 25 ? { shoulders: [point(11), point(12)], hips: [point(23), point(24)], aspect: (data.frame.displayWidth || data.frame.width) / (data.frame.displayHeight || data.frame.height) } : null } : {}),} });// 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 (bodyEnabled && pose) {+ const decision = budget.sample(elapsed, poseRan, performance.now());+ try {+ if (decision === 'tryCPU') await pairDelegate('CPU');+ if (decision === 'restoreGPU') await pairDelegate('GPU');+ } catch { await pairDelegate('GPU'); budget.failed(performance.now()); }+ } else if ((!bodyEnabled || !pose) && delegate === 'GPU' && ++frames > 5) {+ gpuMs += faceElapsed;if (++gpuSamples === 8) {if (gpuMs / gpuSamples > 1000 / 15) {await tracker.setOptions({ baseOptions: { delegate: 'CPU' } });@@ -46,4 +93,11 @@ self.onmessage = async ({ data }) => {} catch { self.postMessage({ type: 'error' }); }finally { data.frame.close(); self.postMessage({ type: 'consumed' }); }}+ }+// Serialize initialization, control changes and frames. Delegate changes await model+// rebuilding; an off toggle must not close a pose model in the middle of that work.+self.onmessage = event => {+ const operation = configuration.then(() => handleMessage(event));+ configuration = operation.catch(() => {});+ return operation;};diff --git a/src/live/tracking.ts b/src/live/tracking.tsindex 251ad66..1e116b9 100644--- a/src/live/tracking.ts+++ b/src/live/tracking.ts@@ -1,13 +1,15 @@+import { BodyPose, type BodyResult } from './body-tracking';// Vite bundles its config before applying aliases, so use the public source entry here.import { PARAMS } from '../../packages/runtime/src/index';export interface FaceResult {+ body?: BodyResult | null;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 interface TrackingOptions { bodyTracking?: boolean; 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,@@ -58,28 +60,40 @@ export function smoothParameters(current: Record<string, number>, target: Recordreturn Object.fromEntries(Object.entries(target).map(([key, value]) => [key, (current[key] ?? value) + (value - (current[key] ?? value)) * alpha]));}export class FacePose {+ private body = new BodyPose();+ private bodyEnabled = false;private face: RawFace | null = null;private neutral: RawFace | null = null;private seen = -Infinity;private params = { ...faceNeutral };private weight = 0;update(result: FaceResult, now: number) {+ if (result.body !== undefined) this.body.update(result.body, now);const face = readFace(result);if (face) { this.face = face; this.seen = now; }}calibrate(now: number) {- if (!this.face || now - this.seen > 500) return false;+ const body = this.bodyEnabled && this.body.calibrate(now);+ if (!this.face || now - this.seen > 500) return body;this.neutral = structuredClone(this.face); this.params = { ...faceNeutral }; return true;}- reset() { this.face = null; this.neutral = null; this.seen = -Infinity; }+ reset() { this.body.reset(); this.face = null; this.neutral = null; this.seen = -Infinity; }sample(now: number, dt: number, options: TrackingOptions) {+ this.bodyEnabled = !!options.bodyTracking;+ const body = this.body.sample(now, dt, options);const tracking = !!this.face && now - this.seen <= 500;const target = tracking ? mapFace(this.face!, this.neutral, options) : faceNeutral;this.params = smoothParameters(this.params, target, dt, tracking ? options.smoothing : 0.7);if (tracking) for (const eye of ['eyeLOpen', 'eyeROpen']) if (target[eye] === 0) this.params[eye] = 0;- this.weight = tracking ? 1 : this.weight * Math.exp(-dt / 0.2);+ this.weight = tracking || body.active ? 1 : this.weight * Math.exp(-dt / 0.2);if (this.weight < 0.005) this.weight = 0;- return { tracking, params: { ...this.params }, weight: this.weight };+ const params = { ...this.params };+ if (body.weight > 0) {+ for (const key of ['bodyAngleX', 'bodyAngleZ'] as const) params[key] += (body.params[key] - params[key]) * body.weight;+ params.weightShift = body.params.weightShift;+ }+ return { tracking: tracking || body.active, params, weight: body.active ? 1 : this.weight,+ parameterWeights: (body.weight > 0 ? { weightShift: body.weight } : {}) as Record<string, number> };}}export function rmsLevel(samples: Float32Array, gain: number): number {diff --git a/src/server/mediapipe-assets.ts b/src/server/mediapipe-assets.tsindex 21c4a0b..4fc9e07 100644--- a/src/server/mediapipe-assets.ts+++ b/src/server/mediapipe-assets.ts@@ -6,6 +6,8 @@ import type { Plugin } from 'vite';export function mediapipeAssets(root: string, prefix = '/'): Plugin {const files = new Map([['tracking-worker.js', resolve(root, 'src/live/tracking-worker.js')],+ ['tracking-budget.js', resolve(root, 'src/live/tracking-budget.js')],+ ['pose_landmarker_lite.task', resolve(root, 'vendor/mediapipe/pose_landmarker_lite.task')],// Served as .js: static hosts can label .cjs as application/node, which importScripts rejects.['vision_bundle.js', 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']diff --git a/tests/body-tracking.test.ts b/tests/body-tracking.test.tsnew file mode 100644index 0000000..518d3a7--- /dev/null+++ b/tests/body-tracking.test.ts@@ -0,0 +1,112 @@+import { expect, test } from 'vitest';+import { readFileSync } from 'node:fs';+import { runInNewContext } from 'node:vm';+import { BodyPose, readBody, mapBody, type BodyResult } from '../src/live/body-tracking';+import { FacePose, type FaceResult } from '../src/live/tracking';+const options = { mirror: false, sensitivity: 1, smoothing: 0, bodyTracking: true };+const point = (x: number, y: number, visibility = 1) => ({ x, y, visibility, presence: 1 });+const body = (shift = 0, hipShift = shift, hipsVisible = true): BodyResult => ({ aspect: 4 / 3,+ shoulders: [point(.35 + shift, .3), point(.65 + shift, .3)], hips: [point(.4 + hipShift, .7, hipsVisible ? 1 : 0), point(.6 + hipShift, .7, hipsVisible ? 1 : 0)] });+const face = (b?: BodyResult | null): FaceResult => ({ faceLandmarks: [[]], faceBlendshapes: [], facialTransformationMatrixes: [{ data: [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] }], ...(b !== undefined ? { body: b } : {}) });+test('shoulder displacement/tilt map independently, hips take weight priority, mirror and gain apply', () => {+ const zero = readBody(body())!;+ const shifted = readBody(body(.06, -.03))!;+ const normal = mapBody(shifted, zero, options), mirror = mapBody(shifted, zero, { ...options, mirror: true });+ expect(normal.bodyAngleX).toBeCloseTo(4); expect(normal.weightShift).toBeCloseTo(-.14);+ expect(mirror.bodyAngleX).toBeCloseTo(-normal.bodyAngleX); expect(mirror.weightShift).toBeCloseTo(-normal.weightShift);+ expect(mapBody(shifted, zero, { ...options, sensitivity: 2 }).bodyAngleX).toBeCloseTo(8);+ expect(mapBody(readBody(body(1))!, zero, options).bodyAngleX).toBe(10);+ const seated = mapBody(readBody(body(.06, -.03, false))!, zero, options); expect(seated.weightShift).toBeCloseTo(.28);+ const tilted = body(); tilted.shoulders[1].y += .04;+ expect(mapBody(readBody(tilted)!, zero, options).bodyAngleZ).toBeGreaterThan(5);+ expect(mapBody(readBody(tilted)!, zero, { ...options, mirror: true }).bodyAngleZ).toBeLessThan(-5);+ tilted.shoulders[0].visibility = .1; expect(readBody(tilted)).toBeNull();+ tilted.shoulders[0].visibility = 1; tilted.shoulders[0].x = NaN; expect(readBody(tilted)).toBeNull();+});+test('body neutral calibration, stale/lost/off fade, and late hip visibility stay continuous', () => {+ const pose = new BodyPose(); pose.update(body(), 0); pose.sample(0, .2, options); pose.update(body(.06, .06, false), 10);+ expect(pose.sample(10, .2, options).params.weightShift).toBeCloseTo(.28);+ pose.calibrate(10); expect(pose.sample(10, .2, options).params.bodyAngleX).toBe(0);+ pose.update(body(.09, .09), 20); const active = pose.sample(20, .2, options);+ expect(active.params.weightShift).toBeCloseTo(.14);+ pose.reset();+ const off = pose.sample(21, .016, { ...options, bodyTracking: false }); expect(off.weight).toBeLessThan(active.weight); expect(off.weight).toBeGreaterThan(0);+ expect(pose.sample(600, .016, options).active).toBe(false);+ pose.update(null, 601); for (let i = 0; i < 100; i++) pose.sample(602+i*16, .016, options);+ expect(pose.sample(3000, .016, options).weight).toBe(0); expect(pose.calibrate(3000)).toBe(false);+});+test('face-only output stays identical when body is off; body overrides rather than adds and fades weight separately', () => {+ const a = new FacePose(), b = new FacePose(); a.update(face(body()), 0); b.update(face(), 0);+ expect(a.sample(1, .016, { ...options, bodyTracking: false })).toEqual(b.sample(1, .016, { ...options, bodyTracking: false }));+ a.sample(1, 1, options); const turned=face(body(.06)); const yaw=Math.PI/6;turned.facialTransformationMatrixes[0].data=[Math.cos(yaw),0,-Math.sin(yaw),0,0,1,0,0,Math.sin(yaw),0,Math.cos(yaw),0,0,0,0,1];a.update(turned, 10); const active = a.sample(10, 1, options);+ expect(active.params.bodyAngleX).toBeCloseTo(4, 1); expect(active.parameterWeights.weightShift).toBeGreaterThan(.99);+ const lost = a.sample(600, .016, options); expect(lost.parameterWeights.weightShift).toBeGreaterThan(0); expect(lost.parameterWeights.weightShift).toBeLessThan(1);+ for (let i = 0; i < 100; i++) a.sample(700+i*16, .016, options);+ expect(a.sample(3000,.016,options).params.weightShift).toBeUndefined();+});+interface Budget { mode: string; sample(ms: number, pose: boolean, now: number): string | null }+function budget(): Budget {+ const self: { TrackingBudget?: new () => Budget } = {};+ runInNewContext(readFileSync('src/live/tracking-budget.js','utf8'), { self }); return new self.TrackingBudget!();+}+test('body-on budget uses amortized total, two bad windows, trial improvement and cooldown', () => {+ for (const improve of [false, true]) {+ const b = budget(); let now = 0, decision: string | null = null;+ for (let i = 0; i < 200 && decision !== 'tryCPU'; i++) { now += 50; decision = b.sample(i % 2 ? 20 : 70, i % 2 === 0, now); }+ expect(decision).toBe('tryCPU');+ decision = null;+ for (let i = 0; i < 100 && !decision; i++) { now += improve ? 33.3 : 90; decision = b.sample(improve ? 20 : 80, i % 2 === 0, now); }+ expect(decision).toBe(improve ? 'keepCPU' : 'restoreGPU');+ for (let i=0;i<100;i++) expect(b.sample(100,true,now+i*50)).toBeNull();+ }+ const fast = budget(); for(let i=0;i<200;i++) expect(fast.sample(20,i%2===0,i*34)).toBeNull();+});++test('worker leaves Pose unloaded when off, runs every second frame when on, returns only four numeric joints and closes frames', async () => {+ const { createContext, runInContext } = await import('node:vm');+ let poseLoads=0, poseCalls=0, closes=0, poseCloses=0, clock=0, rejectPose=false;+ const messages: {type:string; result?:{body?:BodyResult}}[]=[];+ const self: Record<string, unknown> = { location:{href:'http://127.0.0.1/mediapipe/tracking-worker.js'}, postMessage:(m:typeof messages[number])=>messages.push(m),setInterval:()=>0 };+ const context=createContext({self,URL,performance:{now:()=>clock},console});+ self.importScripts=(url:string)=>{+ if(url.endsWith('tracking-budget.js')) runInContext(readFileSync('src/live/tracking-budget.js','utf8'),context);+ else self.exports={ FilesetResolver:{forVisionTasks:async()=>({})},+ FaceLandmarker:{createFromOptions:async()=>({setOptions:async()=>{},detectForVideo:()=>face()})},+ PoseLandmarker:{createFromOptions:async()=>{poseLoads++;if(rejectPose)throw new Error('optional model unavailable');return {close:()=>poseCloses++,setOptions:async()=>{},detectForVideo:()=>{poseCalls++;return {landmarks:[Array.from({length:33},()=>point(.5,.4))]};}};} } };+ };+ runInContext(readFileSync('src/live/tracking-worker.js','utf8'),context);+ const send=self.onmessage as (event:{data:Record<string,unknown>})=>Promise<void>;+ await send({data:{type:'init'}});+ async function frame(){clock+=34;await send({data:{type:'frame',timestamp:clock,frame:{displayWidth:640,displayHeight:480,close:()=>closes++}}});}+ await frame();await frame();expect(poseLoads).toBe(0);expect(messages.filter(m=>m.type==='result').at(-1)?.result?.body).toBeUndefined();+ await send({data:{type:'body',enabled:true}});for(let i=0;i<8;i++)await frame();+ expect(poseLoads).toBe(1);expect(poseCalls).toBe(4);expect(closes).toBe(10);+ const bodyMessages=messages.filter(m=>m.type==='result'&&m.result?.body);+ expect(bodyMessages).toHaveLength(4);expect(Object.keys(bodyMessages[0].result!.body!)).toEqual(['shoulders','hips','aspect']);+ expect(bodyMessages[0].result!.body!.shoulders).toHaveLength(2);expect(bodyMessages[0].result!.body!.hips).toHaveLength(2);+ await send({data:{type:'body',enabled:false}});await frame();expect(poseCloses).toBe(1);expect(poseCalls).toBe(4);expect(closes).toBe(11);+ rejectPose=true;await send({data:{type:'body',enabled:true}});await frame();expect(poseLoads).toBe(2);expect(messages.filter(m=>m.type==='result').at(-1)?.result?.body).toBeNull();+ expect(messages.filter(m=>m.type==='error')).toEqual([]);+});++test('body-off waits for an in-flight CPU trial before closing the model and restores the face delegate', async () => {+ const {createContext,runInContext}=await import('node:vm');+ let releaseCPU!:()=>void, enterCPU!:()=>void, closed=0, frameClosed=0;+ const cpuEntered=new Promise<void>(r=>enterCPU=r),cpuRelease=new Promise<void>(r=>releaseCPU=r);+ const delegates:string[]=[];const messages:{type:string;delegate?:string}[]=[];+ const self:Record<string,unknown>={location:{href:'http://127.0.0.1/mediapipe/tracking-worker.js'},postMessage:(m:typeof messages[number])=>messages.push(m),setInterval:()=>0};+ const context=createContext({self,URL,performance:{now:()=>34}});+ self.importScripts=(url:string)=>{+ if(url.endsWith('tracking-budget.js')) self.TrackingBudget=class { reset(){} sample(){return 'tryCPU';} };+ else self.exports={FilesetResolver:{forVisionTasks:async()=>({})},+ FaceLandmarker:{createFromOptions:async()=>({detectForVideo:()=>face(),setOptions:async(o:{baseOptions:{delegate:string}})=>{const d=o.baseOptions.delegate;if(d==='CPU'){enterCPU();await cpuRelease;}delegates.push(d);}})},+ PoseLandmarker:{createFromOptions:async()=>({close:()=>closed++,setOptions:async()=>{},detectForVideo:()=>({landmarks:[Array.from({length:33},()=>point(.5,.4))]})})}};+ };+ runInContext(readFileSync('src/live/tracking-worker.js','utf8'),context);+ const send=self.onmessage as(e:{data:Record<string,unknown>})=>Promise<void>;+ await send({data:{type:'init',bodyTracking:true}});+ const frame=send({data:{type:'frame',timestamp:34,frame:{displayWidth:640,displayHeight:480,close:()=>frameClosed++}}});+ await cpuEntered;const off=send({data:{type:'body',enabled:false}});await Promise.resolve();await Promise.resolve();expect(closed).toBe(0);+ releaseCPU();await frame;await off;+ expect(delegates).toEqual(['CPU','GPU']);expect(closed).toBe(1);expect(frameClosed).toBe(1);expect(messages.filter(m=>m.type==='error')).toEqual([]);+});diff --git a/vendor/mediapipe/README.md b/vendor/mediapipe/README.mdindex 6913a75..c30010c 100644--- a/vendor/mediapipe/README.md+++ b/vendor/mediapipe/README.md@@ -18,3 +18,17 @@ telemetry and remote asset URLs, then run the live and stream network-isolationwith the real tracker initialized. All assets must still load locally, with no outboundrequests. Camera frames and microphone audio are processed locally and are neverincluded in relay messages.++## Optional Pose Landmarker lite++- Asset: `pose_landmarker_lite.task`, float16, model version 1; 5,777,746 bytes.+- Source: https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task+- SHA-256: `59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a`+- Downloaded: 2026-10-29. The model is unmodified.+- Copyright: The MediaPipe Authors. Apache License, Version 2.0 (see LICENSE).+ The [official model card](https://storage.googleapis.com/mediapipe-assets/Model%20Card%20BlazePose%20GHUM%203D.pdf),+ page 2, specifies the model license.++Body tracking is off by default. The worker loads this local model only when body+tracking is enabled, and runs it on every second accepted face frame. Only numeric+shoulder/hip coordinates return; no frame, segmentation mask or image is returned.diff --git a/vendor/mediapipe/pose_landmarker_lite.task b/vendor/mediapipe/pose_landmarker_lite.tasknew file mode 100644index 0000000..09576a9Binary files /dev/null and b/vendor/mediapipe/pose_landmarker_lite.task differ