Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor
Drive desktop avatar lip sync from the microphone
shinshin8676e863b4aba3
diff --git a/native/Cargo.lock b/native/Cargo.lockindex 8f01b9e..9d90aff 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -37,6 +37,28 @@ dependencies = ["zerocopy",]+[[package]]+name = "alsa"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d"+dependencies = [+ "alsa-sys",+ "bitflags 2.13.2",+ "cfg-if",+ "libc",+]++[[package]]+name = "alsa-sys"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04"+dependencies = [+ "libc",+ "pkg-config",+]+[[package]]name = "android-activity"version = "0.6.1"@@ -352,6 +374,50 @@ dependencies = ["libc",]+[[package]]+name = "coreaudio-rs"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "objc2-audio-toolbox",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+]++[[package]]+name = "cpal"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1"+dependencies = [+ "alsa",+ "block2 0.6.2",+ "coreaudio-rs",+ "dasp_sample",+ "jni",+ "js-sys",+ "libc",+ "mach2",+ "ndk",+ "ndk-context",+ "num-derive",+ "num-traits",+ "objc2 0.6.5",+ "objc2-audio-toolbox",+ "objc2-avf-audio",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+ "web-sys",+ "windows 0.62.2",+ "windows-core 0.62.2",+]+[[package]]name = "crc32fast"version = "1.5.3"@@ -388,6 +454,12 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "dasp_sample"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"+[[package]]name = "derive_arbitrary"version = "1.5.0"@@ -666,7 +738,7 @@ dependencies = ["log","presser","thiserror 1.0.69",- "windows",+ "windows 0.58.0",][[package]]@@ -927,6 +999,12 @@ version = "0.4.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+[[package]]+name = "mach2"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b"+[[package]]name = "malloc_buf"version = "0.0.6"@@ -967,6 +1045,7 @@ name = "mesh-avatar-desktop"version = "0.1.0"dependencies = ["anyhow",+ "cpal","dirs","mesh-avatar-core","mesh-avatar-wgpu",@@ -1107,6 +1186,17 @@ dependencies = ["jni-sys 0.3.1",]+[[package]]+name = "num-derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -1202,6 +1292,32 @@ dependencies = ["objc2-foundation 0.3.2",]+[[package]]+name = "objc2-audio-toolbox"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "objc2 0.6.5",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-avf-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+ "objc2-foundation 0.3.2",+]+[[package]]name = "objc2-cloud-kit"version = "0.2.2"@@ -1226,6 +1342,29 @@ dependencies = ["objc2-foundation 0.2.2",]+[[package]]+name = "objc2-core-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"+dependencies = [+ "dispatch2",+ "objc2 0.6.5",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation 0.3.2",+]++[[package]]+name = "objc2-core-audio-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"+dependencies = [+ "bitflags 2.13.2",+ "objc2 0.6.5",+]+[[package]]name = "objc2-core-data"version = "0.2.2"@@ -1245,7 +1384,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = ["bitflags 2.13.2",+ "block2 0.6.2","dispatch2",+ "libc","objc2 0.6.5",]@@ -1310,6 +1451,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = ["bitflags 2.13.2","block2 0.6.2",+ "libc","objc2 0.6.5","objc2-core-foundation",]@@ -2490,8 +2632,8 @@ dependencies = ["wasm-bindgen","web-sys","wgpu-types",- "windows",- "windows-core",+ "windows 0.58.0",+ "windows-core 0.58.0",][[package]]@@ -2523,23 +2665,68 @@ version = "0.58.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"dependencies = [- "windows-core",+ "windows-core 0.58.0","windows-targets",]+[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core 0.62.2",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core 0.62.2",+]+[[package]]name = "windows-core"version = "0.58.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"dependencies = [- "windows-implement",- "windows-interface",- "windows-result",- "windows-strings",+ "windows-implement 0.58.0",+ "windows-interface 0.58.0",+ "windows-result 0.2.0",+ "windows-strings 0.1.0","windows-targets",]+[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement 0.60.2",+ "windows-interface 0.59.3",+ "windows-link",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core 0.62.2",+ "windows-link",+ "windows-threading",+]+[[package]]name = "windows-implement"version = "0.58.0"@@ -2551,6 +2738,17 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "windows-interface"version = "0.58.0"@@ -2562,12 +2760,33 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core 0.62.2",+ "windows-link",+]+[[package]]name = "windows-result"version = "0.2.0"@@ -2577,16 +2796,34 @@ dependencies = ["windows-targets",]+[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]+[[package]]name = "windows-strings"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"dependencies = [- "windows-result",+ "windows-result 0.2.0","windows-targets",]+[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]+[[package]]name = "windows-sys"version = "0.52.0"@@ -2630,6 +2867,15 @@ dependencies = ["windows_x86_64_msvc",]+[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]+[[package]]name = "windows_aarch64_gnullvm"version = "0.52.6"diff --git a/native/README.ja.md b/native/README.ja.mdindex d74bca9..34c0062 100644--- a/native/README.ja.md+++ b/native/README.ja.md@@ -85,6 +85,24 @@ macOSでは、システムのステータスバーにある単色のアバター待機中の動き、まばたき、呼吸、ときどき入るモーションは自動で再生されます。描画はディスプレイの表示レートに合わせます。リサイズやモニターの拡大率の変更に合わせて実際の描画サイズを更新し、処理が止まったりスリープから復帰したりした後のアニメーションの時間刻みは 0.05 秒までに抑えます。+## マイクで口を動かす(macOS)++アプリメニューとステータスメニューの両方に **Microphone** があります。起動時はオフです。+**Enable Microphone** をオンにすると入力音量で口を動かし、**Input Device** でシステムの既定入力かマイク名を選べます。+**Sensitivity** はLow・Normal(初期値)・Highの3段階です。小さい声に反応しない場合はHigh、環境音で口が開く場合はLowを試してください。+ノイズゲート、平滑化、短い終了待ち時間で、小さい入力による細かい開閉を抑えます。++初めてオンにすると、macOSがマイクへのアクセス許可を求めます。この実行ファイルはアプリバンドルではないため、起動に使ったターミナルアプリへの許可として扱われます。+拒否した場合は **システム設定 → プライバシーとセキュリティ → マイク** でそのターミナルを許可し、もう一度オンにしてください。++音声は音量の計算にだけ使い、録音やアップロードはしません。システムの再生音を取り込む機能ではありません。+アバターを隠したり切り替えたりしても入力は続くため、使い終わったらどちらかのメニューからオフにしてください。+入力デバイス、感度、オン・オフの状態は次回起動時に引き継ぎません。`K` キーのかなデモを使う前にもオフにしてください。+オフにすると、マイクによる口の操作を止めて通常のアニメーションへ戻ります。++デバイスの切断、ストリームエラー、入力コールバックの停止を検知するとオフになり、メニューの **Off:** に続けて理由を表示します。+自動では再開しません。使える入力を選んで再びオンにしてください。デバイス一覧は **Input Device → Refresh Devices** でも更新できます。+## PNG を書き出す```sh@@ -119,6 +137,6 @@ dump は、Rust 側に埋め込んだモーションデータが JavaScript の透明な描画面を使えない環境では、アプリは終了します。- メニューバー、ステータスバーのアイコン、Open Avatar ダイアログは macOS 専用です。実行ファイルには、アプリバンドルなしで「Mesh Avatar」という名前を埋め込んでいます。macOS がほかの場所で表示する名前は、起動のしかたによって変わることがあります。-- デスクトップでの入力は上の操作に限られます。カメラトラッキング、マイク入力、音声再生、ライティングには対応していません。+- マイク入力は現在macOS専用です。カメラトラッキング、システム音声の取り込み、音声再生、ライティングには対応していません。- デスクトップ版は Cargo でビルドする実行ファイルで、インストーラー、署名済みアプリバンドル、グローバルショートカットはありません。- GPU のラスタライズとアンチエイリアスは Chromium とわずかに異なることがあります。ほぼ透明な画像の縁を調べるときは、プリマルチプライド済みの色で比較してください。diff --git a/native/README.md b/native/README.mdindex 226e5ff..2df4bcb 100644--- a/native/README.md+++ b/native/README.md@@ -110,6 +110,31 @@ Rendering follows the display's presentation rate. Resizing and monitor scalechanges update the physical render size; animation time steps are capped at0.05 seconds after a stall or sleep.+## Microphone lip sync (macOS)++The app menu and status menu both have a **Microphone** submenu. Capture is off+at startup. Choose **Enable Microphone** to drive the mouth from input volume;+**Input Device** selects System Default or a named microphone. **Sensitivity**+offers Low, Normal (default), and High. Try High for a quiet voice or Low if+background noise opens the mouth. The noise gate, smoothing and release hold+reduce rapid opening and closing around quiet input.++On first enable, macOS asks for microphone permission. With this unbundled+executable, permission is attributed to the terminal app used to launch it.+Allow that terminal in **System Settings → Privacy & Security → Microphone**+if permission was denied, then enable the microphone again.++Only input levels are used; audio is not recorded or uploaded. This feature does+not capture system playback. Capture stays enabled when the avatar is hidden or+switched. Turn it off from either menu when finished; device, sensitivity and+enabled state are not saved across launches. Disable it before using the `K`+kana demo. Turning it off stops driving the mouth and returns to normal animation.++If a device disconnects, the stream fails, or callbacks stop arriving, the+microphone turns off and the submenu shows **Off:** followed by a reason.+It does not restart automatically. Select an available input and enable it again;+**Input Device → Refresh Devices** refreshes the device list.+## Render a PNG```sh@@ -151,8 +176,8 @@ Metal backend on macOS, and `--dpr=2` checks equal physical sizes at HiDPI.- The native menu bar, status-bar icon and Open Avatar dialog are macOS-only. The executableembeds the name “Mesh Avatar” without an app bundle; the name shown elsewhereby macOS can depend on how it was launched.-- Desktop input is limited to the controls above. Camera tracking, microphone- input, audio playback and lighting are not included.+- Microphone capture is currently macOS-only. Camera tracking, system-audio+ capture, audio playback and lighting are not included.- The desktop is a Cargo-built executable, without an installer, signed appbundle or global keyboard shortcuts.- GPU rasterization and antialiasing can differ slightly from Chromium. Comparediff --git a/native/README.zh.md b/native/README.zh.mdindex b188642..92c89ec 100644--- a/native/README.zh.md+++ b/native/README.zh.md@@ -85,6 +85,24 @@ native/target/release/mesh-avatar-desktop /path/to/project待机动作、眨眼、呼吸和不定时的动作会自动播放。渲染频率跟随显示器的刷新节奏。窗口尺寸或显示器缩放比例变化时会更新实际渲染尺寸;在卡顿或从睡眠恢复后,动画的时间步长上限为 0.05 秒。+## 麦克风口型同步(macOS)++应用菜单和状态菜单都提供 **Microphone** 子菜单,启动时默认关闭。+启用 **Enable Microphone** 后,输入音量会驱动嘴部动作;**Input Device** 可选择系统默认输入或指定的麦克风。+**Sensitivity** 提供Low、Normal(默认)和High三个级别。声音较小时可试用High,环境噪声导致嘴部动作时可试用Low。+噪声门、平滑处理和短暂的结束保持可减少低音量附近的频繁开合。++首次启用时,macOS会请求麦克风权限。由于这是未打包的可执行文件,权限归属于启动它的终端应用。+如果曾拒绝,请在 **系统设置 → 隐私与安全性 → 麦克风** 中允许该终端,然后重新启用麦克风。++程序只使用输入音量,不录音、不上传音频,也不采集系统播放的声音。+隐藏或切换虚拟形象后仍会继续输入;使用完毕后请从任一菜单关闭。+设备选择、灵敏度和启用状态不会保存到下次启动。使用 `K` 键的假名演示前也请先关闭麦克风。+关闭后会停止麦克风对嘴部的控制,恢复正常动画。++设备断开、流错误或输入回调停止时,麦克风会关闭,并在子菜单的 **Off:** 后显示原因,不会自动重启。+选择可用输入后重新启用即可;**Input Device → Refresh Devices** 可刷新设备列表。+## 渲染 PNG```sh@@ -119,6 +137,6 @@ dump 会检查嵌入的动作数据是否与 JavaScript 源码一致。如果无法使用透明绘制表面,程序会退出。- 原生菜单栏、状态栏图标和 Open Avatar 对话框仅支持 macOS。可执行文件在没有应用包的情况下嵌入了名称“Mesh Avatar”;macOS 在其他位置显示的名称可能取决于启动方式。-- 桌面端的输入仅限上述操作。不包含摄像头追踪、麦克风输入、音频播放和光照。+- 麦克风输入目前仅支持macOS。不包含摄像头追踪、系统音频采集、音频播放和光照。- 桌面程序是用 Cargo 构建的可执行文件,没有安装程序、已签名的应用包或全局快捷键。- GPU 光栅化和抗锯齿可能与 Chromium 略有差异。检查接近透明的图像边缘时,请比较预乘后的颜色。diff --git a/native/apps/mesh-avatar-desktop/Cargo.toml b/native/apps/mesh-avatar-desktop/Cargo.tomlindex fa608a4..d2eb3c5 100644--- a/native/apps/mesh-avatar-desktop/Cargo.toml+++ b/native/apps/mesh-avatar-desktop/Cargo.toml@@ -17,6 +17,7 @@ serde.workspace = truedirs = "6"[target.'cfg(target_os = "macos")'.dependencies]+cpal = { version = "0.18.2", default-features = false }muda = { version = "0.19.3", default-features = false }tray-icon = { version = "0.24.2", default-features = false }rfd = { version = "0.17", default-features = false }diff --git a/native/apps/mesh-avatar-desktop/src/app-info.plist b/native/apps/mesh-avatar-desktop/src/app-info.plistindex 06c5a71..a1ced6d 100644--- a/native/apps/mesh-avatar-desktop/src/app-info.plist+++ b/native/apps/mesh-avatar-desktop/src/app-info.plist@@ -5,5 +5,6 @@<key>CFBundleName</key><string>Mesh Avatar</string><key>CFBundleDisplayName</key><string>Mesh Avatar</string><key>NSHighResolutionCapable</key><true/>+ <key>NSMicrophoneUsageDescription</key><string>Mesh Avatar uses microphone levels to animate the avatar mouth. Audio is not recorded or uploaded.</string></dict></plist>diff --git a/native/apps/mesh-avatar-desktop/src/audio_level.rs b/native/apps/mesh-avatar-desktop/src/audio_level.rsnew file mode 100644index 0000000..13ea30c--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/audio_level.rs@@ -0,0 +1,246 @@+//! Allocation-free buffer reduction and a lock-free latest-value handoff.+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};+use std::time::{Duration, Instant};++pub fn rms(samples: impl IntoIterator<Item = f32>) -> f32 {+ let mut power = 0.0_f64;+ let mut count = 0_u64;+ for sample in samples {+ let value = if sample.is_finite() {+ sample.clamp(-1.0, 1.0)+ } else {+ 0.0+ };+ power += f64::from(value).powi(2);+ count += 1;+ }+ if count == 0 {+ 0.0+ } else {+ (power / count as f64).sqrt() as f32+ }+}++#[derive(Default)]+pub struct InputLevel {+ level: AtomicU32,+ sequence: AtomicU64,+ pub failed: AtomicBool,+}+impl InputLevel {+ pub fn publish(&self, value: f32) {+ self.level.store(value.to_bits(), Ordering::Relaxed);+ self.sequence.fetch_add(1, Ordering::Release);+ }+ pub fn read(&self) -> (u64, f32) {+ let sequence = self.sequence.load(Ordering::Acquire);+ (sequence, f32::from_bits(self.level.load(Ordering::Relaxed)))+ }+}++pub struct InputHealth {+ sequence: u64,+ last_sample: Instant,+}+impl InputHealth {+ pub fn new(now: Instant) -> Self {+ Self {+ sequence: 0,+ last_sample: now,+ }+ }+ pub fn failure(+ &mut self,+ input: &InputLevel,+ now: Instant,+ connected: bool,+ ) -> Option<&'static str> {+ let sequence = input.read().0;+ if sequence != self.sequence {+ self.sequence = sequence;+ self.last_sample = now;+ }+ if !connected {+ Some("Input device disconnected")+ } else if input.failed.load(Ordering::Acquire) {+ Some("Input stream failed or device disconnected")+ } else if now.saturating_duration_since(self.last_sample) > Duration::from_secs(2) {+ Some("No microphone samples received")+ } else {+ None+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum Sensitivity {+ Low,+ #[default]+ Normal,+ High,+}+impl Sensitivity {+ pub const ALL: [Self; 3] = [Self::Low, Self::Normal, Self::High];+ pub fn name(self) -> &'static str {+ match self {+ Self::Low => "Low",+ Self::Normal => "Normal",+ Self::High => "High",+ }+ }+ fn db(self) -> f64 {+ match self {+ Self::Low => -6.0,+ Self::Normal => 0.0,+ Self::High => 12.0,+ }+ }+}+#[derive(Default)]+pub struct LevelMapper {+ level: f64,+ gate: bool,+ speaking: bool,+ hold: f64,+}+impl LevelMapper {+ pub fn update(&mut self, rms: f32, dt: f64, sensitivity: Sensitivity) -> (f64, bool) {+ let dt = if dt.is_finite() {+ dt.clamp(0.0, 0.1)+ } else {+ 0.0+ };+ let rms = if rms.is_finite() {+ f64::from(rms.clamp(0.0, 1.0))+ } else {+ 0.0+ };+ let db = 20.0 * rms.max(1e-6).log10() + sensitivity.db();+ if db >= -48.0 {+ self.gate = true;+ } else if db < -54.0 {+ self.gate = false;+ }+ let target = if self.gate {+ ((db + 54.0) / 39.0).clamp(0.0, 1.0)+ } else {+ 0.0+ };+ let tau = if target > self.level { 0.025 } else { 0.1 };+ self.level += (target - self.level) * (1.0 - (-dt / tau).exp());+ if target >= 0.15 || (self.speaking && target >= 0.07) {+ self.speaking = true;+ self.hold = 0.18;+ } else {+ self.hold = (self.hold - dt).max(0.0);+ if self.hold <= 1e-9 {+ self.speaking = false;+ }+ }+ (self.level.clamp(0.0, 1.0), self.speaking)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn silence_sine_antiphase_stereo_and_invalid_samples() {+ assert_eq!(rms([]), 0.0);+ assert_eq!(rms([0.0; 128]), 0.0);+ let sine = (0..480).map(|i| (std::f32::consts::TAU * i as f32 / 48.0).sin() * 0.5);+ assert!((rms(sine) - 0.5 / std::f32::consts::SQRT_2).abs() < 1e-6);+ assert!((rms([0.5, -0.5, 0.5, -0.5]) - 0.5).abs() < 1e-6);+ assert_eq!(rms([f32::NAN, f32::INFINITY]), 0.0);+ assert_eq!(rms([2.0, -2.0]), 1.0);+ }+ #[test]+ fn gate_smoothing_sensitivity_and_speaking_release() {+ let mut mapper = LevelMapper::default();+ for _ in 0..100 {+ assert_eq!(+ mapper.update(0.001, 0.01, Sensitivity::Normal),+ (0.0, false)+ );+ }+ let first = mapper.update(0.1, 0.01, Sensitivity::Normal);+ assert!(first.1 && first.0 > 0.0 && first.0 < 0.5);+ for _ in 0..20 {+ mapper.update(0.1, 0.01, Sensitivity::Normal);+ }+ assert!(mapper.level > first.0);+ for _ in 0..12 {+ assert!(mapper.update(0.0, 0.01, Sensitivity::Normal).1);+ }+ for _ in 0..10 {+ mapper.update(0.0, 0.01, Sensitivity::Normal);+ }+ assert!(!mapper.speaking);+ for _ in 0..100 {+ mapper.update(0.0, 0.01, Sensitivity::Normal);+ }+ assert!(mapper.level < 1e-5);+ let mut normal = LevelMapper::default();+ let mut high = LevelMapper::default();+ assert_eq!(normal.update(0.003, 0.1, Sensitivity::Normal), (0.0, false));+ assert!(high.update(0.003, 0.1, Sensitivity::High).1);+ }+ #[test]+ fn bounded_mapping_and_gate_hysteresis() {+ let mut mapper = LevelMapper::default();+ let db = |db: f32| 10_f32.powf(db / 20.0);+ assert_eq!(mapper.update(db(-51.0), 0.05, Sensitivity::Normal).0, 0.0);+ mapper.update(db(-47.0), 0.05, Sensitivity::Normal);+ assert!(mapper.gate);+ mapper.update(db(-51.0), 0.05, Sensitivity::Normal);+ assert!(mapper.gate);+ mapper.update(db(-55.0), 0.05, Sensitivity::Normal);+ assert!(!mapper.gate);+ for value in [f32::NAN, f32::INFINITY, -1.0, 0.0, 1.0, 100.0] {+ let (level, _) = mapper.update(value, 0.05, Sensitivity::High);+ assert!(level.is_finite() && (0.0..=1.0).contains(&level));+ }+ }+ #[test]+ fn silent_callbacks_are_live_and_old_stream_errors_are_isolated() {+ let old = InputLevel::default();+ let new = InputLevel::default();+ for _ in 0..100 {+ new.publish(rms([0.0; 64]));+ }+ assert_eq!(new.read(), (100, 0.0));+ old.failed.store(true, Ordering::Release);+ assert!(!new.failed.load(Ordering::Acquire));+ }+ #[test]+ fn stalled_callbacks_errors_and_device_removal_are_detected_without_hardware() {+ let input = InputLevel::default();+ let now = Instant::now();+ let mut health = InputHealth::new(now);+ assert!(health.failure(&input, now, true).is_none());+ assert_eq!(+ health.failure(&input, now + Duration::from_secs(3), true),+ Some("No microphone samples received")+ );+ input.publish(0.0);+ assert!(health+ .failure(&input, now + Duration::from_secs(4), true)+ .is_none());+ assert_eq!(+ health.failure(&input, now + Duration::from_secs(4), false),+ Some("Input device disconnected")+ );+ input.failed.store(true, Ordering::Release);+ assert!(health+ .failure(&input, now + Duration::from_secs(4), true)+ .unwrap()+ .contains("stream failed"));+ }+ #[test]+ #[cfg(target_os = "macos")]+ fn pcm_signed_full_scale_and_unsigned_silence_are_normalized() {+ use cpal::Sample;+ assert!((rms([i16::MIN, i16::MAX].map(|v| v.to_sample::<f32>())) - 1.0).abs() < 0.0001);+ assert_eq!(rms([32768_u16; 16].map(|v| v.to_sample::<f32>())), 0.0);+ }+}diff --git a/native/apps/mesh-avatar-desktop/src/main.rs b/native/apps/mesh-avatar-desktop/src/main.rsindex 9d48221..134fef4 100644--- a/native/apps/mesh-avatar-desktop/src/main.rs+++ b/native/apps/mesh-avatar-desktop/src/main.rs@@ -2,6 +2,8 @@ mod geometry;mod loading;mod menu;mod menu_model;+mod microphone;+mod microphone_menu;mod presentation;mod scaling;mod screens;@@ -588,6 +590,7 @@ enum UserEvent {Picked(Option<PathBuf>),AlertClosed,Loaded(Box<Loaded>),+ Microphone(microphone::Event),}struct App {avatar: Option<Avatar>,@@ -602,6 +605,8 @@ struct App {commands: Vec<menu::Command>,dialog_open: bool,settings: Settings,+ microphone: microphone::Microphone,+ mic_driving: bool,}impl App {fn observe_settings(&mut self, now: Instant, include_pending: bool) {@@ -727,6 +732,12 @@ impl App {scene.toggle_click_through();}}+ menu::Command::ToggleMicrophone => {+ self.microphone.set_enabled(!self.microphone.state.enabled)+ }+ menu::Command::MicrophoneDevice(device) => self.microphone.select(device),+ menu::Command::MicrophoneSensitivity(value) => self.microphone.sensitivity(value),+ menu::Command::RefreshMicrophones => self.microphone.refresh(),_ => {}}}@@ -759,6 +770,28 @@ impl App {Err(error) => self.load_error(&format!("{error:#}")),}}+ let mic_active = self.microphone.state.enabled && !self.microphone.state.starting;+ if let Some(scene) = &mut self.scene {+ if mic_active {+ if !self.mic_driving {+ scene.avatar.stop_lip_sync();+ }+ let (level, speaking) = self.microphone.level(Instant::now());+ scene.avatar.set_speaking(speaking);+ scene.avatar.set_voice_level(level);+ } else if self.mic_driving {+ scene.avatar.set_voice_level(0.0);+ scene.avatar.set_speaking(false);+ }+ }+ self.mic_driving = mic_active;+ if let Some(menu) = &mut self.menu {+ if let Some(state) = self.microphone.take_state() {+ if let Err(error) = menu.update_microphone(&state) {+ eprintln!("Could not update microphone menu: {error:#}");+ }+ }+ }if let Some(scene) = &mut self.scene {scene.service()?;}@@ -839,6 +872,8 @@ impl ApplicationHandler<UserEvent> for App {self.commands.push(menu::Command::Open);} else if command && !event.repeat && key == KeyCode::KeyR {self.commands.push(menu::Command::Reload);+ } else if key == KeyCode::KeyK && self.microphone.state.enabled {+ eprintln!("Disable the microphone before running the kana demo");} else {scene.key(event_loop, key, event.repeat);}@@ -896,9 +931,11 @@ impl ApplicationHandler<UserEvent> for App {self.pending_load = Some(*loaded);}}+ UserEvent::Microphone(event) => self.microphone.event(event),}}fn exiting(&mut self, _: &ActiveEventLoop) {+ self.microphone.set_enabled(false);let now = Instant::now();self.observe_settings(now, true);if let Err(error) = self.settings.flush(now, true) {@@ -929,6 +966,10 @@ fn run() -> Result<()> {let event_loop = builder.build()?;event_loop.set_control_flow(ControlFlow::Wait);let proxy = event_loop.create_proxy();+ let mic_notify = proxy.clone();+ let microphone = microphone::Microphone::new(move |event| {+ let _ = mic_notify.send_event(UserEvent::Microphone(event));+ })?;let notify = proxy.clone();let loader = Loader::new(move |loaded| {let _ = notify.send_event(UserEvent::Loaded(Box::new(loaded)));@@ -951,6 +992,8 @@ fn run() -> Result<()> {commands: Vec::new(),dialog_open: false,settings: Settings::load(Settings::config_file()),+ microphone,+ mic_driving: false,};event_loop.run_app(&mut app)?;if let Some(error) = app.error {@@ -992,3 +1035,4 @@ mod tests {assert!((1254.0 * scale + offset - 372.0).abs() < 1e-3);}}+mod audio_level;diff --git a/native/apps/mesh-avatar-desktop/src/menu.rs b/native/apps/mesh-avatar-desktop/src/menu.rsindex 1febd87..c9e5c7d 100644--- a/native/apps/mesh-avatar-desktop/src/menu.rs+++ b/native/apps/mesh-avatar-desktop/src/menu.rs@@ -14,6 +14,10 @@ pub enum Command {Expression(String),ToggleVisible,ToggleClickThrough,+ ToggleMicrophone,+ MicrophoneDevice(Option<String>),+ MicrophoneSensitivity(crate::audio_level::Sensitivity),+ RefreshMicrophones,}#[cfg(target_os = "macos")]@@ -38,6 +42,7 @@ mod platform {expressions: Submenu,avatar_model: AvatarMenu,status: Option<crate::status_bar::StatusBar>,+ microphone: crate::microphone_menu::MicrophoneMenu,}impl AppMenu {pub fn install(proxy: EventLoopProxy<UserEvent>, paths: &[PathBuf]) -> Result<Self> {@@ -87,14 +92,17 @@ mod platform {let motions = Submenu::new("Motion", true);let expressions = Submenu::new("Expression", true);let avatar = Submenu::with_items("Avatar", true, &[&motions, &expressions])?;- root.append_items(&[&app, &file, &avatar, &edit])?;- let status = match crate::status_bar::StatusBar::new(&recent, &open, &quit) {- Ok(status) => Some(status),- Err(error) => {- eprintln!("Could not create status-bar icon: {error:#}");- None- }- };+ let microphone = crate::microphone_menu::MicrophoneMenu::new()?;+ root.append_items(&[&app, &file, &avatar, µphone.submenu, &edit])?;+ let status =+ match crate::status_bar::StatusBar::new(&recent, &open, &quit, µphone.submenu)+ {+ Ok(status) => Some(status),+ Err(error) => {+ eprintln!("Could not create status-bar icon: {error:#}");+ None+ }+ };let mut menu = Self {_root: root,recent,@@ -103,6 +111,7 @@ mod platform {expressions,avatar_model: AvatarMenu::new(&[]),status,+ microphone,};menu.set_recent(paths)?;MenuEvent::set_event_handler(Some(move |event: MenuEvent| {@@ -142,7 +151,8 @@ mod platform {.iter().find(|(item, _)| item.id().as_ref() == id).map(|(_, path)| Command::Recent(path.clone()))- .or_else(|| self.avatar_model.command(id)),+ .or_else(|| self.avatar_model.command(id))+ .or_else(|| self.microphone.command(id)),}}pub fn set_avatar(&mut self, model: AvatarMenu) -> Result<()> {@@ -171,6 +181,9 @@ mod platform {status.update(state);}}+ pub fn update_microphone(&mut self, state: &crate::microphone::State) -> Result<()> {+ self.microphone.update(state)+ }}pub fn open(@@ -231,6 +244,9 @@ mod platform {Ok(())}pub fn update_controls(&mut self, _: crate::window_controls::WindowControls) {}+ pub fn update_microphone(&mut self, _: &crate::microphone::State) -> Result<()> {+ Ok(())+ }}pub fn open(_: EventLoopProxy<UserEvent>, _: &Window, _: Option<&Path>) -> Result<()> {anyhow::bail!("the native Open Avatar dialog is currently available only on macOS")diff --git a/native/apps/mesh-avatar-desktop/src/microphone.rs b/native/apps/mesh-avatar-desktop/src/microphone.rsnew file mode 100644index 0000000..340d6a2--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/microphone.rs@@ -0,0 +1,444 @@+//! Microphone control runs outside the render and real-time callback threads.+use crate::audio_level::{InputLevel, LevelMapper, Sensitivity};+use anyhow::{Context, Result};+use std::sync::atomic::{AtomicU64, Ordering};+use std::{+ sync::{mpsc, Arc},+ time::Instant,+};++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct InputDevice {+ pub id: String,+ pub name: String,+}+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct State {+ pub enabled: bool,+ pub starting: bool,+ pub devices: Vec<InputDevice>,+ pub selected: Option<String>,+ pub sensitivity: Sensitivity,+ pub status: String,+}+impl Default for State {+ fn default() -> Self {+ Self {+ enabled: false,+ starting: false,+ devices: vec![],+ selected: None,+ sensitivity: Sensitivity::Normal,+ status: "Off".into(),+ }+ }+}+pub enum Event {+ Devices(Vec<InputDevice>),+ Started {+ generation: u64,+ name: String,+ input: Arc<InputLevel>,+ },+ Stopped {+ generation: u64,+ error: Option<String>,+ },+ Fatal(String),+}+enum Request {+ Start(u64, Option<String>),+ Stop(u64),+ Refresh,+}+pub struct Microphone {+ requests: mpsc::Sender<Request>,+ pub state: State,+ generation: u64,+ generation_signal: Arc<AtomicU64>,+ input: Option<Arc<InputLevel>>,+ mapper: LevelMapper,+ last_tick: Instant,+ dirty: bool,+}+impl Microphone {+ pub fn new(notify: impl Fn(Event) + Send + 'static) -> Result<Self> {+ let (requests, receiver) = mpsc::channel();+ let generation_signal = Arc::new(AtomicU64::new(0));+ let worker_generation = generation_signal.clone();+ std::thread::Builder::new()+ .name("microphone control".into())+ .spawn(move || {+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ backend::run(receiver, ¬ify, &worker_generation)+ }));+ if result.is_err() {+ notify(Event::Fatal(+ "Microphone backend stopped unexpectedly".into(),+ ));+ }+ })?;+ Ok(Self {+ requests,+ state: State::default(),+ generation: 0,+ generation_signal,+ input: None,+ mapper: LevelMapper::default(),+ last_tick: Instant::now(),+ dirty: true,+ })+ }+ pub fn set_enabled(&mut self, enabled: bool) {+ self.generation = self.generation.wrapping_add(1);+ self.generation_signal+ .store(self.generation, Ordering::Release);+ self.input = None;+ self.mapper = LevelMapper::default();+ self.state.enabled = enabled;+ self.state.starting = enabled;+ self.state.status = if enabled { "Starting…" } else { "Off" }.into();+ let request = if enabled {+ Request::Start(self.generation, self.state.selected.clone())+ } else {+ Request::Stop(self.generation)+ };+ if self.requests.send(request).is_err() {+ self.fail("Microphone control is unavailable".into());+ }+ self.dirty = true;+ }+ pub fn select(&mut self, device: Option<String>) {+ if self.state.selected == device {+ self.dirty = true;+ return;+ }+ self.state.selected = device;+ self.dirty = true;+ if self.state.enabled {+ self.set_enabled(true);+ }+ }+ pub fn sensitivity(&mut self, sensitivity: Sensitivity) {+ self.state.sensitivity = sensitivity;+ self.dirty = true;+ }+ pub fn refresh(&mut self) {+ if self.requests.send(Request::Refresh).is_err() {+ self.fail("Microphone control is unavailable".into());+ }+ }+ fn fail(&mut self, message: String) {+ eprintln!("Microphone off: {message}");+ self.state.enabled = false;+ self.state.starting = false;+ self.state.status = format!("Off: {message}");+ self.input = None;+ self.mapper = LevelMapper::default();+ self.dirty = true;+ }+ pub fn event(&mut self, event: Event) {+ match event {+ Event::Devices(devices) => {+ if devices != self.state.devices {+ self.state.devices = devices;+ self.dirty = true;+ }+ }+ Event::Started {+ generation,+ name,+ input,+ } if generation == self.generation && self.state.enabled => {+ self.input = Some(input);+ self.state.starting = false;+ self.state.status = format!("On: {name}");+ self.dirty = true;+ }+ Event::Stopped { generation, error } if generation == self.generation => {+ if let Some(message) = error {+ self.fail(message);+ } else {+ self.state.enabled = false;+ self.state.starting = false;+ self.state.status = "Off".into();+ self.input = None;+ self.dirty = true;+ }+ }+ Event::Fatal(message) => self.fail(message),+ _ => {}+ }+ }+ pub fn take_state(&mut self) -> Option<State> {+ std::mem::take(&mut self.dirty).then(|| self.state.clone())+ }+ pub fn level(&mut self, now: Instant) -> (f64, bool) {+ let dt = now.saturating_duration_since(self.last_tick).as_secs_f64();+ self.last_tick = now;+ match &self.input {+ Some(input) if self.state.enabled => {+ self.mapper+ .update(input.read().1, dt, self.state.sensitivity)+ }+ _ => (0.0, false),+ }+ }+}++#[cfg(target_os = "macos")]+mod backend {+ use super::*;+ use crate::audio_level::{rms, InputHealth};+ use cpal::{+ traits::{DeviceTrait, HostTrait, StreamTrait},+ FromSample, SampleFormat, SizedSample,+ };+ use std::{sync::atomic::Ordering, time::Duration};++ fn devices(host: &cpal::Host) -> Result<Vec<InputDevice>> {+ Ok(host+ .input_devices()?+ .filter_map(|device| {+ Some(InputDevice {+ id: device.id().ok()?.to_string(),+ name: device.to_string(),+ })+ })+ .collect())+ }+ fn typed_stream<T: SizedSample>(+ device: &cpal::Device,+ config: cpal::StreamConfig,+ input: Arc<InputLevel>,+ ) -> Result<cpal::Stream>+ where+ f32: FromSample<T>,+ {+ let failed = input.clone();+ Ok(device.build_input_stream(+ config,+ move |data: &[T], _| {+ if !data.is_empty() {+ input.publish(rms(data.iter().map(|sample| sample.to_sample::<f32>())));+ }+ },+ move |_| {+ failed.failed.store(true, Ordering::Release);+ },+ None,+ )?)+ }+ fn start(+ host: &cpal::Host,+ selected: Option<&str>,+ input: Arc<InputLevel>,+ generation: u64,+ latest: &AtomicU64,+ ) -> Result<(cpal::Stream, String, String)> {+ let device = if let Some(id) = selected {+ host.device_by_id(&id.parse()?)+ } else {+ host.default_input_device()+ }+ .context("No selected microphone is available")?;+ let config = device.default_input_config()?;+ let format = config.sample_format();+ let config = config.config();+ macro_rules! stream {+ ($ty:ty) => {+ typed_stream::<$ty>(&device, config, input)+ };+ }+ let stream = match format {+ SampleFormat::F32 => stream!(f32),+ SampleFormat::F64 => stream!(f64),+ SampleFormat::I8 => stream!(i8),+ SampleFormat::I16 => stream!(i16),+ SampleFormat::I24 => stream!(cpal::I24),+ SampleFormat::I32 => stream!(i32),+ SampleFormat::I64 => stream!(i64),+ SampleFormat::U8 => stream!(u8),+ SampleFormat::U16 => stream!(u16),+ SampleFormat::U24 => stream!(cpal::U24),+ SampleFormat::U32 => stream!(u32),+ SampleFormat::U64 => stream!(u64),+ _ => anyhow::bail!("Unsupported microphone sample format: {format}"),+ }?;+ // A permission prompt may have outlived a subsequent Off or device selection.+ anyhow::ensure!(+ latest.load(Ordering::Acquire) == generation,+ "Microphone request cancelled"+ );+ stream.play()?;+ anyhow::ensure!(+ latest.load(Ordering::Acquire) == generation,+ "Microphone request cancelled"+ );+ Ok((stream, device.id()?.to_string(), device.to_string()))+ }+ struct Active {+ _stream: cpal::Stream,+ id: String,+ generation: u64,+ input: Arc<InputLevel>,+ health: InputHealth,+ }+ pub fn run(receiver: mpsc::Receiver<Request>, notify: &impl Fn(Event), latest: &AtomicU64) {+ let host = cpal::default_host();+ let mut active: Option<Active> = None;+ let mut next_devices = Instant::now();+ loop {+ match receiver.recv_timeout(Duration::from_millis(25)) {+ Ok(Request::Start(generation, selected)) => {+ if latest.load(Ordering::Acquire) != generation {+ continue;+ }+ active = None;+ let input = Arc::new(InputLevel::default());+ match start(+ &host,+ selected.as_deref(),+ input.clone(),+ generation,+ latest,+ ) {+ Ok((stream, id, name)) => {+ active = Some(Active {+ _stream: stream,+ id,+ generation,+ input: input.clone(),+ health: InputHealth::new(Instant::now()),+ });+ notify(Event::Started {+ generation,+ name,+ input,+ });+ }+ Err(error) => notify(Event::Stopped {+ generation,+ error: Some(format!("{error:#}")),+ }),+ }+ }+ Ok(Request::Stop(generation)) => {+ active = None;+ notify(Event::Stopped {+ generation,+ error: None,+ });+ }+ Ok(Request::Refresh) => next_devices = Instant::now(),+ Err(mpsc::RecvTimeoutError::Disconnected) => return,+ Err(mpsc::RecvTimeoutError::Timeout) => {}+ }+ let now = Instant::now();+ let mut failure = None;+ if let Some(stream) = &mut active {+ failure = stream+ .health+ .failure(&stream.input, now, true)+ .map(str::to_string);+ }+ if now >= next_devices {+ match devices(&host) {+ Ok(devices) => {+ if active+ .as_ref()+ .is_some_and(|s| !devices.iter().any(|d| d.id == s.id))+ {+ failure = Some("Input device disconnected".into());+ }+ notify(Event::Devices(devices));+ }+ Err(error) => {+ if active.is_some() {+ failure = Some(format!("Input devices unavailable: {error}"));+ }+ }+ }+ next_devices = now + Duration::from_secs(if active.is_some() { 1 } else { 5 });+ }+ if let Some(error) = failure {+ if let Some(stream) = active.take() {+ let generation = stream.generation;+ drop(stream);+ notify(Event::Stopped {+ generation,+ error: Some(error),+ });+ }+ }+ }+ }+}+#[cfg(not(target_os = "macos"))]+mod backend {+ use super::*;+ pub fn run(receiver: mpsc::Receiver<Request>, notify: &impl Fn(Event), _: &AtomicU64) {+ for request in receiver {+ if let Request::Start(generation, _) = request {+ notify(Event::Stopped {+ generation,+ error: Some("Microphone input is currently macOS-only".into()),+ });+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn default_is_off_stale_start_cannot_enable_after_stop_and_errors_clear_level() {+ // Synthetic transport: this test never creates a host, stream or permission prompt.+ let (requests, _receiver) = mpsc::channel();+ let mut mic = Microphone {+ requests,+ state: State::default(),+ generation: 0,+ generation_signal: Arc::new(AtomicU64::new(0)),+ input: None,+ mapper: LevelMapper::default(),+ last_tick: Instant::now(),+ dirty: true,+ };+ assert!(!mic.state.enabled);+ mic.set_enabled(true);+ let generation = mic.generation;+ mic.set_enabled(false);+ mic.event(Event::Started {+ generation,+ name: "stale".into(),+ input: Arc::new(InputLevel::default()),+ });+ assert!(!mic.state.enabled && mic.input.is_none());+ mic.set_enabled(true);+ let input = Arc::new(InputLevel::default());+ input.publish(0.5);+ mic.event(Event::Started {+ generation: mic.generation,+ name: "synthetic".into(),+ input,+ });+ assert!(+ mic.level(Instant::now() + std::time::Duration::from_millis(50))+ .1+ );+ mic.event(Event::Stopped {+ generation,+ error: Some("stale stream error".into()),+ });+ assert!(mic.state.enabled);+ mic.event(Event::Stopped {+ generation: mic.generation,+ error: Some("unplugged".into()),+ });+ assert!(!mic.state.enabled);+ assert_eq!(mic.level(Instant::now()), (0.0, false));+ assert!(mic.state.status.contains("unplugged"));+ }+}diff --git a/native/apps/mesh-avatar-desktop/src/microphone_menu.rs b/native/apps/mesh-avatar-desktop/src/microphone_menu.rsnew file mode 100644index 0000000..1989a42--- /dev/null+++ b/native/apps/mesh-avatar-desktop/src/microphone_menu.rs@@ -0,0 +1,124 @@+//! One microphone submenu shared by the app menu and status icon.+#[cfg(target_os = "macos")]+pub struct MicrophoneMenu {+ pub submenu: muda::Submenu,+ toggle: muda::CheckMenuItem,+ status: muda::MenuItem,+ devices: muda::Submenu,+ choices: Vec<(muda::CheckMenuItem, Option<String>)>,+ sensitivities: Vec<(muda::CheckMenuItem, crate::audio_level::Sensitivity)>,+ state: Option<crate::microphone::State>,+}+#[cfg(target_os = "macos")]+impl MicrophoneMenu {+ pub fn new() -> anyhow::Result<Self> {+ use crate::audio_level::Sensitivity;+ use muda::{CheckMenuItem, MenuItem, Submenu};+ let submenu = Submenu::new("Microphone", true);+ let toggle = CheckMenuItem::with_id("mic-toggle", "Enable Microphone", true, false, None);+ let status = MenuItem::new("Off", false, None);+ let devices = Submenu::new("Input Device", true);+ let sensitivity = Submenu::new("Sensitivity", true);+ let mut sensitivities = vec![];+ for value in Sensitivity::ALL {+ let item = CheckMenuItem::with_id(+ format!("mic-sensitivity:{}", value.name()),+ value.name(),+ true,+ value == Sensitivity::Normal,+ None,+ );+ sensitivity.append(&item)?;+ sensitivities.push((item, value));+ }+ submenu.append_items(&[&toggle, &status, &devices, &sensitivity])?;+ let mut menu = Self {+ submenu,+ toggle,+ status,+ devices,+ choices: vec![],+ sensitivities,+ state: None,+ };+ menu.update(&crate::microphone::State::default())?;+ Ok(menu)+ }+ pub fn update(&mut self, state: &crate::microphone::State) -> anyhow::Result<()> {+ use muda::{CheckMenuItem, MenuItem, PredefinedMenuItem};+ self.toggle.set_checked(state.enabled);+ self.status.set_text(state.status.replace('&', "&&"));+ if self+ .state+ .as_ref()+ .is_none_or(|old| old.devices != state.devices || old.selected != state.selected)+ {+ while self.devices.remove_at(0).is_some() {}+ self.choices.clear();+ let default = CheckMenuItem::with_id(+ "mic-default",+ "System Default",+ true,+ state.selected.is_none(),+ None,+ );+ self.devices.append(&default)?;+ self.choices.push((default, None));+ for device in &state.devices {+ let item = CheckMenuItem::with_id(+ format!("mic-input:{}", device.id),+ device.name.replace('&', "&&"),+ true,+ state.selected.as_ref() == Some(&device.id),+ None,+ );+ self.devices.append(&item)?;+ self.choices.push((item, Some(device.id.clone())));+ }+ if state+ .selected+ .as_ref()+ .is_some_and(|id| !state.devices.iter().any(|d| &d.id == id))+ {+ self.devices.append(&CheckMenuItem::new(+ "Selected input unavailable",+ false,+ true,+ None,+ ))?;+ }+ self.devices.append_items(&[+ &PredefinedMenuItem::separator(),+ &MenuItem::with_id("mic-refresh", "Refresh Devices", true, None),+ ])?;+ }+ // Restore radio choices even if a native check item just toggled itself.+ for (item, selected) in &self.choices {+ item.set_checked(selected == &state.selected);+ }+ for (item, value) in &self.sensitivities {+ item.set_checked(*value == state.sensitivity);+ }+ self.state = Some(state.clone());+ Ok(())+ }+ pub fn command(&self, id: &str) -> Option<crate::menu::Command> {+ use crate::menu::Command;+ match id {+ "mic-toggle" => Some(Command::ToggleMicrophone),+ "mic-default" => Some(Command::MicrophoneDevice(None)),+ "mic-refresh" => Some(Command::RefreshMicrophones),+ _ => self+ .choices+ .iter()+ .find(|(item, _)| item.id().as_ref() == id)+ .map(|(_, device)| Command::MicrophoneDevice(device.clone()))+ .or_else(|| {+ self.sensitivities+ .iter()+ .find(|(item, _)| item.id().as_ref() == id)+ .map(|(_, value)| Command::MicrophoneSensitivity(*value))+ }),+ }+ }+}diff --git a/native/apps/mesh-avatar-desktop/src/status_bar.rs b/native/apps/mesh-avatar-desktop/src/status_bar.rsindex 602006e..4d59530 100644--- a/native/apps/mesh-avatar-desktop/src/status_bar.rs+++ b/native/apps/mesh-avatar-desktop/src/status_bar.rs@@ -31,6 +31,7 @@ impl StatusBar {recent: &muda::Submenu,open: &muda::MenuItem,quit: &muda::MenuItem,+ microphone: &muda::Submenu,) -> anyhow::Result<Self> {use muda::{CheckMenuItem, Menu, MenuItem, PredefinedMenuItem};let menu = Menu::new();@@ -40,6 +41,7 @@ impl StatusBar {menu.append_items(&[&visibility,&click_through,+ microphone,&PredefinedMenuItem::separator(),open,recent,