// CHIMERA 口の配線:プランナ(chimera_call)+ジェスチャレコード化+AudioWorklet エンジン。 // 変換規則は Rust 実装(chimera-cli render.rs の apply_overrides、chimera-wasm lib.rs のレコード形式)に一致させる。 export const ARTIC_KEYS = ['jaw', 'tbX', 'tbY', 'ttX', 'ttY', 'ttCurl', 'root', 'lipAp', 'lipProt', 'lipWidth', 'labiodental', 'velum', 'larynx', 'epilarynx', 'ventricular', 'lateral', 'dorsum']; export const CONTROL_KEYS = [...ARTIC_KEYS, 'abduction', 'closure', 'breath', 'f0', 'vibrato']; export const GESTURE_RECORD = 272; export class ChimeraPlanner { constructor(instance) { this.x = instance.exports; this._catalog = null; } static async create(wasmBytes) { const { instance } = await WebAssembly.instantiate(wasmBytes, {}); return new ChimeraPlanner(instance); } call(obj) { const bytes = new TextEncoder().encode(JSON.stringify(obj)); const ptr = this.x.chimera_alloc(bytes.length); new Uint8Array(this.x.memory.buffer, ptr, bytes.length).set(bytes); const code = this.x.chimera_call(ptr, bytes.length); const len = this.x.chimera_result_len(); const rptr = this.x.chimera_result_ptr(); const text = new TextDecoder().decode(new Uint8Array(this.x.memory.buffer, rptr, len)); this.x.chimera_free(ptr, bytes.length); const v = JSON.parse(text); if (code !== 0 || (v && v.error)) throw new Error(`chimera_call ${obj.fn}: ${(v && v.error) || code}`); return v; } catalog() { if (!this._catalog) this._catalog = this.call({ fn: 'catalog' }); return this._catalog; } maleBody() { return this.catalog().bodies.male; } planUtterance(segments, options) { return this.call({ fn: 'planUtterance', segments, options }); } plannedCounts(ipas) { return this.call({ fn: 'plannedCounts', ipa: ipas }); } } // Rust の apply_overrides の移植。inputs: [{ipa, overrides:{key:value}}]、counts: plannedCounts の結果。 export function applyOverrides(plan, inputs, counts) { const plannedOf = []; let p = 0; for (let i = 0; i < inputs.length; i++) { plannedOf.push(p); p += counts[i] || 1; } if (p !== plan.segments.length) throw new Error(`plan has ${plan.segments.length} segments for ${inputs.length} inputs`); for (let i = 0; i < inputs.length; i++) { const ov = inputs[i].overrides; if (!ov || Object.keys(ov).length === 0) continue; const ps = plan.segments[plannedOf[i]]; const lo = ps.t0 - 0.05, hi = ps.t1 + 0.05; const mine = []; plan.gestures.forEach((g, j) => { const end = g.t1 + g.rampOut + (g.releaseHold || 0); if ((g.label || '') === ps.ipa && g.t0 - g.rampIn <= hi && end >= lo) mine.push(j); }); if (mine.length === 0) throw new Error(`segment ${i} (${ps.ipa}): no gesture carries its label`); for (const [name, value] of Object.entries(ov)) { if (!CONTROL_KEYS.includes(name)) throw new Error(`segment ${i}: unknown control key ${name}`); const withKey = mine.filter(j => plan.gestures[j].targets && plan.gestures[j].targets[name] !== undefined); let targets = withKey; if (targets.length === 0) { const maxS = Math.max(...mine.map(j => plan.gestures[j].strength)); targets = mine.filter(j => plan.gestures[j].strength === maxS); } for (const j of targets) plan.gestures[j].targets[name] = value; } } return plan; } // Plan の gestures を wasm のレコード領域形式(272 バイト/件)へ変換する。 export function gesturesToRecords(plan) { const n = plan.gestures.length; const buf = new Uint8Array(n * GESTURE_RECORD); const dv = new DataView(buf.buffer); const enc = new TextEncoder(); plan.gestures.forEach((g, i) => { const o = i * GESTURE_RECORD; dv.setFloat64(o + 0, g.t0, true); dv.setFloat64(o + 8, g.t1, true); dv.setFloat64(o + 16, g.rampIn, true); dv.setFloat64(o + 24, g.rampOut, true); dv.setFloat64(o + 32, g.strength, true); dv.setFloat64(o + 40, g.speed ?? NaN, true); dv.setFloat64(o + 48, g.releaseHold ?? NaN, true); dv.setFloat64(o + 56, g.tag ?? NaN, true); for (let k = 0; k < 22; k++) { const v = g.targets ? g.targets[CONTROL_KEYS[k]] : undefined; dv.setFloat64(o + 64 + k * 8, v === undefined ? NaN : v, true); } if (g.label) { let bytes = enc.encode(g.label); while (bytes.length > 24) bytes = bytes.slice(0, bytes.length - 1); // 24 バイト上限(概ね境界一致) buf[o + 240] = bytes.length; buf.set(bytes, o + 241); } else { buf[o + 240] = 255; } }); return buf; } // ドライバの plan segments([{ipa, dur, overrides}])→ 発話可能なレコード列+総尺。 export function buildSpeech(planner, segments, f0) { const inputs = segments.map(s => ({ ipa: s.ipa, dur: s.dur, overrides: s.overrides || {} })); const counts = planner.plannedCounts(inputs.map(s => s.ipa)); const plan = planner.planUtterance( inputs.map(s => ({ ipa: s.ipa, dur: s.dur })), { body: planner.maleBody(), t0: 0.05, f0, rate: 1.0 }); applyOverrides(plan, inputs, counts); return { records: gesturesToRecords(plan), count: plan.gestures.length, end: plan.end, plan }; } // フレームレイアウト(mouth-worker.js が返す frames の先頭 20 float は v0.14 以来の // 固定レイアウト):[timeSec, outRms, voicing, artic[17], ...面積・圧力・流量]。 // artic は声道の 17 次元(cm 系の実座標)で、顔や計器を駆動したいホスト向けに // playbackTelemetry() からそのまま渡す。 export const FRAME_LAYOUT = { TIME: 0, RMS: 1, VOICING: 2, ARTIC_OFF: 3, ARTIC_N: 17, HEAD_FLOATS: 20 }; // ブラウザ用(v0.14 本線):Web Worker 上で 24kHz オフライン合成し、ネイティブ // AudioBufferSourceNode で再生する。AudioWorklet での 48kHz リアルタイム合成に // よるモバイル CPU 飽和・無音停止を防ぎ、音声再生を AudioContext.currentTime // 基準で正確に追えるようにする。 export async function createMouthPlayer(audioCtx, wasmBytes, hooks = {}) { const worker = new Worker(new URL('./mouth-worker.js', import.meta.url), { type: 'module' }); let seq = 0; const pending = new Map(); worker.onmessage = (ev) => { const m = ev.data || {}; const p = pending.get(m.id); if (!p) return; pending.delete(m.id); if (m.ok) p.resolve(m); else p.reject(new Error(m.error || 'mouth-worker error')); }; worker.onerror = (ev) => { const msg = ev && ev.message ? ev.message : 'mouth-worker crashed'; hooks.onError && hooks.onError(msg); for (const p of pending.values()) p.reject(new Error(msg)); pending.clear(); }; const call = (msg, transfer = []) => new Promise((resolve, reject) => { const id = ++seq; pending.set(id, { resolve, reject }); worker.postMessage({ ...msg, id }, transfer); }); const initCopy = wasmBytes.slice(0); await call({ type: 'init', wasmBytes: initCopy.buffer }, [initCopy.buffer]); const gain = audioCtx.createGain(); gain.gain.value = 2.0; const comp = audioCtx.createDynamicsCompressor(); comp.threshold.value = -6; comp.knee.value = 12; comp.ratio.value = 8; comp.attack.value = 0.002; comp.release.value = 0.12; gain.connect(comp); comp.connect(audioCtx.destination); let activeSource = null; let activePlayback = null; let activeSeq = 0; const scratchArtic = new Float32Array(17); // 再生位置に対応するフレームを探す(タイムラインは等間隔だが時刻検索で正確に引く) function frameAt(elapsed) { if (!activePlayback) return null; const { frames, frameFloats, frameCount } = activePlayback; if (frameCount <= 0) return null; let idx = Math.min(frameCount - 1, Math.floor((elapsed / activePlayback.durationSec) * frameCount)); while (idx + 1 < frameCount && frames[(idx + 1) * frameFloats] <= elapsed) idx++; while (idx > 0 && frames[idx * frameFloats] > elapsed) idx--; return { frames, off: idx * frameFloats }; } const api = { gain, ready: true, // 現在の再生テレメトリ { playing, outRms, voicing, artic }。体の selfEff // (自声 RMS の帰還)に使うほか、顔・計器を駆動したいホスト向けの公開面。 // artic は内部バッファの使い回し(次の呼び出しで上書きされる)。 playbackTelemetry() { if (!activePlayback) return { playing: false, outRms: 0, voicing: 0, artic: null }; const elapsed = audioCtx.currentTime - activePlayback.startCtxTime; if (elapsed < 0) return { playing: true, outRms: 0, voicing: 0, artic: null }; if (elapsed >= activePlayback.durationSec) { activePlayback = null; return { playing: false, outRms: 0, voicing: 0, artic: null }; } const f = frameAt(elapsed); if (!f) return { playing: true, outRms: 0, voicing: 0, artic: null }; for (let k = 0; k < 17; k++) scratchArtic[k] = f.frames[f.off + 3 + k]; return { playing: true, outRms: f.frames[f.off + 1], voicing: f.frames[f.off + 2], artic: scratchArtic, }; }, async prepare(records, count, f0, endSec) { const copy = records.slice(0, count * GESTURE_RECORD); return call( { type: 'render', records: copy.buffer, count, f0, endSec }, [copy.buffer], ); }, async playPrepared(rendered, label = '') { if (audioCtx.state !== 'running') { hooks.onWarn && hooks.onWarn(`オーディオ状態が ${audioCtx.state} のため再開を試行`); try { await audioCtx.resume(); } catch {} } const pcm = new Float32Array(rendered.pcm); const frames = new Float32Array(rendered.frames); if (activeSource) { try { activeSource.stop(); } catch {} activeSource = null; } const mySeq = ++activeSeq; const buf = audioCtx.createBuffer(1, pcm.length, rendered.sampleRate); buf.getChannelData(0).set(pcm); const src = audioCtx.createBufferSource(); src.buffer = buf; src.connect(gain); const startCtxTime = audioCtx.currentTime; activeSource = src; activePlayback = { startCtxTime, durationSec: rendered.durationSec, frames, frameFloats: rendered.frameFloats, frameCount: rendered.frameCount, }; src.onended = () => { if (activeSource === src) { activeSource = null; activePlayback = null; } }; src.start(); if (rendered.peakRms < 0.002) { hooks.onWarn && hooks.onWarn(`口診断: 発話「${label}」の合成出力が無音 (peakRms=${rendered.peakRms.toFixed(4)})`); } setTimeout(() => { if (activeSeq !== mySeq) return; const adv = audioCtx.currentTime - startCtxTime; if (adv <= 0.001) { hooks.onWarn && hooks.onWarn(`口診断: 発話「${label}」でAudioContext時刻が進んでいません (state=${audioCtx.state}, adv=${adv.toFixed(4)})`); } }, 260); return { durationSec: rendered.durationSec, peakRms: rendered.peakRms, renderMs: rendered.renderMs }; }, // 全リソース解放:再生停止、保留中の呼び出しの破棄、ワーカー終了、ノード切断。 close() { if (activeSource) { try { activeSource.stop(); } catch {} activeSource = null; } activePlayback = null; const err = new Error('mouth player closed'); for (const p of pending.values()) p.reject(err); pending.clear(); try { worker.terminate(); } catch {} try { gain.disconnect(); } catch {} try { comp.disconnect(); } catch {} }, }; hooks.onReady && hooks.onReady(); return api; } // ブラウザ用(旧 AudioWorklet 経路互換)。 export async function createMouthEngine(audioCtx, wasmBytes, workletText, hooks = {}) { const blob = new Blob([workletText], { type: 'text/javascript' }); const url = URL.createObjectURL(blob); await audioCtx.audioWorklet.addModule(url); const node = new AudioWorkletNode(audioCtx, 'chimera-engine', { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2], processorOptions: { wasmBytes: wasmBytes.slice(0) }, }); // モバイルスピーカー+AEC 環境で小音量の相槌が埋もれないよう、適度なゲイン+リミッタを通す const gain = audioCtx.createGain(); gain.gain.value = 1.9; const comp = audioCtx.createDynamicsCompressor(); comp.threshold.value = -6; comp.knee.value = 12; comp.ratio.value = 8; comp.attack.value = 0.002; comp.release.value = 0.12; node.connect(gain); gain.connect(comp); comp.connect(audioCtx.destination); let seq = 0; let pendingSpeech = null; let activeSeq = 0; let peakRmsForSeq = 0; let scheduledSeenForSeq = false; let watchdogTimer = null; const sendSchedule = (records, count, f0, label = '') => { if (audioCtx.state !== 'running') { hooks.onWarn && hooks.onWarn(`オーディオ状態が ${audioCtx.state} のため再開を試行`); audioCtx.resume().catch(() => {}); } const mySeq = ++seq; activeSeq = mySeq; peakRmsForSeq = 0; scheduledSeenForSeq = false; const copy = records.slice(0, count * GESTURE_RECORD); node.port.postMessage({ type: 'schedule', seq: mySeq, records: copy.buffer, count, f0 }, [copy.buffer]); clearTimeout(watchdogTimer); watchdogTimer = setTimeout(() => { if (activeSeq !== mySeq) return; if (!scheduledSeenForSeq || peakRmsForSeq < 0.002) { hooks.onWarn && hooks.onWarn( `口診断: 発話「${label}」で無音/未スケジュール検出 (state=${audioCtx.state}, scheduled=${scheduledSeenForSeq}, peakRms=${peakRmsForSeq.toFixed(4)})` ); } }, 360); }; const api = { node, gain, ready: false, // 全リソース解放:監視タイマ停止、Worklet ノードとゲイン段の切断、ポート閉鎖。 close() { clearTimeout(watchdogTimer); try { node.disconnect(); } catch {} try { gain.disconnect(); } catch {} try { comp.disconnect(); } catch {} try { node.port.close(); } catch {} }, speak(records, count, f0, label = '') { if (!api.ready) { pendingSpeech = { records: records.slice(0, count * GESTURE_RECORD), count, f0, label }; return; } sendSchedule(records, count, f0, label); }, }; node.port.onmessage = (ev) => { const m = ev.data; if (m.type === 'ready') { api.ready = true; hooks.onReady && hooks.onReady(); if (pendingSpeech) { const p = pendingSpeech; pendingSpeech = null; sendSchedule(p.records, p.count, p.f0, p.label); } } else if (m.type === 'scheduled') { if (m.seq === activeSeq) scheduledSeenForSeq = true; } else if (m.type === 'telemetry') { if (m.seq === activeSeq && m.outRms > peakRmsForSeq) peakRmsForSeq = m.outRms; hooks.onTelemetry && hooks.onTelemetry(m); } else if (m.type === 'error') { hooks.onError && hooks.onError(m.message); } }; return api; }