Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Add a browser-only Player page to the landing site
shinshin86750619b5d81f
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.ymlindex eaa88fb..1dcb14b 100644--- a/.github/workflows/pages.yml+++ b/.github/workflows/pages.yml@@ -8,6 +8,13 @@ on:- 'docs/images/**'- 'packages/runtime/src/**'- 'samples/miko-qipao/**'+ # The Player page reuses Studio's Live, lighting and tracking files.+ - 'src/live/**'+ - 'src/lighting/**'+ - 'src/editor/Icon.tsx'+ - 'src/server/mediapipe-assets.ts'+ - 'vendor/mediapipe/**'+ - 'package-lock.json'- '.github/workflows/pages.yml'workflow_dispatch:diff --git a/README.ja.md b/README.ja.mdindex 795707b..c23a4e6 100644--- a/README.ja.md+++ b/README.ja.md@@ -5,6 +5,7 @@1枚のイラストから、まばたき・口パク・首振り・呼吸・髪の揺れをする 2D メッシュアバターを作るツールです。アバターの作成はコーディングエージェントが行い、細かい調整はプレビューを見ながらローカルのエディタで行います。実際に動く様子は[紹介ページ](https://shinshin86.github.io/mesh-avatar-studio/ja/)で見られます。+インストールせずに自分の顔と声で動かすなら、Chrome か Edge で [Player](https://shinshin86.github.io/mesh-avatar-studio/ja/play/) を開いてください。@@ -102,6 +103,10 @@ npm run dev配信用画面の URL で指定できる項目、うまく動かないときの確認点、プライバシーについては[リファレンス](docs/reference.md#live-and-streaming)(英語)にまとめています。+### インストールせずに使う++[Player](https://shinshin86.github.io/mesh-avatar-studio/ja/play/) では、顔の追従、マイクでの口パク、表情、ライティングをすべてブラウザ内で動かせます。サンプルか自分の `.mavatar` ファイルを開いて使い、ファイルはアップロードされません。OBS用URLはないため、「アバターウィンドウを開く」(Chrome か Edge)を押し、そのウィンドウを緑の背景にして OBS の「ウィンドウキャプチャ」で取り込み、クロマキーで抜いてください。透明な背景、OBS の「ブラウザ」ソース、他のアプリからの表情の切り替えを使うときは、Studio の配信画面を使います。+## リリース`mesh-avatar` を変更するときは `npm run changeset` を実行し、生成されたファイルをPRに含めてください。`main` に変更が入ると、GitHub Actionsが次のバージョンと変更履歴を含む `chore: version packages` PRを作成・更新します。そのPRをマージすると、`mesh-avatar` がprovenance付きでnpmに公開されます。Studioのルートパッケージは非公開のままです。公開にはnpmのtrusted publishingを使います。npmjs.comの `mesh-avatar` の設定で、このリポジトリと `release.yml` ワークフローをtrusted publisherとして登録してください。npmのトークンをリポジトリに保存する必要はありません。trusted publisherに一致しない公開は、メンテナーが2FAで承認するまでStaged Packagesタブで待機します。ワークフローがバージョン更新のPRを作成できるよう、リポジトリの Settings → Actions → General で **Allow GitHub Actions to create and approve pull requests** を有効にしてください。PRを作る前に、手元で `npm run e2e` を実行してください。CIはその他の検証を実行し、Playwrightのブラウザはインストールしません。diff --git a/README.md b/README.mdindex 28cd297..ad1e66e 100644--- a/README.md+++ b/README.md@@ -7,6 +7,8 @@ breathes and sways its hair. A coding agent prepares the avatar from your image;it in a local editor with a live preview.See it move on the [landing page](https://shinshin86.github.io/mesh-avatar-studio/).+To move it with your own face and voice without installing anything, open the+[Player](https://shinshin86.github.io/mesh-avatar-studio/play/) in Chrome or Edge.@@ -154,6 +156,15 @@ OBS's Virtual Camera ([steps](docs/reference.md#video-calls)).Stream view options, troubleshooting and privacy details are in the[reference](docs/reference.md#live-and-streaming).+### Without installing anything++The [Player](https://shinshin86.github.io/mesh-avatar-studio/play/) runs face tracking,+microphone lip sync, expressions and lighting entirely in the browser. Open the sample or+your own `.mavatar` file; nothing is uploaded. It has no stream URL: choose **Open avatar+window** (Chrome or Edge) and add that window to OBS with **Window Capture** on a green+background and a Chroma Key filter. Transparency, the OBS Browser Source and switching+expressions from other apps need Studio's Live page.+## ReleasesFor changes to `mesh-avatar`, run `npm run changeset` and include the generated file in yourdiff --git a/e2e/live-streaming.spec.ts b/e2e/live-streaming.spec.tsindex f1536c8..7bebf64 100644--- a/e2e/live-streaming.spec.ts+++ b/e2e/live-streaming.spec.ts@@ -40,7 +40,7 @@ async function syntheticMedia(page: Page) {});}async function stubTracker(page: Page, moving = false) {- await page.context().route('**/mediapipe/vision_bundle.cjs', route => route.fulfill({ contentType: 'application/javascript', body: `+ await page.context().route('**/mediapipe/vision_bundle.js', route => route.fulfill({ contentType: 'application/javascript', body: `self.exports.FilesetResolver = { forVisionTasks: async () => ({}) };self.exports.FaceLandmarker = { createFromOptions: async () => ({ close() {}, detectForVideo() {const a = ${moving ? 'Math.sin(performance.now() / 300) * 24' : '24'} * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);diff --git a/e2e/player.spec.ts b/e2e/player.spec.tsnew file mode 100644index 0000000..e581f3e--- /dev/null+++ b/e2e/player.spec.ts@@ -0,0 +1,122 @@+import { expect, test, type BrowserContext, type Page } from '@playwright/test';+import { PNG } from 'pngjs';+import { readFile } from 'node:fs/promises';+import { samplePresent, sampleSkipReason } from './sample';++test.beforeEach(() => { test.skip(!samplePresent, sampleSkipReason); });++const site = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/`;++async function guardNetwork(context: BrowserContext) {+ const outside: string[] = [];+ await context.route('**/*', route => {+ if (new URL(route.request().url()).hostname !== '127.0.0.1') { outside.push(route.request().url()); return route.abort(); }+ return route.continue();+ });+ return outside;+}+// A moving synthetic camera and a tracker stub that reports a head turned 24 degrees.+async function fakeTracking(page: Page) {+ await page.addInitScript(() => {+ Object.defineProperty(navigator.mediaDevices, 'enumerateDevices', { value: async () => [] });+ Object.defineProperty(navigator.mediaDevices, 'getUserMedia', { value: async () => {+ const canvas = document.createElement('canvas'); canvas.width = 640; canvas.height = 480;+ const ctx = canvas.getContext('2d')!;+ const draw = () => { ctx.fillStyle = '#999'; ctx.fillRect(0, 0, 640, 480); ctx.fillStyle = '#fff'; ctx.fillRect(Date.now() % 500, 100, 40, 40); };+ draw(); const timer = window.setInterval(draw, 33);+ const stream = canvas.captureStream(30), track = stream.getTracks()[0], stop = track.stop.bind(track);+ track.stop = () => { clearInterval(timer); stop(); };+ return stream;+ } });+ });+ await page.context().route('**/mediapipe/vision_bundle.js', route => route.fulfill({ contentType: 'application/javascript', body: `+ self.exports.FilesetResolver = { forVisionTasks: async () => ({}) };+ self.exports.FaceLandmarker = { createFromOptions: async () => ({ close() {}, detectForVideo() {+ const a = 24 * Math.PI / 180, c = Math.cos(a), s = Math.sin(a);+ return { faceLandmarks: [[]], facialTransformationMatrixes: [{ data: [c,0,-s,0,0,1,0,0,s,0,c,0,0,0,0,1] }], faceBlendshapes: [{ categories: [] }] };+ } }) };` }));+}+const ready = (page: Page, name: string) => expect(page.getByTestId('player-status')).toHaveText(new RegExp(`· ${name.replace(/[().]/g, '\\$&')}$`));++test('player runs the sample with face tracking in the browser and makes no outside requests', async ({ context, page }) => {+ const outside = await guardNetwork(context);+ await fakeTracking(page);+ await page.goto(`${site}play/`);+ await ready(page, 'Miko (sample)');+ await expect(page.getByTestId('player-status')).toContainText('Avatar ready');+ const canvas = page.getByTestId('player-avatar');+ await page.getByRole('button', { name: 'Start camera' }).click();+ await expect(page.getByTestId('tracking-status')).toHaveAttribute('data-state', 'tracking');+ // While tracking, idle motion is off: the head follows the stubbed 24 degree turn, and+ // calibrating makes that turn the neutral pose.+ await page.waitForTimeout(1000);+ const turned = await canvas.screenshot();+ await page.getByRole('button', { name: 'Calibrate' }).click();+ await expect(page.getByText('Neutral pose saved')).toBeVisible();+ await page.waitForTimeout(1000);+ expect((await canvas.screenshot()).equals(turned)).toBe(false);+ await page.getByRole('button', { name: 'Stop camera' }).click();+ await expect(page.getByTestId('tracking-status')).toHaveAttribute('data-state', 'stopped');+ expect(outside).toEqual([]);+});++test('player opens a dropped or chosen .mavatar and recovers from a broken file', async ({ page }) => {+ await page.goto(`${site}play/`);+ await ready(page, 'Miko (sample)');+ const archive = await (await page.request.get(`${site}miko.mavatar`)).body();+ await page.getByTestId('player-file').setInputFiles({ name: 'mine.mavatar', mimeType: 'application/octet-stream', buffer: archive });+ await ready(page, 'mine.mavatar');+ await expect(page.getByText('Miko © Yuki Shindo')).toHaveCount(0);+ await page.getByTestId('player-file').setInputFiles({ name: 'broken.mavatar', mimeType: 'application/octet-stream', buffer: Buffer.from('not an avatar') });+ await expect(page.getByTestId('player-notice')).toContainText('Could not open this file');+ await ready(page, 'mine.mavatar');+ // Drop onto the page.+ const transfer = await page.evaluateHandle(bytes => {+ const data = new DataTransfer(); data.items.add(new File([new Uint8Array(bytes)], 'dropped.mavatar')); return data;+ }, [...archive]);+ await page.locator('main').dispatchEvent('drop', { dataTransfer: transfer });+ await ready(page, 'dropped.mavatar');+ await page.getByRole('button', { name: 'Use the sample' }).click();+ await ready(page, 'Miko (sample)');+});++test('player shows only the avatar on an exact key colour for a window capture', async ({ page }) => {+ await page.goto(`${site}play/`);+ await ready(page, 'Miko (sample)');+ await page.getByLabel('Background').selectOption('#00ff00');+ // Keys are ignored while a form control has focus.+ await page.getByTestId('player-status').click();+ await page.keyboard.press('2');+ await expect(page.locator('.expression-on')).toHaveText('Smile');+ await page.getByRole('button', { name: 'Avatar only in this window' }).click();+ await expect(page.locator('.live-controls')).toBeHidden();+ await expect(page.getByTestId('player-exit-hint')).toBeHidden({ timeout: 5000 });+ const image = PNG.sync.read(await page.screenshot());+ expect([...image.data.subarray(0, 4)]).toEqual([0, 255, 0, 255]);+ await page.keyboard.press('Escape');+ await expect(page.locator('.live-controls')).toBeVisible();+});++test('player moves the avatar to its own window and back', async ({ page, context }) => {+ await page.goto(`${site}play/`);+ await ready(page, 'Miko (sample)');+ test.skip(!await page.evaluate(() => 'documentPictureInPicture' in window), 'Document Picture-in-Picture is unavailable');+ const opened = context.waitForEvent('page');+ await page.getByRole('button', { name: 'Open avatar window' }).click();+ const avatarWindow = await opened;+ await expect(avatarWindow.locator('canvas')).toHaveCount(1);+ await expect(page.getByText('The avatar is shown in its own window.')).toBeVisible();+ const first = await avatarWindow.screenshot();+ await page.keyboard.press('4');+ await expect.poll(async () => (await avatarWindow.screenshot()).equals(first)).toBe(false);+ await avatarWindow.close();+ await expect(page.locator('.player-stage canvas')).toHaveCount(1);+ await expect(page.getByRole('button', { name: 'Open avatar window' })).toBeVisible();+});++test('Japanese player page uses Japanese text and links back to the English page', async ({ page }) => {+ await page.goto(`${site}ja/play/`);+ await expect(page.getByTestId('player-status')).toContainText('アバターの準備ができました');+ await expect(page.getByRole('link', { name: 'English' })).toHaveAttribute('href', '../../play/');+ expect(await readFile(new URL('../site/ja/play/index.html', import.meta.url), 'utf8')).toContain('lang="ja"');+});diff --git a/playwright.config.ts b/playwright.config.tsindex 8dceae8..493c226 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -1,6 +1,7 @@import { defineConfig } from '@playwright/test';const port = Number(process.env.PLAYWRIGHT_PORT ?? 5173);const baseURL = `http://127.0.0.1:${port}`;+const sitePort = Number(process.env.PLAYWRIGHT_SITE_PORT ?? 5174);export default defineConfig({testDir: 'e2e',@@ -10,9 +11,14 @@ export default defineConfig({baseURL,viewport: { width: 1440, height: 1000 },},- webServer: {+ webServer: [{command: `npm run dev -- --port ${port}`,url: baseURL,reuseExistingServer: true,- },+ }, {+ // The landing site with the Player page, served under its GitHub Pages folder.+ command: `npm run dev:site -- --port ${sitePort} --strictPort`,+ url: `http://127.0.0.1:${sitePort}/mesh-avatar-studio/play/`,+ reuseExistingServer: true,+ }],});diff --git a/site/index.html b/site/index.htmlindex 8de7ea6..415f24f 100644--- a/site/index.html+++ b/site/index.html@@ -38,6 +38,7 @@<a class="header-link" href="#make">Make an avatar</a><a class="header-link" href="#live">Use it live</a><a class="header-link" href="#embed">Embed</a>+ <a class="header-link" href="./play/">Player</a><a class="header-link" href="https://github.com/shinshin86/mesh-avatar-studio">GitHub <span aria-hidden="true">↗</span></a></nav><a class="header-link language-switch" href="./ja/" lang="ja" hreflang="ja">日本語</a>@@ -51,6 +52,7 @@<p class="hero-description">Create and adjust it in Studio, then bring it to your app with the <span class="package-name">mesh-avatar</span> runtime.</p><div class="hero-actions"><a class="button primary" href="https://github.com/shinshin86/mesh-avatar-studio">Get started on GitHub <span aria-hidden="true">↗</span></a>+ <a class="button secondary" href="./play/">Try it in your browser</a><a class="button secondary" href="https://www.npmjs.com/package/mesh-avatar">Runtime on npm <span aria-hidden="true">↗</span></a></div><p class="hero-note">A local editor. An avatar you can embed.</p>@@ -195,7 +197,7 @@</figure></article></div>- <p class="section-note">Both views use the local development server. Keep the Live page open in its own window while streaming. <a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">Streaming guide <span aria-hidden="true">↗</span></a></p>+ <p class="section-note">Both views use the local development server. Keep the Live page open in its own window while streaming. Without any setup, the <a href="./play/">Player</a> moves a .mavatar file with your camera and microphone in the browser, for OBS Window Capture. <a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">Streaming guide <span aria-hidden="true">↗</span></a></p></section><section id="embed" class="content-section" aria-labelledby="embed-title"><div class="section-heading">diff --git a/site/ja/index.html b/site/ja/index.htmlindex b0a0f0e..563d6eb 100644--- a/site/ja/index.html+++ b/site/ja/index.html@@ -38,6 +38,7 @@<a class="header-link" href="#make">作り方</a><a class="header-link" href="#live">配信に使う</a><a class="header-link" href="#embed">組み込む</a>+ <a class="header-link" href="./play/">Player</a><a class="header-link" href="https://github.com/shinshin86/mesh-avatar-studio">GitHub <span aria-hidden="true">↗</span></a></nav><a class="header-link language-switch" href="../" lang="en" hreflang="en">English</a>@@ -51,6 +52,7 @@<p class="hero-description">Studio で作成・調整し、<span class="package-name">mesh-avatar</span> で自分のアプリに組み込めます。</p><div class="hero-actions"><a class="button primary" href="https://github.com/shinshin86/mesh-avatar-studio">GitHub で始める <span aria-hidden="true">↗</span></a>+ <a class="button secondary" href="./play/">ブラウザで試す</a><a class="button secondary" href="https://www.npmjs.com/package/mesh-avatar">npm で見る <span aria-hidden="true">↗</span></a></div><p class="hero-note">エディタはローカルで動きます。</p>@@ -195,7 +197,7 @@</figure></article></div>- <p class="section-note">どちらの画面もローカルの開発サーバーで動きます。配信中は、操作画面を専用のウィンドウで開いたままにしてください。<a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">配信の詳しい使い方(英語)<span aria-hidden="true">↗</span></a></p>+ <p class="section-note">どちらの画面もローカルの開発サーバーで動きます。配信中は、操作画面を専用のウィンドウで開いたままにしてください。セットアップなしで試すなら、<a href="./play/">Player</a> で .mavatar ファイルをブラウザ上でカメラとマイクで動かし、OBS のウィンドウキャプチャで取り込めます。<a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">配信の詳しい使い方(英語)<span aria-hidden="true">↗</span></a></p></section><section id="embed" class="content-section" aria-labelledby="embed-title"><div class="section-heading">diff --git a/site/ja/play/index.html b/site/ja/play/index.htmlnew file mode 100644index 0000000..46d5b17--- /dev/null+++ b/site/ja/play/index.html@@ -0,0 +1,20 @@+<!doctype html>+<html lang="ja">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'" />+ <meta name="description" content=".mavatar ファイルを開き、カメラとマイクでアバターをブラウザ上ですぐに動かせます。OBS に取り込んで配信にも使えます。" />+ <title>Mesh Avatar Player — ブラウザでアバターを動かす</title>+ <link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/ja/play/" />+ <link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/play/" />+ <link rel="alternate" hreflang="ja" href="https://shinshin86.github.io/mesh-avatar-studio/ja/play/" />+ <link rel="alternate" hreflang="x-default" href="https://shinshin86.github.io/mesh-avatar-studio/play/" />+ <link rel="icon" href="/favicon.svg" type="image/svg+xml" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <script type="module" src="/src/player/main.tsx"></script>+ </head>+ <body>+ <div id="root"></div>+ </body>+</html>diff --git a/site/play/index.html b/site/play/index.htmlnew file mode 100644index 0000000..d0b111c--- /dev/null+++ b/site/play/index.html@@ -0,0 +1,20 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'" />+ <meta name="description" content="Open a .mavatar file and move the avatar with your camera and microphone, right in your browser. Show it in OBS for streaming." />+ <title>Mesh Avatar Player — Move an avatar in your browser</title>+ <link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/play/" />+ <link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/play/" />+ <link rel="alternate" hreflang="ja" href="https://shinshin86.github.io/mesh-avatar-studio/ja/play/" />+ <link rel="alternate" hreflang="x-default" href="https://shinshin86.github.io/mesh-avatar-studio/play/" />+ <link rel="icon" href="/favicon.svg" type="image/svg+xml" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <script type="module" src="/src/player/main.tsx"></script>+ </head>+ <body>+ <div id="root"></div>+ </body>+</html>diff --git a/site/src/player/PlayerApp.tsx b/site/src/player/PlayerApp.tsxnew file mode 100644index 0000000..6e5729c--- /dev/null+++ b/site/src/player/PlayerApp.tsx@@ -0,0 +1,275 @@+import { colorHex, LIVE_EXPRESSIONS, loadMeshAvatar, type LiveExpression, type MeshAvatar } from 'mesh-avatar';+import { useEffect, useRef, useState, type DragEvent } from 'react';+import { Icon } from '../../../src/editor/Icon';+import { LightHandle, LightingControls, lightingText } from '../../../src/lighting/Controls';+import { loadLightingPresets, sameLighting, saveLightingPresets } from '../../../src/lighting/presets';+import { loadLighting, saveLighting } from '../../../src/lighting/storage';+import { liveText } from '../../../src/live/i18n';+import { CameraCapture, MicrophoneCapture, type BackgroundTracking, type CameraState, type MicState } from '../../../src/live/media';+import { backgroundColor } from '../../../src/live/settings';+import { FacePose, type TrackingOptions } from '../../../src/live/tracking';+import { runAvatarLoop } from './loop';+import { playerText, type PlayerLanguage } from './text';++// Settings saved in this browser use their own key, separate from Studio projects.+const STORAGE_KEY = 'player';+const MAX_BYTES = 128 * 1024 * 1024;+const SAMPLE_URL = `${import.meta.env.BASE_URL}miko.mavatar`;+const WORKER_URL = `${import.meta.env.BASE_URL}mediapipe/tracking-worker.js`;+const MIKO_TERMS = 'https://miko.aituberonair.com/#terms';+const STUDIO_URL = 'https://github.com/shinshin86/mesh-avatar-studio';++type Source = { kind: 'sample' } | { kind: 'file'; file: File };+type ViewState = 'loading' | 'ready';+type Notice = 'loadError' | 'tooLarge' | null;+interface DocumentPictureInPicture { requestWindow(options?: { width?: number; height?: number }): Promise<Window> }+const pictureInPicture = () => (window as Window & { documentPictureInPicture?: DocumentPictureInPicture }).documentPictureInPicture;++export function PlayerApp({ language }: { language: PlayerLanguage }) {+ const t = { ...liveText[language], ...playerText[language] };+ const [source, setSource] = useState<Source>({ kind: 'sample' });+ const goodSource = useRef<Source>(source);+ const [viewState, setViewState] = useState<ViewState>('loading');+ const [notice, setNotice] = useState<Notice>(null);+ const [dragging, setDragging] = useState(false);+ const [background, setBackground] = useState('transparent');+ const [fit, setFit] = useState<'contain' | 'cover'>('contain');+ const [lighting, setLighting] = useState(() => loadLighting(STORAGE_KEY));+ const [lightingOpen, setLightingOpen] = useState(false);+ const [presets, setPresets] = useState(() => loadLightingPresets(STORAGE_KEY));+ const presetsRef = useRef(presets); presetsRef.current = presets;+ const [expression, setExpression] = useState<LiveExpression>('neutral');+ const expressionRef = useRef(expression); expressionRef.current = expression;+ 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 [backgroundStatus, setBackgroundStatus] = useState<BackgroundTracking>(null);+ const [popup, setPopup] = useState<Window | null>(null);+ const [fullWindow, setFullWindow] = useState(false), [exitHint, setExitHint] = useState(false);+ const stage = useRef<HTMLDivElement>(null), video = useRef<HTMLVideoElement>(null), fileInput = useRef<HTMLInputElement>(null);+ // React never renders this canvas, so it can move to the avatar window and back.+ const [canvas] = useState(() => Object.assign(document.createElement('canvas'), { className: 'player-canvas' }));+ const loop = useRef<ReturnType<typeof runAvatarLoop> | null>(null);+ const camera = useRef<CameraCapture | null>(null), microphone = useRef<MicrophoneCapture | null>(null);+ const avatarRef = useRef<MeshAvatar | null>(null);+ const lightRef = useRef(lighting); lightRef.current = lighting;+ const pose = useRef(new FacePose());+ const controls = useRef({ options, gain, micState }); controls.current = { options, gain, micState };+ const refreshDevices = () => { void navigator.mediaDevices?.enumerateDevices().then(setDevices).catch(() => undefined); };++ useEffect(() => {+ canvas.dataset.testid = 'player-avatar';+ if (!popup) stage.current?.prepend(canvas);+ }, [canvas, popup]);+ useEffect(() => {+ const capture = new CameraCapture(video.current!, (result, now) => pose.current.update(result, now), state => { setCameraState(state); if (state !== 'running') setTracking(false); }, WORKER_URL);+ 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(() => {+ // Timers keep the hidden-page warning current while the avatar window is in front.+ const timer = setInterval(() => {+ const now = performance.now();+ setBackgroundStatus(camera.current?.backgroundStatus(document.visibilityState === 'hidden', now) ?? null);+ }, 500);+ return () => clearInterval(timer);+ }, []);+ useEffect(() => {+ let cancelled = false, avatar: MeshAvatar | undefined;+ setViewState('loading');+ const load = source.kind === 'sample' ? SAMPLE_URL : source.file;+ void loadMeshAvatar(canvas, load, { manual: true, fit, preserveMouthForm: true }).then(value => {+ if (cancelled) { value.destroy(); return; }+ avatar = value; avatarRef.current = value; goodSource.current = source;+ value.setLighting(lightRef.current); value.setExpression(expressionRef.current);+ loop.current = runAvatarLoop(value, canvas, (now, dt) => {+ const control = controls.current, sampled = pose.current.sample(now, dt, control.options);+ setTracking(sampled.tracking);+ value.setAutoIdle(!sampled.tracking); value.setAutoMotion(!sampled.tracking);+ value.setParameters(sampled.params, sampled.weight);+ const micOn = control.micState === 'micOn';+ value.setSpeaking(micOn); value.setVoiceLevel(micOn ? microphone.current?.level(control.gain) ?? 0 : 0);+ });+ setViewState('ready');+ }).catch(() => {+ if (cancelled) return;+ setNotice('loadError');+ // Return to the last avatar that opened, or to the sample if none did.+ setSource(goodSource.current === source ? { kind: 'sample' } : goodSource.current);+ });+ return () => { cancelled = true; loop.current?.stop(); loop.current = null; avatar?.destroy(); avatarRef.current = null; };+ }, [source, fit, canvas]);+ useEffect(() => { saveLighting(STORAGE_KEY, lighting); avatarRef.current?.setLighting(lighting); }, [lighting]);+ useEffect(() => { avatarRef.current?.setExpression(expression); }, [expression]);+ useEffect(() => {+ // The exit hint shows briefly only, so it does not appear in a window capture later.+ setExitHint(fullWindow);+ if (!fullWindow) return;+ const timer = setTimeout(() => setExitHint(false), 3000);+ return () => clearTimeout(timer);+ }, [fullWindow]);++ const openFile = (file: File | undefined) => {+ if (!file) return;+ if (file.size > MAX_BYTES) { setNotice('tooLarge'); return; }+ setNotice(null); setSource({ kind: 'file', file });+ };+ const applyPreset = (preset: number) => { const value = presetsRef.current[preset - 1]; if (value) setLighting({ ...value }); };+ const savePreset = (index: number) => {+ const next = presets.map((value, i) => i === index ? { ...lighting } : value);+ setPresets(next); saveLightingPresets(STORAGE_KEY, next);+ };+ const applyPresetRef = useRef(applyPreset); applyPresetRef.current = applyPreset;+ const fullWindowRef = useRef(fullWindow); fullWindowRef.current = fullWindow;+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ const target = event.target as HTMLElement | null;+ if (event.key === 'Escape' && fullWindowRef.current) { setFullWindow(false); return; }+ if (event.repeat || event.altKey || event.ctrlKey || event.metaKey || target?.closest?.('input, select, textarea, [contenteditable="true"]')) return;+ if (event.shiftKey) {+ const preset = /^Digit([1-8])$/.exec(event.code);+ if (preset) { event.preventDefault(); applyPresetRef.current(Number(preset[1])); }+ return;+ }+ const name = LIVE_EXPRESSIONS[Number(event.key) - 1];+ if (!/^[1-8]$/.test(event.key) || !name) return;+ event.preventDefault(); setExpression(name);+ };+ window.addEventListener('keydown', onKey);+ popup?.addEventListener('keydown', onKey);+ return () => { window.removeEventListener('keydown', onKey); popup?.removeEventListener('keydown', onKey); };+ }, [popup]);+ useEffect(() => {+ if (!popup) return;+ popup.document.body.style.background = background === 'transparent' ? '#ffffff' : background;+ }, [popup, background]);++ const openPopup = async () => {+ const pip = pictureInPicture();+ if (!pip || popup) return;+ const rect = canvas.getBoundingClientRect();+ const size = Math.round(Math.min(720, Math.max(360, rect.height)));+ const win = await pip.requestWindow({ width: size, height: size });+ win.document.title = 'Mesh Avatar';+ const style = win.document.createElement('style');+ style.textContent = 'html, body { margin: 0; height: 100%; overflow: hidden; } .player-canvas { display: block; width: 100vw; height: 100vh; }';+ win.document.head.append(style);+ win.document.body.append(canvas);+ loop.current?.retarget();+ win.addEventListener('pagehide', () => {+ stage.current?.prepend(canvas);+ loop.current?.retarget();+ setPopup(null);+ }, { once: true });+ setPopup(win);+ };++ const onDrag = (event: DragEvent) => {+ if (!event.dataTransfer.types.includes('Files')) return;+ event.preventDefault();+ setDragging(event.type !== 'dragleave' || event.currentTarget.contains(event.relatedTarget as Node | null));+ };+ const onDrop = (event: DragEvent) => {+ if (!event.dataTransfer.types.includes('Files')) return;+ event.preventDefault(); setDragging(false);+ openFile(event.dataTransfer.files[0]);+ };++ const cameraActive = cameraState === 'starting' || cameraState === 'running';+ const micActive = micState === 'micStarting' || micState === 'micOn';+ const status = cameraState === 'running' ? tracking ? 'tracking' : 'lost' : cameraState;+ const sourceName = source.kind === 'sample' ? t.sample : source.file.name;+ const otherLanguage = language === 'ja' ? '../../play/' : '../ja/play/';+ const canPopOut = !!pictureInPicture();+ const stageBackground = { backgroundColor: background, backgroundImage: background === 'transparent' ? undefined : 'none' };++ return <main className={`live-app player-app${fullWindow ? ' player-full' : ''}`} onDragEnter={onDrag} onDragOver={onDrag} onDragLeave={onDrag} onDrop={onDrop}>+ <header className="live-header"><div><a href="../" aria-label={t.home}>Mesh Avatar Studio</a><h1>Mesh Avatar <span>{t.title}</span></h1></div>+ <a className="player-language" href={otherLanguage} lang={language === 'ja' ? 'en' : 'ja'}>{t.otherLanguage}</a>+ </header>+ <p className="player-intro">{t.intro}</p>+ <div className="live-layout"><section className="live-view">+ <div ref={stage} className="live-preview checkerboard lighting-preview player-stage" style={stageBackground} onClick={() => { if (fullWindow) setFullWindow(false); }}>+ {popup && <p className="player-popped">{t.popped}</p>}+ {lightingOpen && !popup && !fullWindow && <LightHandle value={lighting} onChange={setLighting} language={language} />}+ {dragging && <div className="player-drop" aria-hidden="true">{t.dropHere}</div>}+ </div>+ <p role="status" data-testid="player-status">{t[viewState]} · {sourceName}</p>+ {exitHint && <p className="player-exit" data-testid="player-exit-hint">{t.exitFullWindow}</p>}+ </section>+ <aside className="live-controls">+ <section><h2>{t.avatar}</h2>+ <p className="player-source" data-testid="player-source">{sourceName}</p>+ <div className="live-buttons">+ <button className="live-primary" onClick={() => fileInput.current?.click()}>{t.open}</button>+ {source.kind === 'file' && <button onClick={() => { setNotice(null); setSource({ kind: 'sample' }); }}>{t.useSample}</button>}+ </div>+ <input ref={fileInput} type="file" accept=".mavatar" hidden data-testid="player-file" onChange={event => { openFile(event.target.files?.[0]); event.target.value = ''; }} />+ {notice && <p role="alert" className="live-error" data-testid="player-notice">{t[notice]}</p>}+ <small>{t.dropHint}</small>+ <small><a href={STUDIO_URL}>{t.makeOwn}</a></small>+ </section>+ <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>+ {backgroundStatus && <p role="alert" className="live-error">{t[backgroundStatus]}</p>}+ <small>{calibrated ? t.calibrated : t.calibrateHint}</small>+ <label className="live-check"><input type="checkbox" checked={options.mirror} onChange={event => setOptions(current => ({ ...current, mirror: event.target.checked }))} />{t.mirror}</label>+ <label>{t.sensitivity}<input type="range" min="0.25" max="2" step="0.05" value={options.sensitivity} onChange={event => setOptions(current => ({ ...current, sensitivity: Number(event.target.value) }))} /></label>+ <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={background} onChange={event => setBackground(backgroundColor(event.target.value))}>+ <option value="transparent">{t.none}</option><option value="#00ff00">{t.green}</option><option value="#0000ff">{t.blue}</option>{!['transparent', '#00ff00', '#0000ff'].includes(background) && <option value={background}>{t.custom}</option>}+ </select><small className="background-hint" data-testid="background-hint">{background === 'transparent' ? t.bgHintNone : ['#00ff00', '#0000ff'].includes(background) ? t.bgHintChroma : t.bgHintCustom}</small>+ <label>{t.custom}<input type="color" value={background === 'transparent' ? '#ffffff' : background} onChange={event => setBackground(event.target.value)} /></label>+ <label>{t.fit}<select value={fit} onChange={event => setFit(event.target.value as 'contain' | 'cover')}><option value="contain">{t.contain}</option><option value="cover">{t.cover}</option></select></label>+ </section>+ <section><h2>{t.show}</h2><small>{t.showHelp}</small>+ <div className="live-buttons player-show">+ {canPopOut+ ? <button className="live-primary" disabled={viewState !== 'ready'} onClick={() => { if (popup) popup.close(); else void openPopup().catch(() => undefined); }}>{popup ? t.popIn : t.popOut}</button>+ : <small>{t.popOutUnsupported}</small>}+ <button disabled={!!popup} onClick={() => setFullWindow(true)}>{t.fullWindow}</button>+ </div>+ <small>{t.keepVisible}</small>+ </section>+ <details className="live-expression" data-testid="expression-section">+ <summary><Icon name="face" />{t.expression}{expression !== 'neutral' && <span className="expression-on">{t[expression]}</span>}</summary>+ <div className="live-expression-body"><div className="expression-buttons" role="group" aria-label={t.expression}>+ {LIVE_EXPRESSIONS.map((name, i) => <button key={name} type="button" aria-pressed={expression === name} aria-keyshortcuts={String(i + 1)} onClick={() => setExpression(name)}><kbd>{i + 1}</kbd>{t[name]}</button>)}+ </div><small>{t.expressionHint}</small></div>+ </details>+ <details className="live-lighting" data-testid="lighting-section" onToggle={event => setLightingOpen(event.currentTarget.open)}>+ <summary><Icon name="light" />{lightingText[language].title}{lighting.enabled && <span className="lighting-on">ON</span>}</summary>+ <div className="lighting-presets"><h3>{t.presets}</h3>+ <div className="preset-slots" role="group" aria-label={t.presets}>+ {presets.map((value, i) => <div className="preset-slot" key={i}>+ <button type="button" disabled={!value} aria-label={`${t.preset} ${i + 1}${value ? '' : ` (${t.presetEmpty})`}`} aria-pressed={!!value && sameLighting(value, lighting)} aria-keyshortcuts={`Shift+${i + 1}`} onClick={() => applyPreset(i + 1)}>+ <kbd>⇧{i + 1}</kbd>{value ? <span className={`preset-swatch${value.enabled ? '' : ' off'}`} style={value.enabled ? { background: `linear-gradient(135deg, ${colorHex(value.color)} 50%, ${colorHex(value.ambientColor)} 50%)` } : undefined} /> : t.presetEmpty}</button>+ <button type="button" className="preset-save" aria-label={`${t.presetSave}: ${t.preset} ${i + 1}`} onClick={() => savePreset(i)}>{t.presetSave}</button>+ </div>)}+ </div><small>{t.presetHint}</small>+ </div>+ <LightingControls value={lighting} onChange={setLighting} language={language} />+ </details>+ <p className="live-privacy">{t.privacy}</p>+ {source.kind === 'sample' && <p className="live-privacy">{t.credit} <a href={MIKO_TERMS}>{t.terms}</a></p>}+ </aside></div>+ </main>;+}diff --git a/site/src/player/loop.ts b/site/src/player/loop.tsnew file mode 100644index 0000000..6fb3e93--- /dev/null+++ b/site/src/player/loop.ts@@ -0,0 +1,28 @@+import type { MeshAvatar } from 'mesh-avatar';++/**+ * Draws the avatar on the animation frames of whichever window currently holds the canvas,+ * so it keeps moving after the canvas moves to a Picture-in-Picture window. Frame times use+ * this page's clock: other windows have a different time origin.+ */+export function runAvatarLoop(avatar: MeshAvatar, canvas: HTMLCanvasElement, beforeFrame: (now: number, dt: number) => void) {+ let host: Window = window, raf = 0, previous = performance.now(), stopped = false;+ const frame = () => {+ const now = performance.now(), dt = Math.min(0.05, Math.max(0.001, (now - previous) / 1000));+ previous = now;+ beforeFrame(now, dt);+ avatar.advance(dt, 1 / dt);+ schedule();+ };+ const schedule = () => {+ if (stopped) return;+ host = canvas.ownerDocument.defaultView ?? window;+ raf = host.requestAnimationFrame(frame);+ };+ schedule();+ return {+ /** Call after moving the canvas to another document. */+ retarget() { host.cancelAnimationFrame(raf); previous = performance.now(); schedule(); },+ stop() { stopped = true; host.cancelAnimationFrame(raf); },+ };+}diff --git a/site/src/player/main.tsx b/site/src/player/main.tsxnew file mode 100644index 0000000..e7de9dd--- /dev/null+++ b/site/src/player/main.tsx@@ -0,0 +1,7 @@+import { createRoot } from 'react-dom/client';+import '../../../src/live/live.css';+import './player.css';+import { PlayerApp } from './PlayerApp';++const language = document.documentElement.lang === 'ja' ? 'ja' : 'en';+createRoot(document.getElementById('root')!).render(<PlayerApp language={language} />);diff --git a/site/src/player/player.css b/site/src/player/player.cssnew file mode 100644index 0000000..425a5fb--- /dev/null+++ b/site/src/player/player.css@@ -0,0 +1,21 @@+.player-app .live-header a { font-size: 13px; text-decoration: none; }+.player-app .live-header a:hover { text-decoration: underline; }+.player-language { flex-shrink: 0; }+.player-intro { margin: -8px 0 16px; color: #546a87; }+.player-stage { position: relative; }+.player-canvas { display: block; width: 100%; height: 100%; }+.player-popped, .player-drop { position: absolute; inset: 0; display: grid; place-content: center; margin: 0; padding: 24px; text-align: center; }+.player-popped { color: #546a87; background: #f3f5f8; }+.player-drop { z-index: 3; border: 3px dashed #3977d8; border-radius: 12px; background: #e8f0fdee; color: #1d4f9c; font-weight: 600; }+.player-source { margin: 0 0 12px; font-weight: 600; overflow-wrap: anywhere; }+.player-show { margin: 12px 0; }+.player-exit { margin: 0; color: #546a87; font-size: 12px; text-align: center; }++/* Avatar only: the stage fills the window for a window capture. */+.player-full { max-width: none; padding: 0; }+.player-full .live-header, .player-full .player-intro, .player-full .live-controls, .player-full [data-testid="player-status"] { display: none; }+.player-full .live-layout { display: block; }+.player-full .live-preview { height: 100dvh; border: 0; border-radius: 0; }+.player-full .player-exit { position: fixed; bottom: 12px; left: 50%; transform: translateX(-50%); padding: 6px 12px; border-radius: 999px; background: #162132cc; color: white; }++@media (max-width: 480px) { .player-app { padding: 12px 16px; } }diff --git a/site/src/player/text.ts b/site/src/player/text.tsnew file mode 100644index 0000000..999dcb7--- /dev/null+++ b/site/src/player/text.ts@@ -0,0 +1,77 @@+export type PlayerLanguage = 'en' | 'ja';++const en = {+ title: 'Player',+ home: 'Mesh Avatar Studio home',+ otherLanguage: '日本語',+ intro: 'Move a mesh avatar with your face and voice, right in this browser. Nothing to install.',+ avatar: 'Avatar',+ sample: 'Miko (sample)',+ open: 'Open .mavatar file',+ useSample: 'Use the sample',+ dropHint: 'Or drop a .mavatar file anywhere on this page.',+ makeOwn: 'Make your own avatar with Mesh Avatar Studio',+ loading: 'Loading avatar…',+ ready: 'Avatar ready',+ loadError: 'Could not open this file. Choose a .mavatar file exported from Mesh Avatar Studio.',+ tooLarge: 'This file is larger than 128 MiB.',+ dropHere: 'Drop the .mavatar file to open it',+ background: 'Background',+ none: 'None (preview only)',+ bgHintNone: 'Window captures cannot keep transparency. For OBS, choose green or blue.',+ bgHintChroma: 'In OBS, add a Chroma Key filter to the capture with the same key colour.',+ bgHintCustom: 'In OBS, add a Color Key filter to the capture set to this colour.',+ show: 'Show in OBS',+ showHelp: 'Open the avatar in its own window, then add that window to OBS with Window Capture (on macOS, macOS Screen Capture in window mode).',+ popOut: 'Open avatar window',+ popIn: 'Close avatar window',+ popped: 'The avatar is shown in its own window.',+ popOutUnsupported: 'Avatar windows need Chrome or Edge. Use “Avatar only in this window” instead.',+ fullWindow: 'Avatar only in this window',+ exitFullWindow: 'Press Esc or click to show the controls again.',+ keepVisible: 'Keep the avatar window visible. Browsers pause drawing in windows that are minimized or fully covered.',+ privacy: 'Everything runs in this browser. The avatar file, camera video and microphone audio are not uploaded.',+ credit: 'Miko © Yuki Shindo (AITuber OnAir).',+ terms: 'Usage guidelines',+ presetHint: 'Save stores the current lighting in that slot. While this page or the avatar window is focused, Shift+1–8 apply presets.',+ expressionHint: 'While this page or the avatar window is focused, keys 1–8 switch expressions. Key 1 returns to neutral.',+};++const ja: typeof en = {+ title: 'Player',+ home: 'Mesh Avatar Studio のトップへ',+ otherLanguage: 'English',+ intro: 'メッシュアバターを、顔と声でこのブラウザ上ですぐに動かせます。インストールは不要です。',+ avatar: 'アバター',+ sample: 'ミコ(サンプル)',+ open: '.mavatar ファイルを開く',+ useSample: 'サンプルに戻す',+ dropHint: 'ページのどこかに .mavatar ファイルをドロップしても開けます。',+ makeOwn: 'Mesh Avatar Studio で自分のアバターを作る',+ loading: 'アバターを読み込み中…',+ ready: 'アバターの準備ができました',+ loadError: 'このファイルを開けませんでした。Mesh Avatar Studio から書き出した .mavatar ファイルを選んでください。',+ tooLarge: 'ファイルが 128 MiB を超えています。',+ dropHere: 'ドロップして .mavatar ファイルを開く',+ background: '背景',+ none: 'なし(プレビュー用)',+ bgHintNone: 'ウィンドウキャプチャでは透過を保てません。OBS で使うときは緑か青を選んでください。',+ bgHintChroma: 'OBS ではキャプチャに「クロマキー」フィルタを追加し、同じ色を指定します。',+ bgHintCustom: 'OBS ではキャプチャに「カラーキー」フィルタを追加し、この色を指定します。',+ show: 'OBS で使う',+ showHelp: 'アバターを専用ウィンドウで開き、OBS の「ウィンドウキャプチャ」(macOS では「macOS 画面キャプチャ」のウィンドウ指定)で取り込みます。',+ popOut: 'アバターウィンドウを開く',+ popIn: 'アバターウィンドウを閉じる',+ popped: 'アバターは専用ウィンドウに表示しています。',+ popOutUnsupported: 'アバターウィンドウには Chrome か Edge が必要です。代わりに「このウィンドウをアバターだけにする」を使ってください。',+ fullWindow: 'このウィンドウをアバターだけにする',+ exitFullWindow: 'Esc キーかクリックで操作パネルに戻ります。',+ keepVisible: 'アバターのウィンドウは見える状態にしておいてください。最小化したり完全に隠れたりすると、ブラウザが描画を止めます。',+ privacy: 'すべてこのブラウザ内で動きます。アバターファイル、カメラ映像、マイク音声はアップロードされません。',+ credit: 'ミコ © Yuki Shindo (AITuber OnAir)',+ terms: '利用ガイドライン',+ presetHint: '「保存」で今のライティングをその枠に保存します。この画面かアバターウィンドウを操作している間は、Shift+1〜8でプリセットを呼び出せます。',+ expressionHint: 'この画面かアバターウィンドウを操作している間は、キー1〜8で表情を切り替えられます。通常に戻すときはキー1を押します。',+};++export const playerText = { en, ja };diff --git a/site/vite.config.ts b/site/vite.config.tsindex 2be5395..2d20f38 100644--- a/site/vite.config.ts+++ b/site/vite.config.ts@@ -2,9 +2,11 @@ import { readFileSync } from 'node:fs';import { createRequire } from 'node:module';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';+import react from '@vitejs/plugin-react';import { defineConfig, type Plugin } from 'vite';import { packProjectAvatar } from '../packages/runtime/src/format/project-archive';import { readAvatarFolder } from '../tools/avatar-files.mjs';+import { mediapipeAssets } from '../src/server/mediapipe-assets';const fromHere = (path: string) => fileURLToPath(new URL(path, import.meta.url));const base = '/mesh-avatar-studio/';@@ -73,7 +75,8 @@ export default defineConfig({root: fromHere('./'),base,publicDir: false,- plugins: [sampleAvatar(), socialImage()],+ // The Player page tracks the face in the browser with the same local MediaPipe files as Studio.+ plugins: [react(), sampleAvatar(), socialImage(), mediapipeAssets(fromHere('..'), base)],resolve: { alias: { 'mesh-avatar': fromHere('../packages/runtime/src/index.ts') } },server: {host: '127.0.0.1',@@ -90,6 +93,8 @@ export default defineConfig({input: {en: fromHere('./index.html'),ja: fromHere('./ja/index.html'),+ play: fromHere('./play/index.html'),+ 'ja-play': fromHere('./ja/play/index.html'),},output: { banner: `/*! fflate\n${fflateLicense}\n*/` },},diff --git a/src/live/face-tracker.ts b/src/live/face-tracker.tsindex 7a4ea2c..1492cb2 100644--- a/src/live/face-tracker.ts+++ b/src/live/face-tracker.ts@@ -6,4 +6,5 @@ export type TrackingWorkerMessage =| { type: 'consumed' | 'tick' | 'error' };// Classic worker: the pinned MediaPipe runtime loads its local WASM glue with importScripts.-export function createTrackingWorker() { return new Worker('/mediapipe/tracking-worker.js'); }+// Studio serves the files at /mediapipe/; other sites pass their own worker URL.+export function createTrackingWorker(url = '/mediapipe/tracking-worker.js') { return new Worker(url); }diff --git a/src/live/media.ts b/src/live/media.tsindex cc1ef5c..9ae5796 100644--- a/src/live/media.ts+++ b/src/live/media.ts@@ -17,7 +17,8 @@ export class CameraCapture {private started = Infinity;private results: number[] = [];readonly timing = { frames: 0, totalMs: 0, maxMs: 0, delegate: '', source: '' };- constructor(private video: HTMLVideoElement, private onResult: (result: FaceResult, now: number) => void, private onState: (state: CameraState) => void) {}+ constructor(private video: HTMLVideoElement, private onResult: (result: FaceResult, now: number) => void, private onState: (state: CameraState) => void,+ private workerUrl?: string) {}stop() {this.generation++;if (this.videoCallback) this.video.cancelVideoFrameCallback?.(this.videoCallback);@@ -51,7 +52,7 @@ export class CameraCapture {// Preview playback must not gate track processing when the document is hidden.void this.video.play().catch(() => undefined);loadingModel = true;- const worker = createTrackingWorker(); this.worker = worker;+ const worker = createTrackingWorker(this.workerUrl); this.worker = worker;const fail = () => { if (generation === this.generation) { this.stop(); this.onState('modelError'); } };worker.onerror = fail;worker.onmessage = ({ data }: MessageEvent<TrackingWorkerMessage>) => {diff --git a/src/live/tracking-worker.js b/src/live/tracking-worker.jsindex e3accda..7c65dc7 100644--- a/src/live/tracking-worker.js+++ b/src/live/tracking-worker.js@@ -1,17 +1,19 @@// Camera frames stay in this worker. Only the face pose and timing return to the page.+// Asset paths are relative to this worker, so the files can be served under any folder.+const base = new URL('.', self.location.href).href.replace(/\/$/, '');self.exports = {};-self.importScripts('/mediapipe/vision_bundle.cjs');+self.importScripts(`${base}/vision_bundle.js`);const { FaceLandmarker, FilesetResolver } = self.exports;let tracker, lastFrame = -Infinity, delegate = 'GPU', frames = 0, gpuSamples = 0, gpuMs = 0;self.onmessage = async ({ data }) => {if (data.type === 'init') {try {- const files = await FilesetResolver.forVisionTasks('/mediapipe');+ const files = await FilesetResolver.forVisionTasks(base);const options = { runningMode: 'VIDEO', numFaces: 1, outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true };- try { tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: '/mediapipe/face_landmarker.task', delegate } }); }+ 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: '/mediapipe/face_landmarker.task', delegate } });+ tracker = await FaceLandmarker.createFromOptions(files, { ...options, baseOptions: { modelAssetPath: `${base}/face_landmarker.task`, delegate } });}self.postMessage({ type: 'ready', delegate });// Also wakes the ImageBitmap fallback when video frame callbacks stop in a hidden tab.diff --git a/src/server/mediapipe-assets.ts b/src/server/mediapipe-assets.tsindex 040c664..21c4a0b 100644--- a/src/server/mediapipe-assets.ts+++ b/src/server/mediapipe-assets.ts@@ -2,10 +2,12 @@ import { readFile } from 'node:fs/promises';import { resolve } from 'node:path';import type { Plugin } from 'vite';-export function mediapipeAssets(root: string): Plugin {+/** Serves the tracking files under `${prefix}mediapipe/` in development and emits them to `mediapipe/`. */+export function mediapipeAssets(root: string, prefix = '/'): Plugin {const files = new Map([['tracking-worker.js', resolve(root, 'src/live/tracking-worker.js')],- ['vision_bundle.cjs', resolve(root, 'node_modules/@mediapipe/tasks-vision/vision_bundle.cjs')],+ // 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'].map(name => [name, resolve(root, 'node_modules/@mediapipe/tasks-vision/wasm', name)] as const),['face_landmarker.task', resolve(root, 'vendor/mediapipe/face_landmarker.task')],@@ -15,8 +17,9 @@ export function mediapipeAssets(root: string): Plugin {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);+ const folder = `${prefix}mediapipe/`;+ if (!url?.startsWith(folder)) { next(); return; }+ const name = url.slice(folder.length), path = files.get(name);if (!path || !['GET', 'HEAD'].includes(req.method ?? '')) { res.writeHead(404); res.end(); return; }try {const data = await readFile(path);diff --git a/tests/live-worker.test.ts b/tests/live-worker.test.tsindex 04007c0..ae19e6a 100644--- a/tests/live-worker.test.ts+++ b/tests/live-worker.test.ts@@ -8,17 +8,17 @@ test('worker falls back from GPU to CPU, keeps frames local and closes both acceconst detectForVideo = vi.fn(() => result), create = vi.fn().mockRejectedValueOnce(new Error('GPU unavailable')).mockResolvedValue({ detectForVideo });const postMessage = vi.fn(), now = vi.fn(() => 0), tick = vi.fn();const scope = {- exports: {}, postMessage, setInterval: tick,+ exports: {}, postMessage, setInterval: tick, location: { href: 'http://127.0.0.1:5173/mediapipe/tracking-worker.js' },importScripts: vi.fn((url: string) => {- expect(url).toBe('/mediapipe/vision_bundle.cjs');- scope.exports = { FaceLandmarker: { createFromOptions: create }, FilesetResolver: { forVisionTasks: async (path: string) => { expect(path).toBe('/mediapipe'); return {}; } } };+ expect(url).toBe('http://127.0.0.1:5173/mediapipe/vision_bundle.js');+ scope.exports = { FaceLandmarker: { createFromOptions: create }, FilesetResolver: { forVisionTasks: async (path: string) => { expect(path).toBe('http://127.0.0.1:5173/mediapipe'); return {}; } } };}),onmessage: async (_event: { data: Record<string, unknown> }) => {},};- runInNewContext(source, { self: scope, performance: { now } });+ runInNewContext(source, { self: scope, performance: { now }, URL });await scope.onmessage({ data: { type: 'init' } });expect(create.mock.calls.map(call => call[1].baseOptions.delegate)).toEqual(['GPU', 'CPU']);- expect(create.mock.calls[1][1].baseOptions.modelAssetPath).toBe('/mediapipe/face_landmarker.task');+ expect(create.mock.calls[1][1].baseOptions.modelAssetPath).toBe('http://127.0.0.1:5173/mediapipe/face_landmarker.task');expect(postMessage).toHaveBeenCalledWith({ type: 'ready', delegate: 'CPU' });const frame = { close: vi.fn() };await scope.onmessage({ data: { type: 'frame', frame, timestamp: 0 } });@@ -36,11 +36,11 @@ test('worker changes an initialized but persistently slow GPU to CPU once afterlet now = 0;const setOptions = vi.fn(async () => undefined), postMessage = vi.fn();const tracker = { setOptions, detectForVideo: () => { now += 100; return { faceLandmarks: [], faceBlendshapes: [], facialTransformationMatrixes: [] }; } };- const scope = { exports: {}, postMessage, setInterval: vi.fn(),+ const scope = { exports: {}, postMessage, setInterval: vi.fn(), location: { href: 'http://127.0.0.1:5173/mediapipe/tracking-worker.js' },importScripts: () => { scope.exports = { FaceLandmarker: { createFromOptions: async () => tracker }, FilesetResolver: { forVisionTasks: async () => ({}) } }; },onmessage: async (_event: { data: Record<string, unknown> }) => {},};- runInNewContext(source, { self: scope, performance: { now: () => now } });+ runInNewContext(source, { self: scope, performance: { now: () => now }, URL });await scope.onmessage({ data: { type: 'init' } });for (let i = 0; i < 12; i++) await scope.onmessage({ data: { type: 'frame', frame: { close() {} }, timestamp: i * 100 } });expect(setOptions).not.toHaveBeenCalled();@@ -48,3 +48,19 @@ test('worker changes an initialized but persistently slow GPU to CPU once afterexpect(setOptions).toHaveBeenCalledExactlyOnceWith({ baseOptions: { delegate: 'CPU' } });expect(postMessage).toHaveBeenCalledWith({ type: 'delegate', delegate: 'CPU' });});++test('worker loads its files from the folder it is served from', async () => {+ const create = vi.fn().mockResolvedValue({ detectForVideo: vi.fn() }), imported: string[] = [], resolved: string[] = [];+ const scope = { exports: {}, postMessage: vi.fn(), setInterval: vi.fn(), location: { href: 'https://example.github.io/mesh-avatar-studio/mediapipe/tracking-worker.js' },+ importScripts: (url: string) => {+ imported.push(url);+ scope.exports = { FaceLandmarker: { createFromOptions: create }, FilesetResolver: { forVisionTasks: async (path: string) => { resolved.push(path); return {}; } } };+ },+ onmessage: async (_event: { data: Record<string, unknown> }) => {},+ };+ runInNewContext(source, { self: scope, performance: { now: () => 0 }, URL });+ await scope.onmessage({ data: { type: 'init' } });+ expect(imported).toEqual(['https://example.github.io/mesh-avatar-studio/mediapipe/vision_bundle.js']);+ expect(resolved).toEqual(['https://example.github.io/mesh-avatar-studio/mediapipe']);+ expect(create.mock.calls[0][1].baseOptions.modelAssetPath).toBe('https://example.github.io/mesh-avatar-studio/mediapipe/face_landmarker.task');+});