Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add mouth-movement settings for lip sync

shinshin86fc3e071b046a
diff --git a/.changeset/mouth-movement-settings.md b/.changeset/mouth-movement-settings.md
new file mode 100644
index 0000000..62c0730
--- /dev/null
+++ b/.changeset/mouth-movement-settings.md
@@ -0,0 +1,6 @@
+---
+"mesh-avatar": minor
+"mesh-avatar-element": minor
+---
+
+Add optional mouth-movement settings for audio loudness and kana previews: granularity, openness and closing speed. Configure them with `lipSync` or partial `setLipSync` updates; omitted and center values preserve the existing motion. Avatar manifests store the settings and optional editor preset, and loaders apply them. The element retains explicit property or method overrides across loads.
diff --git a/docs/format.md b/docs/format.md
index 6b3d9a4..157689e 100644
--- a/docs/format.md
+++ b/docs/format.md
@@ -53,8 +53,24 @@ source variants, masks and review images; these are not required for playback.
| `license` | Optional license text or reference to the artwork's terms. The runtime's MIT license does not grant rights to the artwork. |
| `source` | Optional original-image filename relative to the root, normally `source.png`. |
| `thumbnail` | Optional preview-image filename relative to the root, normally `thumbnail.png`. |
+| `lipSync` | Optional mouth-movement settings: `granularity`, `openness`, `closeSpeed` (each optional, finite 0–1, default 0.5). Optional `preset` records the editor selection (`calm`, `default`, `lively`, `subtle`, `big`, `custom`); playback always uses the numbers. An omitted or empty block preserves existing behavior. |
| `studio.version` | Optional version string identifying the Studio that prepared the avatar. |
+For example, `"lipSync": { "granularity": 0, "openness": 0.5, "closeSpeed": 0,
+"preset": "calm" }` selects smoother, less frequent closures. Low `granularity` reacts only
+to large loudness dips and groups short kana morae; high values separate smaller dips.
+`openness` scales mouth opening from 0.55 to 1.25 times the original amount (capped at 1),
+with exactly the original amount at 0.5. `closeSpeed` changes release from slow to quick.
+All three default to 0.5, preserving the existing animation exactly. `preset` does not
+change the numeric values or cause playback.
+
+The editor saves this block independently of the rig and preserves it on export/import.
+Preview audio is never stored in the archive. Loaders and Live/Player apply saved settings;
+explicit runtime settings override the corresponding saved fields. Audio-driven lip sync
+requires an application supplying analyzed loudness. Loading an avatar alone does not
+start a microphone. Older readers ignore this optional key. Format version and existing
+fields are unchanged. Unknown fields in the block are ignored.
+
On import, Studio saves the original image as `source.png` and updates `avatar.json.source` when its filename differs.
An existing folder without `avatar.json` has the effective manifest
diff --git a/docs/reference.md b/docs/reference.md
index b0d5a81..8737175 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -287,6 +287,56 @@ The camera is optional. Turn on only the microphone and the avatar keeps its idl
the camera the mouth keeps one shape and changes only how far it opens; drawn mouth images
are still used when the project has them.
+### Mouth movement settings
+
+The studio's **Lip sync** tab offers five styles: Relaxed, Standard, Snappy, Subtle and
+Expressive. Choosing one immediately previews the mouth motion with kana. Open **Fine-tune**
+to adjust movement, size and closing; adjusting a slider selects **Custom**, and releasing it
+previews the result. A user-started kana phrase keeps its current playback position while
+settings change. The disclosure also contains a local audio-file preview driven by loudness.
+Preview files stay in the browser and are not included in avatar exports.
+
+Each movement setting accepts a finite number from 0 to 1 and defaults to 0.5:
+
+| Setting | 0 | 0.5 (existing behavior) | 1 |
+| --- | --- | --- | --- |
+| `granularity` | Only large loudness dips separate syllables; merge short kana morae. | Existing sensitivity. | Smaller dips separate syllables; stronger kana closures. |
+| `openness` | Scale opening by 0.55. | Original opening amount. | Scale opening by 1.25, capped at 1. |
+| `closeSpeed` | Slow release (6/s). | Existing audio 32/s and kana 22/s release. | Quick release (45/s). |
+
+Configure the runtime when creating it, or update settings during playback:
+
+```ts
+import { createMeshAvatar, type LipSyncSettings } from 'mesh-avatar';
+
+const settings: LipSyncSettings = { granularity: 0, openness: 0.5, closeSpeed: 0 };
+const avatar = await createMeshAvatar(canvas, { rig, assets, lipSync: settings });
+avatar.setLipSync({ openness: 0.75 }); // retains the current movement and closing settings
+avatar.setSpeaking(true);
+avatar.setVoiceLevel(level); // normalized audio loudness, 0–1
+```
+
+`setLipSync(settings: LipSyncSettings): void` is a partial update: omitted or undefined fields
+retain their current values. Empty settings and omitted creation options use the existing
+behavior; explicitly setting all three numbers to 0.5 produces the same motion and random
+draws. Invalid objects, non-finite numbers and values outside 0–1 throw before changing settings.
+Openness also affects held-mouth previews. Low kana granularity groups adjacent short morae
+and softens brief closures; long pauses still close the mouth.
+
+Writable projects save the numbers and optional editor selection in `avatar.json.lipSync`;
+exports include them for browser-picked folders and read-only samples too. `loadMeshAvatar`
+applies these saved values, with explicit `options.lipSync` fields taking precedence. The
+Live page and browser Player apply the avatar's settings to their existing microphone
+loudness path. Loading an avatar alone does not start a microphone.
+
+The element exposes `element.lipSync: LipSyncSettings` (get/set) and
+`element.setLipSync(settings: LipSyncSettings): void`. Both assignment and the method apply
+partial updates. The getter returns a copy of explicit overrides; these survive source or
+fit changes and otherwise the avatar's saved values apply. The optional `preset` field
+(`calm`, `default`, `lively`, `subtle`, `big`, `custom`) records the editor selection only;
+playback always uses the three numbers. The React wrapper exposes the element through its
+ref, so call `ref.current.setLipSync(...)`; it has no dedicated settings prop.
+
### Video calls
To use the avatar in Zoom, Google Meet or other video-call apps, show the stream view in OBS
diff --git a/e2e/embed-element.spec.ts b/e2e/embed-element.spec.ts
index 6600983..1244216 100644
--- a/e2e/embed-element.spec.ts
+++ b/e2e/embed-element.spec.ts
@@ -239,3 +239,39 @@ test('coalesces connection, src and fit changes and exposes a pending ready imme
expect(defaults).toBe(0);
expect(explicit).toBe(1);
});
+
+
+test('mouth settings apply before loading, merge partial updates and survive fit and source reloads', async ({ page }) => {
+ await open(page);
+ const result = await page.evaluate(async src => {
+ const el = document.createElement('mesh-avatar');
+ el.paused = true;
+ el.lipSync = { granularity: 0, openness: 0 };
+ el.setLipSync({ closeSpeed: 0 });
+ document.body.append(el);
+ const opening = async () => {
+ const avatar = await el.ready;
+ avatar.setAutoIdle(false); avatar.setAutoMotion(false); avatar.holdMouth('a');
+ for (let i = 0; i < 60; i++) avatar.advance(1 / 60);
+ return avatar.getParameters().mouthOpen;
+ };
+ const before = await opening();
+ el.setLipSync({ openness: 1 });
+ const large = await opening();
+ const overrides = el.lipSync;
+ overrides.openness = 0; // The getter must not expose retained mutable state.
+ let rejected = false;
+ try { el.setLipSync({ openness: 2 }); } catch { rejected = true; }
+ const retained = el.lipSync;
+ el.fit = 'cover';
+ const fit = await opening();
+ el.src = src + '?settings-reload';
+ const source = await opening();
+ el.remove();
+ return { before, large, fit, source, rejected, retained };
+ }, sample);
+ expect(result.before).toBeCloseTo(0.495, 5);
+ for (const value of [result.large, result.fit, result.source]) expect(value).toBeCloseTo(1, 5);
+ expect(result.rejected).toBe(true);
+ expect(result.retained).toEqual({ granularity: 0, openness: 1, closeSpeed: 0 });
+});
diff --git a/e2e/lip-sync-settings.spec.ts b/e2e/lip-sync-settings.spec.ts
new file mode 100644
index 0000000..30fc3bb
--- /dev/null
+++ b/e2e/lip-sync-settings.spec.ts
@@ -0,0 +1,178 @@
+import { expect, test } from '@playwright/test';
+import { readFile, rm } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { unzipSync } from 'fflate';
+import { dismissGuide, samplePresent, sampleSkipReason } from './sample';
+
+function tone() {
+ const rate = 16000, samples = rate * 2, bytes = Buffer.alloc(44 + samples * 2);
+ bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8);
+ bytes.writeUInt32LE(16, 16); bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22);
+ bytes.writeUInt32LE(rate, 24); bytes.writeUInt32LE(rate * 2, 28); bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34);
+ bytes.write('data', 36); bytes.writeUInt32LE(samples * 2, 40);
+ for (let i = 0; i < samples; i++) bytes.writeInt16LE(Math.round(Math.sin(i * 2 * Math.PI * 150 / rate) * 3000), 44 + i * 2);
+ return bytes;
+}
+
+test('presets preview immediately, fine-tuning becomes custom and user kana keeps its playback position', async ({ page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto('/'); await dismissGuide(page);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByTestId('idle-toggle').click();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByRole('tab', { name: 'Lip sync', exact: true }).click();
+ const settings = page.getByTestId('audio-lip-settings');
+ await expect(page.locator('#lip-panel').getByTestId('audio-lip-settings')).toBeVisible();
+ await expect(settings.locator('.audio-lip-advanced')).not.toHaveAttribute('open', '');
+ await expect(settings.getByRole('button', { name: 'Preview a local audio file', exact: true })).toBeHidden();
+ const stop = page.locator('.lip-text-row').getByRole('button', { name: 'Stop', exact: true });
+ await expect(stop).toBeDisabled();
+ await expect(settings.getByRole('combobox')).toHaveCount(0);
+ await expect(settings.locator('input[type=checkbox]')).toHaveCount(0);
+ await expect(settings.getByRole('button', { name: 'Standard', exact: true })).toHaveAttribute('aria-pressed', 'true');
+ await settings.getByRole('button', { name: 'Relaxed', exact: true }).click();
+ await expect(stop).toBeEnabled();
+ await expect(page.locator('#lip-panel .lip-live input')).toBeDisabled();
+ await expect.poll(() => page.locator('#lip-panel .lip-live input').inputValue().then(Number)).toBeGreaterThan(0.3);
+ await expect(settings.getByLabel('Mouth movement', { exact: true })).toHaveValue('0');
+ await expect(settings.getByLabel('Closing', { exact: true })).toHaveValue('0');
+ await settings.getByRole('button', { name: 'Standard', exact: true }).click();
+ await expect(settings.getByLabel('Mouth movement', { exact: true })).toHaveValue('0.5');
+ await stop.click();
+ await settings.locator('.audio-lip-advanced > summary').click();
+ for (const label of ['Mouth movement', 'Mouth size', 'Closing'])
+ await expect(settings.getByLabel(label, { exact: true })).toBeEnabled();
+ await page.getByLabel('Kana text', { exact: true }).fill('あーーーーいーーーー');
+ await page.getByRole('checkbox', { name: 'Loop', exact: true }).check();
+ await page.locator('.lip-text-row').getByRole('button', { name: 'Play', exact: true }).click();
+ const revision = await page.getByTestId('preview').getAttribute('data-revision');
+ const peak = () => page.evaluate(async () => {
+ const input = document.querySelector<HTMLInputElement>('#lip-panel .lip-live input')!;
+ const end = performance.now() + 1700; let max = 0;
+ while (performance.now() < end) { await new Promise(requestAnimationFrame); max = Math.max(max, Number(input.value)); }
+ return max;
+ });
+ await settings.getByLabel('Mouth size', { exact: true }).fill('0');
+ await page.waitForTimeout(250);
+ const subtle = await peak(); expect(subtle).toBeLessThan(0.55); expect(subtle).toBeGreaterThan(0.2);
+ await settings.getByLabel('Mouth size', { exact: true }).fill('1');
+ expect(await peak()).toBeGreaterThan(0.8);
+ await settings.getByLabel('Mouth movement', { exact: true }).fill('0');
+ await settings.getByLabel('Closing', { exact: true }).fill('0');
+ await settings.getByLabel('Closing', { exact: true }).dispatchEvent('pointerup');
+ await expect(settings.locator('.audio-lip-custom')).toHaveText('Custom');
+ await expect(settings.locator('.audio-lip-presets button[aria-pressed="true"]')).toHaveCount(0);
+ await expect(page.getByTestId('preview')).toHaveAttribute('data-revision', revision!);
+ await expect(page.locator('.lip-text-row').getByRole('button', { name: 'Stop', exact: true })).toBeEnabled();
+ await page.locator('.lip-text-row').getByRole('button', { name: 'Stop', exact: true }).click();
+ await settings.getByLabel('Mouth movement', { exact: true }).fill('0.1');
+ await expect(stop).toBeDisabled();
+ await settings.getByLabel('Mouth movement', { exact: true }).dispatchEvent('pointerup');
+ await expect(stop).toBeEnabled();
+ await stop.click();
+ // A two-second user phrase must finish on its original timeline after a preset click.
+ await page.getByLabel('Kana text', { exact: true }).fill('あーーーーーーー');
+ await page.getByLabel('Morae per second', { exact: true }).fill('4');
+ await page.getByRole('checkbox', { name: 'Loop', exact: true }).uncheck();
+ await page.locator('.lip-text-row').getByRole('button', { name: 'Play', exact: true }).click();
+ await page.waitForTimeout(1000);
+ await settings.getByRole('button', { name: 'Expressive', exact: true }).click();
+ await expect(stop).toBeDisabled({ timeout: 1600 });
+ await page.getByRole('tab', { name: 'Pose test', exact: true }).click();
+ await expect(settings).toBeHidden();
+});
+
+test('editor previews local audio, exports preferences, saves them and Live/Player load the saved settings', async ({ page, context }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ const errors: string[] = [], outside: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await context.route('**/*', route => {
+ const url = new URL(route.request().url());
+ if (!['127.0.0.1', 'localhost'].includes(url.hostname) && !['blob:', 'data:'].includes(url.protocol)) { outside.push(url.href); return route.abort(); }
+ return route.continue();
+ });
+ let name: string | undefined;
+ try {
+ await page.goto('/'); await dismissGuide(page);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByTestId('idle-toggle').click();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByRole('tab', { name: 'Lip sync', exact: true }).click();
+ const section = page.getByTestId('audio-lip-settings');
+ await section.locator('.audio-lip-advanced > summary').click();
+ await section.getByLabel('Mouth movement', { exact: true }).fill('0.2');
+ await section.getByLabel('Mouth size', { exact: true }).fill('0.75');
+ await section.getByLabel('Closing', { exact: true }).fill('0.15');
+ const canvas = page.getByTestId('preview'), before = await canvas.screenshot();
+ await section.getByLabel('Preview a local audio file').setInputFiles({ name: 'synthetic.wav', mimeType: 'audio/wav', buffer: tone() });
+ await expect(section.locator('.audio-file-picker')).toContainText('synthetic.wav');
+ await section.locator('audio').evaluate((audio: HTMLAudioElement) => audio.play());
+ await expect.poll(() => canvas.screenshot().then(image => image.equals(before))).toBe(false);
+ await section.getByRole('button', { name: 'Stop audio preview' }).click();
+ await expect.poll(() => section.locator('audio').evaluate((audio: HTMLAudioElement) => audio.paused)).toBe(true);
+
+ const menu = page.getByTestId('export-menu'); await menu.locator('summary').click();
+ const downloaded = page.waitForEvent('download'); await menu.getByRole('button', { name: 'Download .mavatar', exact: true }).click();
+ const bytes = await readFile((await (await downloaded).path())!);
+ const manifest = JSON.parse(new TextDecoder().decode(unzipSync(bytes)['avatar.json']));
+ expect(manifest.lipSync).toEqual({ preset: 'custom', granularity: 0.2, openness: 0.75, closeSpeed: 0.15 });
+ expect(Object.keys(unzipSync(bytes)).some(path => path.endsWith('.wav'))).toBe(false);
+ await page.locator('.open-menu > summary').click();
+ const imported = page.waitForResponse(response => response.url().endsWith('/__studio/import'));
+ await page.getByLabel('Avatar archive file').setInputFiles({ name: 'settings.mavatar', mimeType: 'application/octet-stream', buffer: bytes });
+ const response = await imported; expect(response.ok()).toBe(true); name = (await response.json()).name;
+ await expect(page.getByTestId('project-location')).toContainText(name!);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByRole('tab', { name: 'Lip sync', exact: true }).click();
+ await expect(section.getByLabel('Mouth size', { exact: true })).toHaveValue('0.75');
+ await section.locator('.audio-lip-advanced > summary').click();
+ await section.getByLabel('Mouth size', { exact: true }).fill('0.8');
+ const saved = page.waitForResponse(response => response.url().endsWith('/lip-sync') && response.request().method() === 'POST');
+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();
+ expect((await saved).ok()).toBe(true);
+ expect(JSON.parse(await readFile(resolve('projects', name!, 'avatar.json'), 'utf8')).lipSync.openness).toBe(0.8);
+ await page.reload(); await expect(page.getByTestId('project-location')).toContainText(name!);
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByRole('tab', { name: 'Lip sync', exact: true }).click();
+ await expect(section.getByLabel('Mouth movement', { exact: true })).toHaveValue('0.2');
+ await section.locator('.audio-lip-advanced > summary').click();
+ await expect(section.getByLabel('Mouth size', { exact: true })).toHaveValue('0.8');
+ await expect(section.locator('.audio-lip-custom')).toHaveText('Custom');
+ const saveAndReload = async () => {
+ const response = page.waitForResponse(response => response.url().endsWith('/lip-sync') && response.request().method() === 'POST');
+ await page.getByRole('button', { name: 'Save rig', exact: true }).click();
+ expect((await response).ok()).toBe(true);
+ await page.reload();
+ await expect(page.getByTestId('preview-status')).toHaveAttribute('data-state', 'ready');
+ await page.getByRole('tab', { name: 'Lip sync', exact: true }).click();
+ };
+ await section.getByRole('button', { name: 'Relaxed', exact: true }).click();
+ await saveAndReload();
+ await expect(section.getByRole('button', { name: 'Relaxed', exact: true })).toHaveAttribute('aria-pressed', 'true');
+ await expect(section.getByLabel('Mouth movement', { exact: true })).toHaveValue('0');
+ await expect(section.getByLabel('Mouth size', { exact: true })).toHaveValue('0.5');
+ await expect(section.getByLabel('Closing', { exact: true })).toHaveValue('0');
+ await section.locator('.audio-lip-advanced > summary').click();
+ // Returning a slider to the preset's exact value still preserves the explicit Custom selection.
+ await section.getByLabel('Mouth movement', { exact: true }).fill('0.05');
+ await section.getByLabel('Mouth movement', { exact: true }).fill('0');
+ await saveAndReload();
+ await expect(section.locator('.audio-lip-custom')).toHaveText('Custom');
+ await expect(section.locator('.audio-lip-presets button[aria-pressed="true"]')).toHaveCount(0);
+ expect(JSON.parse(await readFile(resolve('projects', name!, 'avatar.json'), 'utf8')).lipSync.preset).toBe('custom');
+
+ await page.goto(`/live.html?project=${encodeURIComponent(name!)}&idle=0`);
+ await expect(page.locator('canvas[data-state="ready"]')).toBeVisible();
+ await page.getByRole('combobox', { name: 'Framing', exact: true }).selectOption('cover');
+ await expect(page.locator('canvas[data-state="ready"]')).toBeVisible();
+ const site = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/play/`;
+ await page.goto(site);
+ await expect(page.getByTestId('player-status')).toContainText('Avatar ready');
+ await page.getByTestId('player-file').setInputFiles({ name: 'settings.mavatar', mimeType: 'application/octet-stream', buffer: bytes });
+ await expect(page.getByTestId('player-status')).toHaveText('Avatar ready · settings.mavatar');
+ await page.getByRole('combobox', { name: 'Framing', exact: true }).selectOption('cover');
+ await expect(page.getByTestId('player-status')).toHaveText('Avatar ready · settings.mavatar');
+ expect(outside).toEqual([]); expect(errors).toEqual([]);
+ } finally { if (name) await rm(resolve('projects', name), { recursive: true, force: true }); }
+});
diff --git a/e2e/react-wrapper.spec.ts b/e2e/react-wrapper.spec.ts
index a883c06..e06d133 100644
--- a/e2e/react-wrapper.spec.ts
+++ b/e2e/react-wrapper.spec.ts
@@ -69,11 +69,11 @@ test('loads a File and restores the unchanged src when source is removed', async
test('delivers load, error and motion once to the latest callbacks', async ({ page }) => {
await open(page);
- await page.evaluate(async src => {
- window.harness.update({ src, paused: true });
- await new Promise(requestAnimationFrame);
+ await page.evaluate(src => window.harness.update({ src, paused: true, label: 'Updated callbacks' }), sample);
+ await expect(page.locator('mesh-avatar')).toHaveAttribute('label', 'Updated callbacks');
+ await page.evaluate(() => {
window.harness.ref.current!.dispatchEvent(new CustomEvent('motion', { detail: { id: 'wave' } }));
- }, sample);
+ });
expect(await page.evaluate(() => window.harness.log.filter(x => x.event === 'motion'))).toEqual([{ version: 1, event: 'motion', value: 'wave' }]);
await page.evaluate(src => window.harness.update({ src, source: new Blob(['broken']) }), sample);
await expect.poll(() => page.evaluate(() => window.harness.log.filter(x => x.event === 'error'))).toEqual([{ version: 2, event: 'error', value: expect.any(String) }]);
diff --git a/e2e/workflow.spec.ts b/e2e/workflow.spec.ts
index 4873a92..b8ccfe7 100644
--- a/e2e/workflow.spec.ts
+++ b/e2e/workflow.spec.ts
@@ -200,6 +200,14 @@ test('pose and lip tabs keep a large preview at 1440 by 900 in both languages',
await page.getByRole('tab', { name: tab, exact: true }).click();
expect((await page.getByTestId('preview').boundingBox())!.height).toBeGreaterThanOrEqual(420);
await expect(page.getByRole('tabpanel')).toHaveCount(1);
+ if (tab === 'Lip sync' || tab === '口の動き') {
+ const pane = page.locator('#lip-panel'); await pane.evaluate(element => { element.scrollTop = 0; });
+ const bounds = (await pane.boundingBox())!;
+ for (const locator of [pane.locator('.lip-text-row')]) {
+ const box = (await locator.boundingBox())!;
+ expect(box.y).toBeGreaterThanOrEqual(bounds.y); expect(box.y + box.height).toBeLessThanOrEqual(bounds.y + bounds.height);
+ }
+ }
expect((await page.locator('.preview-panel').boundingBox())!.y + (await page.locator('.preview-panel').boundingBox())!.height).toBeLessThanOrEqual(900);
}
}
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index f119be8..f1b6b51 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -1,9 +1,9 @@
-import { loadMeshAvatar, type AvatarSource, type MeshAvatar } from 'mesh-avatar';
+import { loadMeshAvatar, parseManifest, type AvatarSource, type MeshAvatar, type LipSyncSettings } from 'mesh-avatar';
import { DEFAULT_SRC, frameSeconds, parseEmotion, parseExpression, parseFit, ReadySignal, type Fit } from './attributes.js';
export { DEFAULT_SRC, EMOTIONS } from './attributes.js';
export type { Emotion, Fit } from './attributes.js';
-export type { AvatarSource, MeshAvatar, LiveExpression } from 'mesh-avatar';
+export type { AvatarSource, MeshAvatar, LiveExpression, LipSyncSettings } from 'mesh-avatar';
const STYLE = `
:host { display: block; position: relative; aspect-ratio: 1 / 1; }
@@ -33,6 +33,7 @@ export class MeshAvatarElement extends Base {
#onScreen = true;
#observer: IntersectionObserver | null = null;
#voiceLevel: number | null = null;
+ #lipSync: LipSyncSettings = {};
#warned = new Set<string>();
constructor() {
@@ -79,6 +80,18 @@ export class MeshAvatarElement extends Base {
this.#avatar?.setVoiceLevel(value);
}
+ /** Explicit mouth-movement overrides, retained across loads. Assignment is a partial update. */
+ get lipSync(): LipSyncSettings { return { ...this.#lipSync }; }
+ set lipSync(settings: LipSyncSettings) { this.setLipSync(settings); }
+
+ /** Partial overrides of the avatar's saved mouth-movement settings, retained across loads. */
+ setLipSync(settings: LipSyncSettings): void {
+ // Validate before updating either the loaded avatar or the retained overrides.
+ const updates = parseManifest({ format: 'mesh-avatar', version: 1, name: 'Avatar', lipSync: settings }).lipSync!;
+ this.#avatar?.setLipSync(updates);
+ this.#lipSync = { ...this.#lipSync, ...updates };
+ }
+
/** Moves the mouth to Japanese text without audio. Waits for the avatar to load. */
async speak(text: string, options?: { speed?: number; loop?: boolean }) {
(await this.ready).speakKana(text, options);
@@ -160,6 +173,7 @@ export class MeshAvatarElement extends Base {
if (name !== 'emotion' || this.hasAttribute(name)) this.#apply(avatar, name);
}
if (this.#voiceLevel !== null) avatar.setVoiceLevel(this.#voiceLevel);
+ avatar.setLipSync(this.#lipSync);
// Hair moves less for people who ask for reduced motion; the avatar itself still moves.
if (matchMedia('(prefers-reduced-motion: reduce)').matches) avatar.setSwayGain(0.5);
avatar.onMotion(motion => this.dispatchEvent(new CustomEvent('motion', { detail: { id: motion } })));
diff --git a/packages/runtime/src/engine/createMeshAvatar.js b/packages/runtime/src/engine/createMeshAvatar.js
index a2700eb..72dbb29 100644
--- a/packages/runtime/src/engine/createMeshAvatar.js
+++ b/packages/runtime/src/engine/createMeshAvatar.js
@@ -140,6 +140,7 @@ export async function createMeshAvatarImpl(canvas, options) {
const physics = new Physics();
const motion = new Motion(rig.view.gazeCenter ?? [rig.head.cx, rig.head.cy]);
+ if (options.lipSync !== undefined) motion.setLipSync(options.lipSync);
const listeners = new Set();
motion.onMotion = id => { for (const fn of listeners) fn(id); };
@@ -227,6 +228,8 @@ export async function createMeshAvatarImpl(canvas, options) {
getParameters() { return { ...lastParameters }; },
/** 0..1 loudness of the voice being played (e.g. normalised RMS). */
setVoiceLevel(v) { motion.setVoiceLevel(v); },
+ /** Partial mouth-movement settings; omitted fields retain their current values. */
+ setLipSync(settings) { motion.setLipSync(settings); },
/** true while TTS audio is playing: idle motions pause and the head nods along. */
setSpeaking(on) { motion.setSpeaking(on); },
/** AITuber OnAir emotion tag: happy / sad / angry / surprised / relaxed / neutral (or null). */
diff --git a/packages/runtime/src/engine/index.ts b/packages/runtime/src/engine/index.ts
index 44d7868..ac49c7f 100644
--- a/packages/runtime/src/engine/index.ts
+++ b/packages/runtime/src/engine/index.ts
@@ -3,6 +3,7 @@ import type { Rig } from '../rig/types';
import { parseRig } from '../rig/validate';
import { createMeshAvatarImpl } from './createMeshAvatar.js';
import { OVERLAY_EXPRESSIONS } from './expression-overlay.js';
+import type { LipSyncSettings } from './lip-sync';
export type LiveExpression = keyof typeof OVERLAY_EXPRESSIONS;
export const LIVE_EXPRESSIONS = Object.keys(OVERLAY_EXPRESSIONS) as LiveExpression[];
@@ -16,6 +17,7 @@ export interface MeshAvatarOptions {
padSide?: number;
fit?: 'contain' | 'cover';
preserveMouthForm?: boolean;
+ lipSync?: LipSyncSettings;
}
export interface MeshAvatar {
readonly motions: { id: string; label: string; idle: boolean }[];
@@ -24,6 +26,8 @@ export interface MeshAvatar {
setParameters(parameters: Record<string, number>, weight?: number): void;
getParameters(): Record<string, number>;
setVoiceLevel(value: number): void;
+ /** Partial mouth-movement settings; omitted fields retain their current values. */
+ setLipSync(settings: LipSyncSettings): void;
setSpeaking(on: boolean): void;
setEmotion(tag: string | null, options?: { playMotion?: boolean }): void;
setExpression(name: LiveExpression): void;
diff --git a/packages/runtime/src/engine/kana.js b/packages/runtime/src/engine/kana.js
index 24b11ce..ece4b29 100644
--- a/packages/runtime/src/engine/kana.js
+++ b/packages/runtime/src/engine/kana.js
@@ -50,7 +50,8 @@ export function kanaToMoras(text, mora = 0.14) {
}
/** Mouth target at time t (s) of a mora timeline, or null when it is over. */
-export function sampleMoras(moras, t) {
+export function sampleMoras(moras, t, granularity = 0.5) {
+ if (granularity !== 0.5) return sampleGroupedMoras(moras, t, granularity);
let start = 0;
for (const m of moras) {
if (t < start + m.dur) {
@@ -65,3 +66,29 @@ export function sampleMoras(moras, t) {
}
return null;
}
+
+// Low sensitivity groups short morae and softens closures. Long pauses still close.
+function sampleGroupedMoras(moras, t, granularity) {
+ const groupSeconds = granularity < 0.5 ? (0.5 - granularity) * 0.72 : 0;
+ let start = 0, groupDuration = 0, groupVowel = null;
+ for (const m of moras) {
+ let vowel = m.vowel;
+ if (m.vowel === 'n') {
+ if (groupSeconds && m.dur <= 0.2 && groupVowel) vowel = groupVowel;
+ else { groupDuration = 0; groupVowel = null; }
+ } else {
+ if (!groupVowel || groupDuration >= groupSeconds) { groupVowel = m.vowel; groupDuration = 0; }
+ groupDuration += m.dur;
+ if (groupSeconds) vowel = groupVowel;
+ }
+ if (t < start + m.dur) {
+ const v = VOWELS[vowel];
+ const original = m.onset === 'lips' ? 0.05 : m.onset === 'consonant' ? 0.45 : 1;
+ const onset = granularity < 0.5 ? 1 - (1 - original) * granularity * 2 : original * (2 - granularity * 2);
+ const attack = Math.min(m.dur * 0.35, 0.05), x = (t - start) / attack;
+ return { open: v.open * (x < 1 ? onset + (1 - onset) * x : 1), form: v.form, vowel };
+ }
+ start += m.dur;
+ }
+ return null;
+}
diff --git a/packages/runtime/src/engine/lip-sync.ts b/packages/runtime/src/engine/lip-sync.ts
new file mode 100644
index 0000000..fb9cc4b
--- /dev/null
+++ b/packages/runtime/src/engine/lip-sync.ts
@@ -0,0 +1,51 @@
+export interface LipSyncSettings {
+ granularity?: number;
+ openness?: number;
+ closeSpeed?: number;
+ /** Editor selection only; playback uses the numeric settings. */
+ preset?: 'calm' | 'default' | 'lively' | 'subtle' | 'big' | 'custom';
+}
+
+type ResolvedLipSync = Required<Pick<LipSyncSettings, 'granularity' | 'openness' | 'closeSpeed'>>;
+
+export function parseLipSyncSettings(input: unknown): LipSyncSettings {
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('lipSync: expected an object');
+ const raw = input as LipSyncSettings, settings: LipSyncSettings = {};
+ for (const key of ['granularity', 'openness', 'closeSpeed'] as const) {
+ const value = raw[key];
+ if (value === undefined) continue;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1)
+ throw new RangeError(`lipSync.${key}: expected 0–1`);
+ settings[key] = value;
+ }
+ if (raw.preset !== undefined) {
+ if (!['calm', 'default', 'lively', 'subtle', 'big', 'custom'].includes(raw.preset))
+ throw new RangeError('lipSync.preset: expected calm, default, lively, subtle, big or custom');
+ settings.preset = raw.preset;
+ }
+ return settings;
+}
+
+export function resolveLipSync(input: LipSyncSettings = {}, base: ResolvedLipSync = {
+ granularity: 0.5, openness: 0.5, closeSpeed: 0.5,
+}): ResolvedLipSync {
+ const settings = parseLipSyncSettings(input);
+ return { granularity: settings.granularity ?? base.granularity,
+ openness: settings.openness ?? base.openness, closeSpeed: settings.closeSpeed ?? base.closeSpeed };
+}
+
+// Center values are explicit so the unconfigured path keeps its original constants.
+const centered = (value: number, low: number, center: number, high: number) => value === 0.5 ? center
+ : value < 0.5 ? low + (center - low) * value * 2 : center + (high - center) * (value - 0.5) * 2;
+export function lipMotionOptions(settings: ResolvedLipSync) {
+ return {
+ arm: centered(settings.granularity, 0.2, 0.6, 0.9),
+ trigger: centered(settings.granularity, 0.65, 0.8, 0.95),
+ relax: centered(settings.granularity, 1.5, 5, 12),
+ range: centered(settings.granularity, 0.7, 0.3, 0.05),
+ risePower: centered(settings.granularity, 0.05, 0.3, 0.8),
+ openness: centered(settings.openness, 0.55, 1, 1.25),
+ audioRelease: centered(settings.closeSpeed, 6, 32, 45),
+ kanaRelease: centered(settings.closeSpeed, 6, 22, 45),
+ };
+}
diff --git a/packages/runtime/src/engine/motion.js b/packages/runtime/src/engine/motion.js
index 76e0e03..78e624c 100644
--- a/packages/runtime/src/engine/motion.js
+++ b/packages/runtime/src/engine/motion.js
@@ -1,4 +1,5 @@
// Drives parameters: idle ("auto idle"), mouse follow, blinking, expressions, motions.
+import { resolveLipSync, lipMotionOptions } from './lip-sync.ts';
import { PARAMS } from './rig.js';
import { MOTIONS, IDLE_MOTIONS, ADDITIVE, sampleTrack } from './motions.js';
import { VOWELS, kanaToMoras, sampleMoras } from './kana.js';
@@ -81,6 +82,8 @@ export class Motion {
this.mouth = 0;
this.vowel = 'a';
this.vowelForm = 0;
+ this.lipSync = resolveLipSync();
+ this.lipMotion = lipMotionOptions(this.lipSync);
this.syllableArmed = true;
this.voicePeak = 0;
this.voiceTrough = 0;
@@ -104,6 +107,11 @@ export class Motion {
// ---- speech (driven from outside, e.g. by the TTS audio analyser) ----
setVoiceLevel(v) { this.voice = Math.min(1, Math.max(0, Number(v) || 0)); }
+ setLipSync(settings) {
+ this.lipSync = resolveLipSync(settings, this.lipSync);
+ this.lipMotion = lipMotionOptions(this.lipSync);
+ }
+
setSpeaking(on) {
if (on === this.speaking) return;
this.speaking = !!on;
@@ -156,33 +164,35 @@ export class Motion {
else {
this.kana.t += dt;
if (this.kana.loop) this.kana.t %= this.kana.duration;
- m = sampleMoras(this.kana.moras, this.kana.t);
+ m = sampleMoras(this.kana.moras, this.kana.t, this.lipSync.granularity);
}
- if (!m) { this.kana = null; return this.mouth > 0.01 ? [this.mouth *= 0.6, this.vowelForm] : null; }
- const k = m.open > this.mouth ? 1 - Math.exp(-dt * 30) : 1 - Math.exp(-dt * 22);
- this.mouth += (m.open - this.mouth) * k;
+ if (!m) { this.kana = null; return this.mouth > 0.01 ? [this.mouth *= this.lipSync.closeSpeed === 0.5 ? 0.6 : Math.exp(-dt * this.lipMotion.kanaRelease), this.vowelForm] : null; }
+ const target = this.lipMotion.openness === 1 ? m.open : Math.min(1, m.open * this.lipMotion.openness);
+ const k = target > this.mouth ? 1 - Math.exp(-dt * 30) : 1 - Math.exp(-dt * this.lipMotion.kanaRelease);
+ this.mouth += (target - this.mouth) * k;
if (m.form !== null) this.vowelForm = m.form;
return [this.mouth, this.vowelForm];
}
const v = this.speaking ? this.voice : 0;
// recent peak / trough: follow at once, then relax over ~0.2 s
- const relax = 1 - Math.exp(-dt * 5);
+ const relax = 1 - Math.exp(-dt * this.lipMotion.relax);
this.voicePeak = v > this.voicePeak ? v : this.voicePeak + (v - this.voicePeak) * relax;
this.voiceTrough = v < this.voiceTrough ? v : this.voiceTrough + (v - this.voiceTrough) * relax;
const peak = Math.max(this.voicePeak, 0.05);
- if (v < peak * 0.6) this.syllableArmed = true;
- else if (this.syllableArmed && v > peak * 0.8 && v > 0.1) {
+ if (v < peak * this.lipMotion.arm) this.syllableArmed = true;
+ else if (this.syllableArmed && v > peak * this.lipMotion.trigger && v > 0.1) {
this.syllableArmed = false;
const r = Math.random();
this.vowel = r < 0.4 ? 'a' : r < 0.58 ? 'o' : r < 0.74 ? 'e' : r < 0.88 ? 'i' : 'u';
}
const range = this.voicePeak - this.voiceTrough;
- const rise = range < peak * 0.3 ? 1 : Math.max(0, (v - this.voiceTrough) / range);
+ const rise = range < peak * this.lipMotion.range ? 1 : Math.max(0, (v - this.voiceTrough) / range);
const shape = VOWELS[this.vowel ?? 'a'];
- const level = Math.min(1, Math.pow(v, 0.7) * 1.15) * Math.pow(rise, 0.3);
- const target = this.speaking ? Math.min(0.95, level) * (0.45 + 0.55 * shape.open / 0.9) : 0;
+ const level = Math.min(1, Math.pow(v, 0.7) * 1.15) * Math.pow(rise, this.lipMotion.risePower);
+ const baseTarget = this.speaking ? Math.min(0.95, level) * (0.45 + 0.55 * shape.open / 0.9) : 0;
+ const target = this.lipMotion.openness === 1 ? baseTarget : Math.min(1, baseTarget * this.lipMotion.openness);
// quick attack, quick release: the mouth has to shut between morae (~7 per second)
- const k = target > this.mouth ? 1 - Math.exp(-dt * 40) : 1 - Math.exp(-dt * 32);
+ const k = target > this.mouth ? 1 - Math.exp(-dt * 40) : 1 - Math.exp(-dt * this.lipMotion.audioRelease);
this.mouth += (target - this.mouth) * k;
if (this.speaking) this.vowelForm = shape.form; // after the line: close in the last shape
return this.speaking || this.mouth > 0.01 ? [this.mouth, this.vowelForm] : null;
diff --git a/packages/runtime/src/format/manifest.ts b/packages/runtime/src/format/manifest.ts
index 0e91617..c558dac 100644
--- a/packages/runtime/src/format/manifest.ts
+++ b/packages/runtime/src/format/manifest.ts
@@ -1,3 +1,5 @@
+import { parseLipSyncSettings, type LipSyncSettings } from '../engine/lip-sync.ts';
+
export interface AvatarManifest {
format: 'mesh-avatar';
version: 1;
@@ -7,6 +9,7 @@ export interface AvatarManifest {
thumbnail?: string;
source?: string;
studio?: { version: string };
+ lipSync?: LipSyncSettings;
}
export function parseManifest(input: unknown): AvatarManifest {
@@ -30,6 +33,11 @@ export function parseManifest(input: unknown): AvatarManifest {
errors.push('avatar.json.studio.version: expected a non-empty string');
} else manifest.studio = { version: studio.version };
}
+ if (value.lipSync !== undefined) {
+ try {
+ manifest.lipSync = parseLipSyncSettings(value.lipSync);
+ } catch (error) { errors.push(`avatar.json.lipSync: ${error instanceof Error ? error.message : String(error)}`); }
+ }
if (errors.length) throw new Error(errors.join('\n'));
return manifest;
}
diff --git a/packages/runtime/src/format/open.ts b/packages/runtime/src/format/open.ts
index bbaa471..c5a85f9 100644
--- a/packages/runtime/src/format/open.ts
+++ b/packages/runtime/src/format/open.ts
@@ -1,3 +1,4 @@
+import { parseLipSyncSettings } from '../engine/lip-sync.ts';
import { createMeshAvatar, type MeshAvatar, type MeshAvatarOptions } from '../engine';
import { parseRig } from '../rig/validate';
import type { Rig } from '../rig/types';
@@ -106,7 +107,9 @@ export async function loadMeshAvatar(canvas: HTMLCanvasElement, source: AvatarSo
options: Omit<MeshAvatarOptions, 'rig' | 'assets' | 'assetsBase'> = {}): Promise<MeshAvatar & { package: AvatarPackage }> {
const owned = !isPackage(source), loaded = await openAvatar(source);
try {
- const avatar = await createMeshAvatar(canvas, { ...options, rig: loaded.rig, assets: loaded.assets });
+ const lipSync = options.lipSync === undefined ? loaded.manifest.lipSync
+ : { ...loaded.manifest.lipSync, ...parseLipSyncSettings(options.lipSync) };
+ const avatar = await createMeshAvatar(canvas, { ...options, ...(lipSync === undefined ? {} : { lipSync }), rig: loaded.rig, assets: loaded.assets });
const destroy = avatar.destroy.bind(avatar);
let destroyed = false;
return Object.assign(avatar, { package: loaded, destroy() {
diff --git a/packages/runtime/src/format/project-archive.ts b/packages/runtime/src/format/project-archive.ts
index 0ec39ea..6cdd0bd 100644
--- a/packages/runtime/src/format/project-archive.ts
+++ b/packages/runtime/src/format/project-archive.ts
@@ -1,4 +1,5 @@
import { parseManifest, type AvatarManifest } from './manifest.ts';
+import type { LipSyncSettings } from '../engine/lip-sync.ts';
import { checkEntryName, packAvatar } from './zip.ts';
type Files = Record<string, Uint8Array>;
@@ -6,7 +7,7 @@ type Files = Record<string, Uint8Array>;
// Shared by Studio and the CLI; this is not part of the runtime's public API.
export async function packProjectAvatar(
read: (paths: Set<string>) => Promise<Files>,
- { name, includeSource = true }: { name: string; includeSource?: boolean },
+ { name, includeSource = true, lipSync }: { name: string; includeSource?: boolean; lipSync?: LipSyncSettings },
): Promise<Uint8Array> {
const wanted = new Set(['avatar.json', 'rig.json', 'built/layers.json', 'built/sprites/sprites.json']);
const metadata = await read(wanted);
@@ -29,5 +30,6 @@ export async function packProjectAvatar(
const files = await read(wanted);
let override: Partial<AvatarManifest> | undefined = manifest ? undefined : { name };
if (!includeSource && manifest?.source) override = { ...manifest, source: undefined };
+ if (lipSync !== undefined) override = { ...manifest, ...override, lipSync };
return packAvatar(files, { manifest: override });
}
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 2f0641e..8b5f005 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,5 +1,6 @@
export { createMeshAvatar, LIVE_EXPRESSIONS } from './engine';
export type { MeshAvatar, MeshAvatarOptions, LiveExpression } from './engine';
+export type { LipSyncSettings } from './engine/lip-sync';
export type { Rig, Eye, Strand, Accessory, Hand, Ellipse, Point, Band } from './rig/types';
export { validateRig, parseRig } from './rig/validate';
export { PARAMS } from './engine/rig.js';
diff --git a/packages/runtime/tests/manifest.test.ts b/packages/runtime/tests/manifest.test.ts
index 1e68942..56bd3d6 100644
--- a/packages/runtime/tests/manifest.test.ts
+++ b/packages/runtime/tests/manifest.test.ts
@@ -4,6 +4,15 @@ import { defaultManifest } from '../src/format/manifest';
const manifest = { format: 'mesh-avatar', version: 1, name: 'My avatar' };
+test('optional lip sync settings retain defaults by omission, validate ranges and ignore unknown keys', () => {
+ expect(parseManifest(manifest).lipSync).toBeUndefined();
+ expect(parseManifest({ ...manifest, lipSync: {} }).lipSync).toEqual({});
+ const lipSync = { openness: 0.75, extra: true };
+ expect(parseManifest({ ...manifest, lipSync }).lipSync).toEqual({ openness: 0.75 });
+ for (const lipSync of [null, [], 'settings', 1])
+ expect(() => parseManifest({ ...manifest, lipSync })).toThrow('avatar.json.lipSync');
+});
+
test('parses known manifest fields without retaining unknown data or shared objects', () => {
const input = { ...manifest, author: 'Artist', license: 'Artwork terms', source: 'source.png',
thumbnail: 'thumbnail.png', studio: { version: '0.1.0', extra: true }, extra: true };
@@ -30,3 +39,20 @@ test.each([
])('names invalid manifest field in %j', (change, field) => {
expect(() => parseManifest({ ...manifest, ...change })).toThrow(`avatar.json.${field}:`);
});
+
+test('movement settings round trip with validation and preserve omission for older manifests', () => {
+ const lipSync = { granularity: 0, openness: 0.75, closeSpeed: 1 };
+ expect(parseManifest({ ...manifest, lipSync }).lipSync).toEqual(lipSync);
+ for (const key of ['granularity', 'openness', 'closeSpeed'])
+ for (const value of [-0.01, 1.01, NaN, Infinity, '0.5', null])
+ expect(() => parseManifest({ ...manifest, lipSync: { [key]: value } })).toThrow(`lipSync.${key}`);
+});
+
+test('editor preset metadata survives parsing without changing playback values', () => {
+ for (const preset of ['calm', 'default', 'lively', 'subtle', 'big', 'custom']) {
+ const lipSync = { preset, granularity: 0.5, openness: 0.5, closeSpeed: 0.5 };
+ expect(parseManifest({ ...manifest, lipSync }).lipSync).toEqual(lipSync);
+ }
+ for (const preset of ['', 'unknown', null, 1, {}])
+ expect(() => parseManifest({ ...manifest, lipSync: { preset } })).toThrow('avatar.json.lipSync: lipSync.preset:');
+});
diff --git a/packages/runtime/tests/open.test.ts b/packages/runtime/tests/open.test.ts
index 8a81b3c..fd318f9 100644
--- a/packages/runtime/tests/open.test.ts
+++ b/packages/runtime/tests/open.test.ts
@@ -113,3 +113,16 @@ test('loadMeshAvatar releases owned resources on destroy or failure but preserve
second.destroy(); expect(release).not.toHaveBeenCalled();
shared.release();
});
+
+test('loadMeshAvatar applies saved mouth settings and lets explicit runtime options override them', async () => {
+ const lipSync = { granularity: 0.2, openness: 0.75, closeSpeed: 0.1 };
+ const archive = packAvatar(files, { manifest: { lipSync } });
+ const avatar = await loadMeshAvatar({} as HTMLCanvasElement, archive);
+ expect(avatar.package.manifest.lipSync).toEqual(lipSync);
+ expect(vi.mocked(createMeshAvatar).mock.calls.at(-1)?.[1].lipSync).toEqual(lipSync);
+ avatar.destroy();
+ const override = { openness: 0.3 };
+ const other = await loadMeshAvatar({} as HTMLCanvasElement, archive, { lipSync: override });
+ expect(vi.mocked(createMeshAvatar).mock.calls.at(-1)?.[1].lipSync).toEqual({ ...lipSync, ...override });
+ other.destroy();
+});
diff --git a/src/editor/App.tsx b/src/editor/App.tsx
index d05579f..290cb5d 100644
--- a/src/editor/App.tsx
+++ b/src/editor/App.tsx
@@ -2,10 +2,10 @@ import { useEffect, useRef, useState } from 'react';
import fixture from 'virtual:sample-rig';
import { EditorCanvas } from './EditorCanvas';
import { setAt } from './model';
-import { type Rig, parseRig, validateRig } from 'mesh-avatar';
+import { type Rig, type LipSyncSettings, parseRig, validateRig } from 'mesh-avatar';
import { Preview } from './Preview';
import { RigHistory, downloadRig } from './history';
-import { openProjectFolder, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, sampleSourceUrl, repositoryContext, runProjectJob, ProjectJobError, importAvatar, exportAvatar, type ProjectJob, type LocalProject, type LocalProjectEntry } from './project';
+import { openProjectFolder, saveLipSync, openLocalProject, copySample, localProjects, projectAction, sampleImagesAvailable, sampleSourceUrl, repositoryContext, runProjectJob, ProjectJobError, importAvatar, exportAvatar, type ProjectJob, type LocalProject, type LocalProjectEntry } from './project';
import { ExportAvatar, ImportAvatar } from './AvatarTransfer';
import { archiveText } from './archive-i18n';
import { folderOpenError } from './folder-errors';
@@ -37,6 +37,8 @@ function Workspace() {
const [help, setHelp] = useState(false);
const [history] = useState(() => new RigHistory(parseRig(fixture)));
const [rig, setRig] = useState(history.present);
+ const [lipSync, setLipSync] = useState<LipSyncSettings | undefined>();
+ const [savedLipSync, setSavedLipSync] = useState<string | undefined>();
const [savedRig, setSavedRig] = useState(() => JSON.stringify(history.present));
const pickedFiles = useRef<File[] | undefined>(undefined);
const [archiveBusy, setArchiveBusy] = useState(false);
@@ -141,6 +143,7 @@ function Workspace() {
try {
const project = await openProjectFolder(files);
projectOpened.current = true;
+ setLipSync(project.lipSync); setSavedLipSync(JSON.stringify(project.lipSync));
if (project.rig) {
history.load(project.rig); setRig(history.present); setDragStale(null);
setSavedRig(JSON.stringify(project.rig));
@@ -181,6 +184,7 @@ function Workspace() {
try {
const project = await openLocalProject(entry);
projectOpened.current = true;
+ setLipSync(project.lipSync); setSavedLipSync(JSON.stringify(project.lipSync));
history.load(project.rig!); setRig(history.present); setDragStale(null); setBuiltSignature(layerSignature(project.rig!));
setSavedRig(JSON.stringify(project.rig)); pickedFiles.current = undefined;
setSelected(null); setLocalProject(entry); setPickedName('');
@@ -201,11 +205,15 @@ function Workspace() {
const save = async () => {
if (jobRef.current) return;
if (localProject?.hasSource === false) return;
- if (!localProject || localProject.readOnly) { downloadRig(history.present); return; }
+ if (!localProject || localProject.readOnly) {
+ if (JSON.stringify(lipSync) !== savedLipSync) await exportFile(true).catch(() => undefined); else downloadRig(history.present);
+ return;
+ }
if (saving) return;
setSaving(true);
const snapshot = JSON.stringify(history.present);
- try { const result = await projectAction(localProject, 'rig', history.present); setSavedRig(snapshot); setNotice({ key: 'savedTo', path: result.path }); setError(null); }
+ try { const result = await projectAction(localProject, 'rig', history.present);
+ if (lipSync) { await saveLipSync(localProject, lipSync); setSavedLipSync(JSON.stringify(lipSync)); } setSavedRig(snapshot); setNotice({ key: 'savedTo', path: result.path }); setError(null); }
catch { setError({ kind: 'saveError', paths: [] }); }
finally { setSaving(false); }
};
@@ -347,7 +355,7 @@ function Workspace() {
};
const playbackOnly = localProject?.hasSource === false;
const busy = job !== null || opening || archiveBusy;
- const dirty = JSON.stringify(rig) !== savedRig;
+ const dirty = JSON.stringify(rig) !== savedRig || JSON.stringify(lipSync) !== savedLipSync;
const writable = !!localProject && !localProject.readOnly && !playbackOnly;
const importFile = async (file: File) => {
if (jobRef.current || saving || opening) return;
@@ -370,9 +378,10 @@ function Workspace() {
if (writable && dirty) {
const snapshot = JSON.stringify(history.present);
await projectAction(localProject!, 'rig', history.present); setSavedRig(snapshot);
+ if (lipSync) { await saveLipSync(localProject!, lipSync); setSavedLipSync(JSON.stringify(lipSync)); }
}
const name = localProject?.name ?? (pickedName || 'sample-miko-qipao');
- const blob = await exportAvatar(name, includeSource, pickedFiles.current);
+ const blob = await exportAvatar(name, includeSource, pickedFiles.current, lipSync);
const url = URL.createObjectURL(blob), link = document.createElement('a');
link.href = url; link.download = `${name}.mavatar`; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
@@ -450,7 +459,7 @@ function Workspace() {
</div>
</section>}
<div className="right-column">
- <Preview key={localProject?.name ?? (pickedName || 'sample-miko-qipao')} projectKey={localProject?.name ?? (pickedName || 'sample-miko-qipao')} rig={rig} assets={assets} hasMouthSprites={mouthSprites} onDrawMouth={playbackOnly ? undefined : () => setMouthRequest(value => value + 1)} />
+ <Preview key={localProject?.name ?? (pickedName || 'sample-miko-qipao')} projectKey={localProject?.name ?? (pickedName || 'sample-miko-qipao')} rig={rig} assets={assets} lipSync={lipSync} onLipSyncChange={setLipSync} hasMouthSprites={mouthSprites} onDrawMouth={playbackOnly ? undefined : () => setMouthRequest(value => value + 1)} />
{!playbackOnly && <VariantsPanel project={localProject} projectPath={localProject?.relativePath ?? (pickedName ? `<${pickedName}>` : 'samples/miko-qipao')} assets={assets} rootPath={rootPath} busy={busy || saving} stale={changed.length > 0} onRun={runJob} mouthRequest={mouthRequest} onMouthPresence={setMouthSprites} />}
{!localProject && !pickedName && <details className="panel new-illustration"><summary>{t.newIllustration}</summary><AskAgent newProject rootPath={rootPath} /></details>}
{!playbackOnly && <aside className="panel inspector" inert={busy}>
diff --git a/src/editor/LipSyncSettings.tsx b/src/editor/LipSyncSettings.tsx
new file mode 100644
index 0000000..20a845a
--- /dev/null
+++ b/src/editor/LipSyncSettings.tsx
@@ -0,0 +1,133 @@
+import { useEffect, useRef, useState } from 'react';
+import { type LipSyncSettings as Settings, type MeshAvatar } from 'mesh-avatar';
+import { rmsLevel } from '../live/tracking';
+import { useI18n } from './i18n';
+
+const presets = {
+ calm: { granularity: 0, openness: 0.5, closeSpeed: 0 },
+ default: { granularity: 0.5, openness: 0.5, closeSpeed: 0.5 },
+ lively: { granularity: 1, openness: 0.5, closeSpeed: 1 },
+ subtle: { granularity: 0.5, openness: 0, closeSpeed: 0.5 },
+ big: { granularity: 0.5, openness: 1, closeSpeed: 0.5 },
+} as const;
+type Preset = keyof typeof presets;
+const presetNames = Object.keys(presets) as Preset[];
+
+export const lipSyncText = {
+ en: {
+ movementTitle: 'Mouth movement style', calm: 'Relaxed', default: 'Standard', lively: 'Snappy', subtle: 'Subtle', big: 'Expressive', custom: 'Custom',
+ demoHint: 'Choose a style to see it talk.', granularity: 'Mouth movement', granularityLow: 'Relaxed', granularityHigh: 'Snappy',
+ openness: 'Mouth size', opennessLow: 'Small', opennessHigh: 'Large', closeSpeed: 'Closing', closeSpeedLow: 'Smooth', closeSpeedHigh: 'Crisp',
+ advanced: 'Fine-tune', title: 'Audio lip sync',
+ file: 'Preview a local audio file', noFile: 'No audio selected', stop: 'Stop audio preview',
+ hint: 'Settings are included in the avatar when saved or exported. The selected audio stays in this browser.', error: 'Could not play this audio file.',
+ },
+ ja: {
+ movementTitle: '口の動きのタイプ', calm: 'ゆったり', default: '標準', lively: 'キビキビ', subtle: '控えめ', big: 'はっきり', custom: 'カスタム',
+ demoHint: '選ぶとすぐに口の動きを試せます。', granularity: '口の動き', granularityLow: 'ゆったり', granularityHigh: 'キビキビ',
+ openness: '口の大きさ', opennessLow: '小さく', opennessHigh: '大きく', closeSpeed: '閉じ方', closeSpeedLow: 'なめらか', closeSpeedHigh: 'パクパク',
+ advanced: '細かく調整する', title: '音声リップシンク',
+ file: '音声ファイルで試す', noFile: '音声未選択', stop: '音声プレビューを停止',
+ hint: '設定は保存・書き出し時にアバターへ含めます。選んだ音声はこのブラウザ内で再生します。', error: 'この音声ファイルを再生できませんでした。',
+ },
+ zh: {
+ movementTitle: '口型动作风格', calm: '舒缓', default: '标准', lively: '轻快', subtle: '含蓄', big: '鲜明', custom: '自定义',
+ demoHint: '选择风格即可预览口型动作。', granularity: '口型动作', granularityLow: '舒缓', granularityHigh: '轻快',
+ openness: '张嘴幅度', opennessLow: '小', opennessHigh: '大', closeSpeed: '闭嘴方式', closeSpeedLow: '平滑', closeSpeedHigh: '利落',
+ advanced: '精细调整', title: '语音口型同步',
+ file: '预览本地音频文件', noFile: '未选择音频', stop: '停止音频预览',
+ hint: '保存或导出时,设置将包含在虚拟形象中。所选音频仅在此浏览器中播放。', error: '无法播放此音频文件。',
+ },
+};
+
+export function LipSyncSettings({ value, onChange, avatar, onPreview, onDemo }: {
+ value?: Settings; onChange(value: Settings): void; avatar: MeshAvatar | null; onPreview(active: boolean): void; onDemo(): void;
+}) {
+ const { language } = useI18n(), t = lipSyncText[language];
+ const settings = { granularity: 0.5, openness: 0.5, closeSpeed: 0.5, ...value } as Required<Omit<Settings, 'preset'>> & Pick<Settings, 'preset'>;
+ const [url, setUrl] = useState(''), [fileName, setFileName] = useState(''), [failed, setFailed] = useState(false);
+ const pendingSlider = useRef(false);
+ const selected = settings.preset === 'custom' ? 'custom' : presetNames.find(name =>
+ (['granularity', 'openness', 'closeSpeed'] as const).every(key => presets[name][key] === settings[key])) ?? 'custom';
+ const apply = (next: typeof settings) => {
+ settingsRef.current = next;
+ avatar?.setLipSync(next);
+ onChange(next);
+ };
+ const commitSlider = () => {
+ if (!pendingSlider.current) return;
+ pendingSlider.current = false;
+ stop(); onDemo();
+ };
+ const fileInput = useRef<HTMLInputElement>(null);
+ const audio = useRef<HTMLAudioElement>(null), context = useRef<AudioContext | null>(null), analyser = useRef<AnalyserNode | null>(null);
+ const raf = useRef(0), settingsRef = useRef(settings); settingsRef.current = settings;
+ const previewRef = useRef(onPreview); previewRef.current = onPreview;
+ const stop = () => {
+ cancelAnimationFrame(raf.current); raf.current = 0;
+ audio.current?.pause(); avatar?.setSpeaking(false); avatar?.setVoiceLevel(0);
+ previewRef.current(false);
+ };
+ useEffect(() => {
+ avatar?.setLipSync(settings);
+ }, [avatar, settings.granularity, settings.openness, settings.closeSpeed]);
+ useEffect(() => () => {
+ cancelAnimationFrame(raf.current); raf.current = 0; audio.current?.pause();
+ avatar?.setSpeaking(false); previewRef.current(false);
+ }, [avatar]);
+ useEffect(() => () => { if (url) URL.revokeObjectURL(url); }, [url]);
+ useEffect(() => () => { void context.current?.close().catch(() => undefined); }, []);
+ const play = async () => {
+ if (!avatar || !audio.current) return;
+ setFailed(false);
+ try {
+ if (!context.current) {
+ const ctx = new AudioContext(); context.current = ctx;
+ const node = ctx.createAnalyser(); node.fftSize = 2048; analyser.current = node;
+ ctx.createMediaElementSource(audio.current).connect(node); node.connect(ctx.destination);
+ }
+ await context.current.resume();
+ if (audio.current.paused) return;
+ avatar.stopLipSync(); avatar.setSpeaking(true); previewRef.current(true);
+ const samples = new Float32Array(2048);
+ cancelAnimationFrame(raf.current);
+ const frame = () => {
+ if (!analyser.current || !context.current || !audio.current || audio.current.paused) return;
+ analyser.current.getFloatTimeDomainData(samples);
+ avatar.setVoiceLevel(rmsLevel(samples.subarray(1024), 1));
+ raf.current = requestAnimationFrame(frame);
+ };
+ raf.current = requestAnimationFrame(frame);
+ } catch { stop(); setFailed(true); }
+ };
+ return <div className="audio-lip-settings" data-testid="audio-lip-settings" role="group" aria-label={t.title}>
+ <div className="audio-lip-heading"><h3>{t.movementTitle}</h3>{selected === 'custom' && <span className="audio-lip-custom" role="status">{t.custom}</span>}</div>
+ <div className="audio-lip-presets" role="group" aria-label={t.movementTitle}>
+ {presetNames.map(name => <button type="button" key={name} aria-pressed={selected === name} disabled={!avatar} onClick={() => {
+ pendingSlider.current = false;
+ stop(); apply({ ...settings, ...presets[name], preset: name }); onDemo();
+ }}>{t[name]}</button>)}
+ </div>
+ <p className="audio-lip-demo-hint">{t.demoHint}</p>
+ <details className="audio-lip-advanced" onToggle={event => { if (!event.currentTarget.open) stop(); }}><summary>{t.advanced}</summary><div>
+ <div className="audio-lip-sliders">
+ {(['granularity', 'openness', 'closeSpeed'] as const).map(key => <label key={key}>
+ <span>{t[key]}</span><input type="range" aria-label={t[key]} min="0" max="1" step="0.05" value={settings[key]}
+ onChange={event => { pendingSlider.current = true; apply({ ...settingsRef.current, [key]: Number(event.target.value), preset: 'custom' }); }}
+ onPointerUp={commitSlider} onKeyUp={commitSlider} onBlur={commitSlider} />
+ <small className="audio-lip-range"><span>{t[`${key}Low`]}</span><span>{t[`${key}High`]}</span></small>
+ </label>)}
+ </div>
+ <div className="audio-file-picker">
+ <input ref={fileInput} type="file" hidden aria-label={t.file} accept="audio/*,.wav,.aiff" onChange={event => {
+ stop(); setFailed(false); const file = event.target.files?.[0]; setFileName(file?.name ?? ''); setUrl(file ? URL.createObjectURL(file) : ''); event.target.value = '';
+ }} />
+ <button type="button" disabled={!avatar} onClick={() => fileInput.current?.click()}>{t.file}</button>
+ <span role="status" aria-live="polite">{fileName || t.noFile}</span>
+ </div>
+ <audio ref={audio} src={url || undefined} controls hidden={!url} onPlay={() => { void play(); }} onPause={stop} onEnded={stop} onError={() => { if (url) { stop(); setFailed(true); } }} />
+ {url && <button onClick={stop}>{t.stop}</button>}
+ <small>{t.hint}</small>{failed && <p role="alert">{t.error}</p>}
+ </div></details>
+ </div>;
+}
diff --git a/src/editor/Preview.tsx b/src/editor/Preview.tsx
index 90fc87d..e5d930c 100644
--- a/src/editor/Preview.tsx
+++ b/src/editor/Preview.tsx
@@ -1,7 +1,8 @@
+import { LipSyncSettings } from './LipSyncSettings';
import { LightingControls, LightHandle, lightingText } from '../lighting/Controls';
import { loadLighting, saveLighting } from '../lighting/storage';
import { useEffect, useRef, useState } from 'react';
-import { createMeshAvatar, type MeshAvatar, PARAMS, type Rig } from 'mesh-avatar';
+import { createMeshAvatar, type MeshAvatar, PARAMS, type Rig, type LipSyncSettings as AudioSettings } from 'mesh-avatar';
import { VOWELS, skippedKanaCharacters } from '../../packages/runtime/src/engine/kana.js';
import { useI18n } from './i18n';
import { Icon } from './Icon';
@@ -17,8 +18,8 @@ const sliders = [
{ id: 'bodyAngleZ', label: 'bodyTilt', min: -10, max: 10, def: 0 },
] as const;
type Vowel = 'a' | 'i' | 'u' | 'e' | 'o' | 'n';
-type Lip = { kind: 'hold'; vowel: Vowel } | { kind: 'text'; text: string; speed: number; loop: boolean } | null;
-export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth }: { projectKey: string; rig: Rig; assets?: Record<string, string>; hasMouthSprites: boolean; onDrawMouth?: () => void }) {
+type Lip = { kind: 'hold'; vowel: Vowel } | { kind: 'text'; text: string; speed: number; loop: boolean; source: 'user' | 'sample' } | null;
+export function Preview({ projectKey, rig, assets, lipSync, onLipSyncChange, hasMouthSprites, onDrawMouth }: { projectKey: string; rig: Rig; assets?: Record<string, string>; lipSync?: AudioSettings; onLipSyncChange(value: AudioSettings): void; hasMouthSprites: boolean; onDrawMouth?: () => void }) {
const { t, language } = useI18n();
const [lighting, setLighting] = useState(() => loadLighting(projectKey));
const lightRef = useRef(lighting); lightRef.current = lighting;
@@ -29,8 +30,9 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
const [idle, setIdle] = useState(true);
const [stress, setStress] = useState(false);
const [parameters, setParameters] = useState<Record<string, number>>({});
+ const [audioActive, setAudioActive] = useState(false);
const [lip, setLip] = useState<Lip>(null);
- const [text, setText] = useState('あいうえお');
+ const [text, setText] = useState('あいうえお、こんにちは');
const [speed, setSpeed] = useState(7);
const [loop, setLoop] = useState(false);
const [liveMouth, setLiveMouth] = useState(0);
@@ -78,7 +80,7 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
if (lip?.kind === 'hold') value.holdMouth(lip.vowel);
if (lip?.kind === 'text') value.speakKana(lip.text, { speed: lip.speed, loop: lip.loop });
value.advance(0);
- if (!idle && !stress && !lip) return;
+ if (!idle && !stress && !lip && !audioActive) return;
let raf = 0;
const start = performance.now();
let previous = start;
@@ -90,7 +92,7 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
angleZ: Math.sin(t * 1.1) * 25, bodyAngleZ: Math.cos(t * 0.7) * 8 });
if (t >= 6) { setStress(false); return; }
}
- value.advance(lip ? Math.min(0.05, Math.max(0, (now - previous) / 1000)) : 1 / 60);
+ value.advance(lip || audioActive ? Math.min(0.05, Math.max(0, (now - previous) / 1000)) : 1 / 60);
previous = now;
if (lip) {
const state = value.getLipSyncState();
@@ -101,7 +103,7 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
};
raf = requestAnimationFrame(frame);
return () => cancelAnimationFrame(raf);
- }, [rig, assets, idle, stress, parameters, revision, lip]);
+ }, [rig, assets, idle, stress, parameters, revision, lip, audioActive]);
useEffect(() => {
saveLighting(projectKey, lighting);
avatar.current?.setLighting(lighting);
@@ -109,14 +111,14 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
}, [lighting, projectKey]);
return (
<section className="panel preview-panel">
- <div className="panel-title"><h2>{t.preview}</h2><span role="status" data-testid="preview-status" data-state={status}>{t[status]}</span></div>
+ <div className="panel-title"><h2>{t.preview}</h2><span role="status" data-testid="preview-status" data-state={status}>{t[status]}</span>{tab === 'lip' && <button className="icon-button lip-idle-toggle" aria-label={idle ? t.pause : t.play} title={idle ? t.pause : t.play} data-testid="idle-toggle" aria-pressed={idle} onClick={() => setIdle(current => !current)}><Icon name={idle ? 'pause' : 'play'} /></button>}</div>
<div className="lighting-preview"><canvas ref={canvas} data-testid="preview" data-revision={revision} className="preview-canvas"
style={{ aspectRatio: `${rig.image.width * (1 + 2 * rig.view.padSide)} / ${rig.image.height * (1 + rig.view.padTop)}` }} />
{lightingOpen && <LightHandle value={lighting} onChange={setLighting} language={language} />}
</div>
- <div className="preview-tools">
+ <div className="preview-tools" hidden={tab === 'lip'}>
<button className="icon-button" aria-label={idle ? t.pause : t.play} title={idle ? t.pause : t.play}
- data-testid="idle-toggle" aria-pressed={idle} onClick={() => setIdle(current => !current)}><Icon name={idle ? 'pause' : 'play'} /></button><span>{t.idle}</span>
+ data-testid={tab === 'pose' ? 'idle-toggle' : undefined} aria-pressed={idle} onClick={() => setIdle(current => !current)}><Icon name={idle ? 'pause' : 'play'} /></button><span>{t.idle}</span>
</div>
<div className="preview-tabs" role="tablist" aria-label={t.preview}>
<button id="pose-tab" role="tab" aria-selected={tab === 'pose'} aria-controls="pose-panel" onClick={() => setTab('pose')}><Icon name="pose" />{t.pose}</button>
@@ -143,23 +145,29 @@ export function Preview({ projectKey, rig, assets, hasMouthSprites, onDrawMouth
<button className="sweep-button" title={t.sweepTip} onClick={() => setStress(current => !current)}>{stress ? t.stopSweep : t.sweep}</button></div>
</div>
<div className="lip-sync" id="lip-panel" role="tabpanel" aria-labelledby="lip-tab" hidden={tab !== 'lip'}>
+ <div className="lip-text-row"><input aria-label={t.lipText} value={text} onChange={event => setText(event.target.value)} />
+ <button disabled={!text.trim()} onClick={() => setLip({ kind: 'text', text, speed, loop, source: 'user' })}>{t.lipPlay}</button>
+ <button disabled={!lip} onClick={() => setLip(null)}>{t.lipStop}</button>
+ </div>
+ <div className="sliders lip-live"><label>{t.mouthOpen}<input type="range" aria-label={t.mouthOpen} min="0" max="1" step="0.01" disabled={lip !== null}
+ value={lip ? liveMouth : parameters.mouthOpen ?? 0} onChange={event => setParameters(current => ({ ...current, mouthOpen: Number(event.target.value) }))} /><output>{(lip ? liveMouth : parameters.mouthOpen ?? 0).toFixed(2)}</output></label></div>
+ <LipSyncSettings value={lipSync} onChange={onLipSyncChange} avatar={avatar.current} onDemo={() => {
+ if (lip?.kind === 'text' && lip.source === 'user') return;
+ avatar.current?.stopLipSync();
+ setLip({ kind: 'text', text: 'あいうえお、こんにちは', speed, loop: false, source: 'sample' });
+ }} onPreview={active => { if (active) setLip(null); setAudioActive(active); }} />
<div className="vowel-buttons" role="group" aria-label={t.lipSync}>
{(Object.keys(VOWELS) as Vowel[]).map(vowel => <button key={vowel} aria-pressed={lip?.kind === 'hold' && lip.vowel === vowel}
onClick={() => setLip(current => current?.kind === 'hold' && current.vowel === vowel ? null : { kind: 'hold', vowel })}>{VOWELS[vowel].label}</button>)}
<button onClick={() => setLip(null)}>{t.release}</button>
</div>
- <div className="lip-text-row"><input aria-label={t.lipText} value={text} onChange={event => setText(event.target.value)} />
- <button disabled={!text.trim()} onClick={() => setLip({ kind: 'text', text, speed, loop })}>{t.lipPlay}</button>
- <button disabled={!lip} onClick={() => setLip(null)}>{t.lipStop}</button>
- </div>
<div className="lip-options"><label className="lip-speed">{t.lipSpeed}<input type="range" min="4" max="12" step="1" value={speed} aria-label={t.lipSpeed}
onChange={event => { const value = Number(event.target.value); setSpeed(value); setLip(current => current?.kind === 'text' ? { ...current, speed: value } : current); }} /><output>{speed}</output></label>
<label><input type="checkbox" checked={loop} onChange={event => { const value = event.target.checked; setLoop(value); setLip(current => current?.kind === 'text' ? { ...current, loop: value } : current); }} />{t.lipLoop}</label>
</div>
{!hasMouthSprites && <p className="mouth-fallback">{t.mouthFallback} {onDrawMouth && <button type="button" onClick={onDrawMouth}>{t.drawMouth}</button>}</p>}
<p className="lip-help">{t.lipHelp}</p>{skipped && <p className="lip-skipped">{t.skippedKana} {skipped}</p>}
- <div className="sliders lip-live"><label>{t.mouthOpen}<input type="range" aria-label={t.mouthOpen} min="0" max="1" step="0.01" disabled={lip !== null}
- value={lip ? liveMouth : parameters.mouthOpen ?? 0} onChange={event => setParameters(current => ({ ...current, mouthOpen: Number(event.target.value) }))} /><output>{(lip ? liveMouth : parameters.mouthOpen ?? 0).toFixed(2)}</output></label></div>
+
</div>
<details className="lighting-section" 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>
diff --git a/src/editor/project.ts b/src/editor/project.ts
index 6bcf33e..b26fb04 100644
--- a/src/editor/project.ts
+++ b/src/editor/project.ts
@@ -1,4 +1,4 @@
-import { openAvatar, parseRig, type Rig, type AvatarPackage } from 'mesh-avatar';
+import { openAvatar, parseRig, type Rig, type AvatarPackage, parseManifest, type LipSyncSettings } from 'mesh-avatar';
import type { LocalProject, LocalProjectEntry } from '../project-types';
import { FolderOpenError } from './folder-errors';
import { packProjectAvatar } from '../../packages/runtime/src/format/project-archive';
@@ -16,6 +16,7 @@ export interface ProjectAssets {
assets: Record<string, string>;
rig?: Rig;
urls: string[];
+ lipSync?: LipSyncSettings;
}
export async function openProjectFolder(files: File[]): Promise<ProjectAssets> {
const entries = files.map(file => ({ file, path: file.webkitRelativePath.replace(/^[^/]+\//, '') || file.name }));
@@ -43,6 +44,8 @@ export async function openProjectFolder(files: File[]): Promise<ProjectAssets> {
for (const entry of entries.filter(entry => entry.path.startsWith(prefix))) {
built.push({ entry, bytes: entry === layers ? layerBytes : await read(entry) });
}
+ const manifestFile = entries.find(entry => entry.path === 'avatar.json');
+ const lipSync = manifestFile ? parseManifest(JSON.parse(new TextDecoder().decode(await read(manifestFile)))).lipSync : undefined;
const urls: string[] = [];
const sourceUrl = URL.createObjectURL(new Blob([sourceBytes], { type: source.file.type }));
urls.push(sourceUrl);
@@ -51,7 +54,7 @@ export async function openProjectFolder(files: File[]): Promise<ProjectAssets> {
urls.push(url);
return [entry.path.slice(prefix.length), url];
}));
- return { sourceUrl, assets, rig, urls };
+ return { sourceUrl, assets, rig, urls, lipSync };
}
export async function localProjects(): Promise<LocalProjectEntry[] | null> {
@@ -80,7 +83,7 @@ export async function importAvatar(file: File): Promise<LocalProject> {
if (!response.ok) throw new Error(result.error);
return result;
}
-export async function exportAvatar(name: string, includeSource: boolean, pickedFiles?: File[]): Promise<Blob> {
+export async function exportAvatar(name: string, includeSource: boolean, pickedFiles?: File[], lipSync?: LipSyncSettings): Promise<Blob> {
if (pickedFiles) {
const entries = new Map(pickedFiles.map(file => [file.webkitRelativePath.replace(/^[^/]+\//, '') || file.name, file]));
const bytes = await packProjectAvatar(async paths => {
@@ -90,10 +93,10 @@ export async function exportAvatar(name: string, includeSource: boolean, pickedF
if (file) files[path] = new Uint8Array(await file.arrayBuffer());
}
return files;
- }, { name, includeSource });
+ }, { name, includeSource, lipSync });
return new Blob([new Uint8Array(bytes)], { type: 'application/octet-stream' });
}
- const response = await fetch('/__studio/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ project: name, includeSource }) });
+ const response = await fetch('/__studio/export', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ project: name, includeSource, lipSync }) });
if (!response.ok) throw new Error((await response.json()).error);
return response.blob();
}
@@ -138,14 +141,14 @@ async function jsonFile(url: string) {
}
export async function openLocalProject(project: LocalProject): Promise<ProjectAssets> {
const base = baseUrl(project), version = Date.now();
- const { rig, assets } = await openAvatar(base, { version, rigFile: project.rigFile });
+ const { rig, assets, manifest } = await openAvatar(base, { version, rigFile: project.rigFile });
const sourceUrl = project.hasSource === false ? '' : `${base}source.png?v=${version}`;
// Check images before replacing the editor's current project.
const urls = [sourceUrl, ...Object.entries(assets).filter(([name]) => name.endsWith('.png')).map(([, url]) => url)].filter(Boolean);
await Promise.all(urls.map(url => new Promise<void>((done, reject) => {
const image = new Image(); image.onload = () => done(); image.onerror = () => reject(new Error('Missing project image.')); image.src = url;
})));
- return { sourceUrl, assets, rig, urls: [] };
+ return { sourceUrl, assets, rig, urls: [], lipSync: manifest.lipSync };
}
export async function projectAction(project: LocalProject, action: 'rig' | 'reveal', rig?: Rig): Promise<{ path: string }> {
const response = await fetch(`${baseUrl(project)}${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: rig ? JSON.stringify(rig) : '{}' });
@@ -161,3 +164,8 @@ export function sampleImagesAvailable(): Promise<boolean> {
image.src = url;
}))).then(results => results.every(Boolean));
}
+
+export async function saveLipSync(project: LocalProject, lipSync: LipSyncSettings) {
+ const response = await fetch(`${baseUrl(project)}lip-sync`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(lipSync) });
+ if (!response.ok) throw new Error('Could not save lip sync settings.');
+}
diff --git a/src/editor/style.css b/src/editor/style.css
index ee94e9c..8888405 100644
--- a/src/editor/style.css
+++ b/src/editor/style.css
@@ -250,3 +250,41 @@ main:has(.stale) .editor-panel, main:has(.stale) .parts-panel { height: calc(100
.agent-recipient button { font-size: 12px; padding: 5px 8px; }
.agent-recipient button[aria-pressed="true"] { color: var(--accent); background: var(--accent-soft); border-color: #b3cdfa; }
.agent-disclosure { font-size: 11px; color: var(--muted); margin: 6px 0; }
+
+.audio-lip-settings { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--line); }
+.audio-lip-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
+.audio-lip-heading h3 { font-size: 13px; margin: 0; }
+.audio-lip-custom { font-size: 11px; border: 1px solid var(--accent); color: var(--accent); border-radius: 12px; padding: 2px 8px; }
+.audio-lip-presets { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
+.audio-lip-presets button { min-width: 0; border: 1px solid var(--line); border-radius: 7px; padding: 8px 4px; font-size: 12px; }
+.audio-lip-presets button[aria-pressed="true"] { color: var(--accent); border-color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, var(--surface)); font-weight: 600; }
+.audio-lip-demo-hint { margin: 9px 0 0; color: var(--muted); font-size: 11px; line-height: 1.5; }
+.audio-lip-sliders { display: grid; gap: 20px; padding: 6px 0 12px; }
+.audio-lip-sliders > label { display: grid; gap: 6px; align-items: center; font-size: 12px; }
+.audio-lip-sliders > label > span { font-weight: 500; }
+.audio-lip-sliders input { width: 100%; min-width: 0; margin: 3px 0; accent-color: var(--accent); }
+.audio-lip-range { display: flex; justify-content: space-between; gap: 12px; color: var(--muted); font-size: 11px; }
+.audio-lip-advanced { margin-top: 16px; }
+.audio-lip-advanced > summary { color: var(--muted); font-size: 12px; cursor: pointer; }
+.audio-lip-advanced > div { display: grid; gap: 10px; margin: 10px 0; }
+.audio-lip-advanced label { display: grid; gap: 6px; font-size: 12px; }
+.audio-lip-advanced audio, .audio-lip-advanced input[type="file"] { width: 100%; min-width: 0; }
+.audio-lip-advanced small { color: var(--muted); font-size: 11px; line-height: 1.5; }
+@media (min-width: 1200px) {
+ .preview-panel:has(#lip-tab[aria-selected="true"]) { display: flex; flex-direction: column; max-height: inherit; }
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .panel-title,
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .lighting-preview,
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .preview-tools,
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .preview-tabs { flex-shrink: 0; }
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .lip-sync,
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .lighting-section { min-height: 0; overflow-y: auto; scrollbar-width: thin; }
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .lip-sync { flex: 1 1 auto; }
+ .preview-panel:has(#lip-tab[aria-selected="true"]) > .lighting-section:not([open]) { flex-shrink: 0; }
+}
+
+.preview-tools[hidden] { display: none; }
+.preview-panel .lip-idle-toggle { width: 20px; height: 20px; padding: 2px; border: 0; color: var(--accent); }
+#lip-panel .lip-live { margin: 0; }
+.audio-file-picker { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
+.audio-file-picker button { font-size: 12px; padding: 6px 10px; }
+.audio-file-picker span { flex: 1; min-width: 0; overflow-wrap: anywhere; font-size: 11px; color: var(--muted); }
diff --git a/src/live/avatar-view.ts b/src/live/avatar-view.ts
index 5a29c2e..25dc0e1 100644
--- a/src/live/avatar-view.ts
+++ b/src/live/avatar-view.ts
@@ -15,7 +15,8 @@ export async function createAvatarView(canvas: HTMLCanvasElement, settings: View
const projects = await localProjects(), project = projects?.find(entry => entry.name === settings.project);
if (project?.error || (!project && settings.project !== SAMPLE_PROJECT)) throw new Error('Project unavailable');
const loaded = project ? await openLocalProject(project) : await openSampleAvatar();
- avatar = await createMeshAvatar(canvas, { ...options, rig: loaded.rig!, assets: loaded.assets });
+ const lipSync = 'manifest' in loaded ? loaded.manifest.lipSync : loaded.lipSync;
+ avatar = await createMeshAvatar(canvas, { ...options, lipSync, rig: loaded.rig!, assets: loaded.assets });
}
if (settings.lighting) avatar.setLighting(settings.lighting);
avatar.setAutoIdle(settings.idle); avatar.setAutoMotion(settings.idle);
diff --git a/src/server/local-projects.ts b/src/server/local-projects.ts
index 9854e1a..a9d5faa 100644
--- a/src/server/local-projects.ts
+++ b/src/server/local-projects.ts
@@ -206,7 +206,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
saving.add(path);
try {
let bytes: Uint8Array;
- try { bytes = await packProjectAvatar(names => readSelected(path, names), { name: body.project, includeSource: body.includeSource ?? true }); }
+ try { bytes = await packProjectAvatar(names => readSelected(path, names), { name: body.project, includeSource: body.includeSource ?? true, lipSync: body.lipSync }); }
catch (error) { if (error instanceof HttpError || (error as NodeJS.ErrnoException).code) throw error; throw new HttpError(400, (error as Error).message); }
res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Disposition': `attachment; filename="${body.project}.mavatar"`, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
res.end(Buffer.from(bytes));
@@ -288,7 +288,7 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
const manifest = resolve(path, 'built/sprites/sprites.json'); if (await exists(manifest)) await checked(path, manifest);
json(200, { variants: await variantState(path), requests: await requests(path, name) }); return;
}
- if (req.method === 'POST' && tail.length === 1 && ['rig', 'rebuild', 'variant-requests', 'import-variants'].includes(tail[0])) {
+ if (req.method === 'POST' && tail.length === 1 && ['rig', 'lip-sync', 'rebuild', 'variant-requests', 'import-variants'].includes(tail[0])) {
if (name === SAMPLE) throw new HttpError(403, 'The sample is read-only.');
if (!await sourceFile(path)) throw new HttpError(403, 'Source image is missing. This avatar is playback-only.');
const action = tail[0], body = await readBody(req, action === 'import-variants' ? 36 * 1024 * 1024 : 1024 * 1024);
@@ -297,7 +297,17 @@ export function localProjectMiddleware(root: string, reveal = revealFolder, runn
if (saving.has(path)) throw new HttpError(409, 'A project operation is already in progress.');
saving.add(path);
try {
- if (action === 'rig') { await saveRig(path, body); json(200, { path: relative(root, resolve(path, 'rig.json')).split(sep).join('/') }); }
+ if (action === 'lip-sync') {
+ const target = resolve(path, 'avatar.json'), temporary = resolve(path, `.avatar-${randomUUID()}.tmp`);
+ let raw: Record<string, unknown> = { format: 'mesh-avatar', version: 1, name };
+ if (await exists(target)) raw = JSON.parse(await readFile(await checked(path, target), 'utf8'));
+ const manifest = { ...raw, lipSync: body };
+ try { manifest.lipSync = parseManifest(manifest).lipSync; } catch (error) { throw new HttpError(400, (error as Error).message); }
+ try { await writeFile(temporary, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx' }); await rename(temporary, target); }
+ finally { await unlink(temporary).catch(() => undefined); }
+ json(200, { path: relative(root, target).split(sep).join('/') });
+ }
+ else if (action === 'rig') { await saveRig(path, body); json(200, { path: relative(root, resolve(path, 'rig.json')).split(sep).join('/') }); }
else {
if (action === 'rebuild' || action === 'variant-requests') await saveRig(path, body?.rig);
const result = await projectJob(root, path, action === 'rebuild' ? 'build-layers' : action === 'variant-requests' ? 'variant-requests' : 'build-sprites', files, runner);
diff --git a/tests/avatar-transfer.test.ts b/tests/avatar-transfer.test.ts
index 3feef0e..32208a2 100644
--- a/tests/avatar-transfer.test.ts
+++ b/tests/avatar-transfer.test.ts
@@ -44,6 +44,18 @@ async function call(path: string, data?: unknown, headers: Record<string, string
}
const exported = () => call('export', { project: 'sample-miko-qipao', includeSource: true });
+test('export and import retain lip-sync preferences without modifying the sample manifest', async () => {
+ const lipSync = { granularity: 0.2, openness: 0.75, closeSpeed: 0.1, preset: 'custom' };
+ const result = await call('export', { project: 'sample-miko-qipao', lipSync });
+ expect(result.status).toBe(200);
+ const packed = unpackAvatar(result.bytes), manifest = JSON.parse(new TextDecoder().decode(packed['avatar.json']));
+ expect(manifest.lipSync).toEqual(lipSync);
+ expect((await call('import', result.bytes)).status).toBe(200);
+ expect(JSON.parse(await readFile(resolve(root, 'projects/Miko-qipao/avatar.json'), 'utf8')).lipSync).toEqual(lipSync);
+ expectSameBytes(await readFile(resolve(root, 'samples/miko-qipao/avatar.json')), fixture['avatar.json'], 'sample manifest');
+ expect((await call('export', { project: 'sample-miko-qipao', lipSync: { openness: 1.1 } })).status).toBe(400);
+});
+
function expectSameBytes(actual: Uint8Array, expected: Uint8Array, path: string) {
// Compare every byte without traversing large typed arrays as object properties.
expect(Buffer.from(actual).equals(expected), `${path}: all bytes must match`).toBe(true);
diff --git a/tests/lip-motion-settings.test.ts b/tests/lip-motion-settings.test.ts
new file mode 100644
index 0000000..5587ba0
--- /dev/null
+++ b/tests/lip-motion-settings.test.ts
@@ -0,0 +1,93 @@
+import { expect, test, vi } from 'vitest';
+import { Motion } from '../packages/runtime/src/engine/motion.js';
+import { kanaToMoras, sampleMoras } from '../packages/runtime/src/engine/kana.js';
+import type { LipSyncSettings } from 'mesh-avatar';
+
+type Settings = LipSyncSettings;
+function audio(settings: Settings) {
+ const motion = new Motion([0, 0]); motion.mode = 'manual'; motion.setLipSync(settings);
+ motion.setSpeaking(true);
+ const trace: { open: number; form: number }[] = [];
+ for (let f = 0; f < 240; f++) {
+ motion.setVoiceLevel(f < 15 || f > 220 ? 0 : f % 20 < 5 ? 0.4 : 0.8);
+ const p = motion.update(1 / 60); trace.push({ open: p.mouthOpen, form: p.mouthForm });
+ }
+ return trace;
+}
+const cycles = (trace: { open: number }[]) => trace.filter((p, i) => p.open > 0.3 && (!i || trace[i - 1].open <= 0.3)).length;
+const mean = (trace: { open: number }[]) => trace.reduce((sum, p) => sum + p.open, 0) / trace.length;
+
+test('movement settings change loudness cycles and amplitude', () => {
+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.1);
+ try {
+ const calm = audio({ granularity: 0, closeSpeed: 0 }), lively = audio({ granularity: 1, closeSpeed: 1 });
+ expect(cycles(lively)).toBeGreaterThanOrEqual(2 * cycles(calm));
+ const subtle = audio({ openness: 0 }), big = audio({ openness: 1 });
+ expect(mean(big)).toBeGreaterThan(mean(subtle) * 1.8);
+ expect(Math.max(...big.map(p => p.open))).toBeLessThanOrEqual(1);
+ } finally { random.mockRestore(); }
+});
+
+test('closing speed changes release after the same audio and held kana opening', () => {
+ for (const kana of [false, true]) {
+ const run = (closeSpeed: number) => {
+ const m = new Motion([0, 0]); m.mode = 'manual'; m.setLipSync({ closeSpeed });
+ if (kana) m.holdMouth('a'); else { m.setSpeaking(true); m.setVoiceLevel(0.8); }
+ for (let f = 0; f < 60; f++) m.update(1 / 60);
+ if (kana) m.holdMouth('n'); else m.setVoiceLevel(0);
+ for (let f = 0; f < 6; f++) m.update(1 / 60);
+ return m.P.mouthOpen;
+ };
+ expect(run(0)).toBeGreaterThan(0.3); expect(run(1)).toBeLessThan(0.03);
+ }
+});
+
+test('kana sensitivity groups short morae, strengthens high-sensitivity closures and keeps long pauses', () => {
+ const moras = kanaToMoras('まみむめもまみむめも。', 0.14);
+ const forms = (g: number) => Array.from({ length: 95 }, (_, f) => sampleMoras(moras, f / 60, g)?.form);
+ const count = (values: (number | null | undefined)[]) => values.slice(1).filter((x, i) => x !== null && x !== undefined && x !== values[i]).length;
+ expect(count(forms(1))).toBeGreaterThanOrEqual(count(forms(0)) * 2);
+ expect(sampleMoras(moras, 0.14 + 0.005, 0)!.open).toBeGreaterThan(sampleMoras(moras, 0.14 + 0.005, 1)!.open);
+ expect(sampleMoras(moras, 1.5, 0)!.open).toBe(0);
+ for (const openness of [0, 1]) {
+ const m = new Motion([0, 0]); m.mode = 'manual'; m.setLipSync({ openness }); m.holdMouth('a');
+ for (let f = 0; f < 60; f++) m.update(1 / 60);
+ expect(m.P.mouthOpen).toBeCloseTo(openness ? 1 : 0.495, 5);
+ }
+});
+
+test('new options reject out-of-range inputs and partial updates retain the other values', () => {
+ const m = new Motion([0, 0]); m.setLipSync({ openness: 0.7 });
+ for (const key of ['granularity', 'openness', 'closeSpeed'])
+ for (const value of [-0.01, 1.01, NaN, Infinity, '0.5', null])
+ expect(() => m.setLipSync({ [key]: value })).toThrow(RangeError);
+ m.setLipSync({ granularity: 0.2 });
+ expect(m.lipSync.openness).toBe(0.7); expect(m.lipSync.closeSpeed).toBe(0.5);
+});
+
+test('explicit center settings preserve every parameter and random draw in audio and kana paths', () => {
+ const random = vi.spyOn(Math, 'random');
+ const run = (explicit: boolean) => {
+ let state = 42; random.mockImplementation(() => { state = Math.imul(state, 1664525) + 1013904223 >>> 0; return state / 4294967296; });
+ const m = new Motion([0, 0]), trace = [];
+ if (explicit) m.setLipSync({ granularity: 0.5, openness: 0.5, closeSpeed: 0.5 });
+ m.setSpeaking(true);
+ for (let f = 0; f < 900; f++) {
+ m.setVoiceLevel(Math.max(0, Math.sin(f * 0.2)) * 0.8);
+ if (f === 300) { m.setSpeaking(false); m.speakKana('まみむめも、あいうえお'); }
+ if (f === 600) m.holdMouth('o');
+ trace.push({ ...m.update(1 / 60) });
+ }
+ return { trace, state };
+ };
+ try { expect(run(true)).toEqual(run(false)); } finally { random.mockRestore(); }
+});
+
+
+test('preset metadata alone leaves movement at its defaults', () => {
+ const motion = new Motion([0, 0]);
+ motion.setLipSync({ preset: 'big' });
+ expect(motion.lipSync).toEqual({ granularity: 0.5, openness: 0.5, closeSpeed: 0.5 });
+ expect(() => motion.setLipSync({ openness: 0.1, closeSpeed: 2 })).toThrow(RangeError);
+ expect(motion.lipSync).toEqual({ granularity: 0.5, openness: 0.5, closeSpeed: 0.5 });
+});
diff --git a/tests/local-projects.test.ts b/tests/local-projects.test.ts
index 8886803..40b268c 100644
--- a/tests/local-projects.test.ts
+++ b/tests/local-projects.test.ts
@@ -48,6 +48,20 @@ async function call(path: string, method = 'GET', body?: unknown, headers: Recor
return result;
}
+test('saves lip sync settings atomically in the manifest without changing the rig or unrelated metadata', async () => {
+ const path = resolve(root, 'projects/nova/avatar.json');
+ await writeFile(path, JSON.stringify({ format: 'mesh-avatar', version: 1, name: 'Nova', author: 'Artist', custom: { keep: true } }));
+ const rigBefore = await readFile(resolve(root, 'projects/nova/rig.json'), 'utf8');
+ const lipSync = { granularity: 0.2, openness: 0.75, closeSpeed: 0.1, preset: 'custom' };
+ expect((await call('/__studio/projects/nova/lip-sync', 'POST', lipSync)).status).toBe(200);
+ const saved = await readFile(path, 'utf8');
+ expect(JSON.parse(saved)).toMatchObject({ name: 'Nova', author: 'Artist', custom: { keep: true }, lipSync });
+ expect(await readFile(resolve(root, 'projects/nova/rig.json'), 'utf8')).toBe(rigBefore);
+ expect((await call('/__studio/projects/nova/lip-sync', 'POST', { openness: 1.1 })).status).toBe(400);
+ expect(await readFile(path, 'utf8')).toBe(saved);
+ expect((await call('/__studio/projects/sample-miko-qipao/lip-sync', 'POST', lipSync)).status).toBe(403);
+});
+
test('lists eligible projects and the read-only installed sample, and serves project images', async () => {
await mkdir(resolve(root, 'projects/unbuilt'), { recursive: true });
await writeFile(resolve(root, 'projects/unbuilt/rig.draft.json'), '{}');