Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

docs: room-test skill for measuring the room mic with an ESP32 speaker as the table, linked from AGENTS.md

wqugurue7fe8d04218f
diff --git a/.claude/skills/room-test/SKILL.md b/.claude/skills/room-test/SKILL.md
new file mode 100644
index 0000000..ada4a37
--- /dev/null
+++ b/.claude/skills/room-test/SKILL.md
@@ -0,0 +1,52 @@
+---
+name: room-test
+description: Measure Cicada's room microphone for real on the Mac — echo from the speakers, people at the table talking in the gaps and over the online side, music, headphones — with an ESP32 speaker standing in for a person at the table, and score each round. Use after any change to 打开麦克风, the room mic, EchoGate / EchoMatch, voice activity or the room recognizer, or for "测回声", "测会议室麦克风", "混合会议实测", "抢话测试".
+---
+
+# Room test
+
+How the 打开麦克风 change (cb7762c) was measured. The Mac is the reference; Windows and Linux VMs have no speakers or mic, so their rounds are UI and state only (`cicadactl mic on`, `roomechosim`).
+
+## The rig
+
+- **Online side:** `mac.wav` (five English sentences, 10 s apart) from the MacBook's speakers, through `afplay`.
+- **Table side:** `table.wav` (six Chinese sentences: three in the Mac's gaps, three over its speech) from the M5Stack StopWatch's speaker: `~/workshop/15.experiment/m5-stopwatch/tablevoice/tv.py play <wav> --at <utc>` (prints START/END). Different languages, so each record line says which side it came from.
+- **Where:** the ESP32 about 10 cm from the MacBook Pro's mics, which sit under the left speaker grille near the hinge (by Esc), speaker facing it, not on the right grille. At 30 cm it reaches only −22 dB peak and half the table lines are lost to level alone. Its volume is already the ceiling (255).
+- The ESP32 belongs to the `esp32-stopwatch-meeting-mic-test` session: message it before using the port (one `tv.py` at a time) and when done. Flashing it is that session's user's call.
+- `scripts/clips.py` writes the clips (and `music.wav`); `scripts/audio.swift` sets the output device and the mic's input level; `scripts/round.sh` runs one round and scores it. Both are built into `$WORK` on first use.
+
+## Before the first round
+
+- `ListAgents`: tell the sessions on this repo you hold the dev build, the speakers and the mic; nobody else rebuilds or drives `build/Cicada.app` until you say so. Build it yourself and check the panel's `main @ <commit>` line is yours.
+- Nothing else makes sound: quit the release Cicada (`osascript -e 'quit app id "com.wquguru.cicada"'`; if it hangs, `kill -TERM`), shut simulators (`xcrun simctl shutdown all`). `pmset -g assertions | grep -i audio` lists who plays or records. Ask before closing anything the user may be using.
+- `audio list`: output must be the MacBook speakers and the MacBook mic's level about 0.5. **AirPods take the output when they connect** (and the clips then play in the user's ears): `round.sh` forces the output every round; check it again after any pause, and ask the user before playing out loud.
+- The terminal has no microphone permission: `ffmpeg -f avfoundation` records zeros. Judge the mic only through the app (`hybridState`, the record).
+
+## Rounds
+
+`scripts/round.sh <label> [mac|music|none] [volume]`, env `OUT` (`BlackHole` = headphones: nothing reaches the room), `ECHO` (`roomEcho`, default off), `GATE`, `TABLE`. Each round is about 75 s and prints, for example:
+
+```
+== speakers56: mac=5 room=3 echo_dropped=0 english_room=0 table: 空100% 抢0% 空75% 抢0% 抢20% 空100%
+ echo=true [during=7.8s p80=0.0943 quiet=4.8s floor=0.0043]
+```
+
+`english_room` is online speech that got into the room's record (echo). `空` is a table sentence in a gap, `抢` one over the online side, with the share of its characters found. `echo=` is what EchoGate measured: speakers about ×20 at 56 %, ×6 at 25 %, headphones about ×1.
+
+The pass line (2026-11-06, MacBook Pro 14):
+
+| Round | Command | Pass |
+|---|---|---|
+| Speakers 25 / 56 / 100 % | `round.sh s25 mac 25` … | `english_room` 0; gaps ≥ 75 % |
+| Music | `round.sh music music 56` | table ≥ 60 % (gaps and over) |
+| Headphones | `OUT=BlackHole round.sh hp mac 56` | `echo=false`; over ≥ 90 % |
+| Then speakers again | `round.sh s56b mac 56` | `english_room` 0 (the measurement starts over) |
+| Table alone | `round.sh alone none` | 6/6 |
+
+Lines over the online side are lost on speakers by design (the gate). Run a round twice before believing a single bad cell: the ESP32 is quiet and one round varies.
+
+Also: `lsctl roomMicSilent:on` then `mic:on` shows 麦克风没声音 after about 10 s (log `room mic: silent since it started`, then `still silent`); `roomEchoSim:<on|off|real>` fixes the measurement for UI work.
+
+## After
+
+`lsctl mic:off`, `stop`, `roomEcho:off`, `roomGate:on`, `roomMicSilent:off`; output back to what the user had; volume back; tell the ESP32 session and the repo's sessions you're done. Put the numbers in the commit message.
diff --git a/.claude/skills/room-test/scripts/audio.swift b/.claude/skills/room-test/scripts/audio.swift
new file mode 100644
index 0000000..a2b403e
--- /dev/null
+++ b/.claude/skills/room-test/scripts/audio.swift
@@ -0,0 +1,70 @@
+// Core Audio from the shell, for room tests (macOS has no command for these):
+// audio list devices, the default input and output, each input's level
+// audio out <name part> make it the default output (and the system output)
+// audio level <name part> <0-1> an input's level (the MacBook mic's)
+// Build: swiftc -O audio.swift -o audio (round.sh does it once into the work folder).
+import CoreAudio
+import Foundation
+
+let system = AudioObjectID(kAudioObjectSystemObject)
+
+func address(_ selector: AudioObjectPropertySelector, _ scope: AudioObjectPropertyScope = kAudioObjectPropertyScopeGlobal) -> AudioObjectPropertyAddress {
+ AudioObjectPropertyAddress(mSelector: selector, mScope: scope, mElement: 0)
+}
+
+func name(_ d: AudioObjectID) -> String {
+ var a = address(kAudioObjectPropertyName)
+ var s: CFString = "" as CFString
+ var size = UInt32(MemoryLayout<CFString>.size)
+ AudioObjectGetPropertyData(d, &a, 0, nil, &size, &s)
+ return s as String
+}
+
+func devices() -> [AudioObjectID] {
+ var a = address(kAudioHardwarePropertyDevices)
+ var size: UInt32 = 0
+ AudioObjectGetPropertyDataSize(system, &a, 0, nil, &size)
+ var ids = [AudioObjectID](repeating: 0, count: Int(size) / 4)
+ AudioObjectGetPropertyData(system, &a, 0, nil, &size, &ids)
+ return ids
+}
+
+func current(_ selector: AudioObjectPropertySelector) -> AudioObjectID {
+ var a = address(selector)
+ var d = AudioObjectID(0)
+ var size = UInt32(4)
+ AudioObjectGetPropertyData(system, &a, 0, nil, &size, &d)
+ return d
+}
+
+func inputLevel(_ d: AudioObjectID) -> Float32? {
+ var a = address(kAudioDevicePropertyVolumeScalar, kAudioDevicePropertyScopeInput)
+ var v: Float32 = 0
+ var size = UInt32(4)
+ return AudioObjectGetPropertyData(d, &a, 0, nil, &size, &v) == noErr ? v : nil
+}
+
+func find(_ part: String) -> AudioObjectID? { devices().first { name($0).contains(part) } }
+
+let args = CommandLine.arguments.dropFirst()
+switch args.first {
+case "out":
+ guard let part = args.dropFirst().first, var d = find(part) else { print("no such device"); exit(1) }
+ for sel in [kAudioHardwarePropertyDefaultOutputDevice, kAudioHardwarePropertyDefaultSystemOutputDevice] {
+ var a = address(sel)
+ AudioObjectSetPropertyData(system, &a, 0, nil, 4, &d)
+ }
+ print("output: \(name(current(kAudioHardwarePropertyDefaultOutputDevice)))")
+case "level":
+ let rest = Array(args.dropFirst())
+ guard rest.count == 2, let d = find(rest[0]), var v = Float32(rest[1]) else { print("audio level <name part> <0-1>"); exit(1) }
+ var a = address(kAudioDevicePropertyVolumeScalar, kAudioDevicePropertyScopeInput)
+ AudioObjectSetPropertyData(d, &a, 0, nil, 4, &v)
+ print("\(name(d)) input level \(inputLevel(d) ?? -1)")
+default:
+ print("output: \(name(current(kAudioHardwarePropertyDefaultOutputDevice)))")
+ print("input: \(name(current(kAudioHardwarePropertyDefaultInputDevice)))")
+ for d in devices() {
+ if let v = inputLevel(d) { print(" \(name(d)): input level \(v)") }
+ }
+}
diff --git a/.claude/skills/room-test/scripts/clips.py b/.claude/skills/room-test/scripts/clips.py
new file mode 100755
index 0000000..ec70b86
--- /dev/null
+++ b/.claude/skills/room-test/scripts/clips.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""Writes the room test's clips into a folder (16 kHz mono WAV, 52 s each, on one timeline):
+
+ mac.wav five English sentences (Samantha) at 0, 10, 20, 30, 40 s: the online side, from the speakers
+ table.wav six Chinese sentences (Tingting) for the ESP32 speaker: three in the gaps (6, 25, 47 s),
+ three over the Mac's speech (11, 31, 41 s)
+ music.wav chords and a beat, no words: what the Mac plays instead of mac.wav in the music round
+
+Different languages on the two sides, so every line in the record says where it came from.
+Usage: clips.py <folder>"""
+import array, math, os, random, subprocess, sys, wave
+
+MAC = ["Revenue grew twelve percent compared to last quarter, mostly from enterprise.",
+ "The mobile team shipped offline mode two weeks ago, and crashes dropped by half.",
+ "We still have three open roles in engineering and one in design.",
+ "Customers keep asking for better export options before summer.",
+ "The offsite budget needs approval by Friday, so send comments soon."]
+TABLE = ["我同意这个数字。", "等一下,企业版具体涨了多少?", "设计那个岗位很急。", "好的,没问题。", "导出功能我们下周排期。", "周四之前我会回复。"]
+TABLE_AT = [6, 11, 25, 31, 41, 47]
+RATE, LENGTH = 16000, 52
+
+
+def say(voice, text, out):
+ aiff = out + ".aiff"
+ subprocess.run(["say", "-v", voice, "-o", aiff, text], check=True)
+ subprocess.run(["afconvert", "-f", "WAVE", "-d", "LEI16@%d" % RATE, "-c", "1", aiff, out], check=True)
+ os.remove(aiff)
+ w = wave.open(out)
+ return array.array("h", w.readframes(w.getnframes()))
+
+
+def write(path, pieces):
+ buf = array.array("h", [0] * (RATE * LENGTH))
+ for samples, at in pieces:
+ start = int(at * RATE)
+ buf[start:start + len(samples)] = samples
+ with wave.open(path, "w") as w:
+ w.setnchannels(1); w.setsampwidth(2); w.setframerate(RATE)
+ w.writeframes(buf.tobytes())
+
+
+def music():
+ out, chords = array.array("h"), [(220, 277, 330), (196, 247, 294), (174, 220, 262), (196, 247, 294)]
+ for i in range(RATE * LENGTH):
+ t = i / RATE
+ v = sum(math.sin(2 * math.pi * f * t) for f in chords[int(t / 2) % 4]) * 0.18 * (0.7 + 0.3 * math.sin(math.pi * t))
+ beat = t % 0.5
+ if beat < 0.08:
+ v += 0.35 * math.sin(2 * math.pi * 60 * t) * (1 - beat / 0.08)
+ if 0.25 < beat < 0.28:
+ v += 0.15 * (random.random() * 2 - 1)
+ out.append(int(max(-1, min(1, v)) * 30000))
+ return out
+
+
+if __name__ == "__main__":
+ folder = sys.argv[1]
+ os.makedirs(folder, exist_ok=True)
+ tmp = os.path.join(folder, "piece.wav")
+ write(os.path.join(folder, "mac.wav"), [(say("Samantha", s, tmp), i * 10) for i, s in enumerate(MAC)])
+ write(os.path.join(folder, "table.wav"), [(say("Tingting", s, tmp), at) for s, at in zip(TABLE, TABLE_AT)])
+ os.remove(tmp)
+ write(os.path.join(folder, "music.wav"), [(music(), 0)])
+ print("clips in", folder)
diff --git a/.claude/skills/room-test/scripts/round.sh b/.claude/skills/room-test/scripts/round.sh
new file mode 100755
index 0000000..a98a8c4
--- /dev/null
+++ b/.claude/skills/room-test/scripts/round.sh
@@ -0,0 +1,57 @@
+#!/bin/zsh
+# One room-test round on the Mac dev build, scored. Usage:
+# round.sh <label> [mac|music|none] [volume 0-100]
+# Env: OUT (output device name part, default "MacBook Pro Speakers"; "BlackHole" stands in for
+# headphones), ECHO (roomEcho on|off, default off), GATE (roomGate on|off, default on),
+# TABLE (on|off: play table.wav on the ESP32, default on), WORK (clips and tools, default
+# $TMPDIR/cicada-room-test).
+# Prints: mac/room line counts, echoes dropped, English room lines (echo that got through), and
+# for each table sentence gap|over and the share of its characters found in the room lines.
+set -e
+here=${0:A:h}
+repo=${here:h:h:h:h}
+label=${1:?label}; play=${2:-mac}; vol=${3:-56}
+OUT=${OUT:-MacBook Pro Speakers}; ECHO=${ECHO:-off}; GATE=${GATE:-on}; TABLE=${TABLE:-on}
+WORK=${WORK:-${TMPDIR:-/tmp}/cicada-room-test}
+TV=~/workshop/15.experiment/m5-stopwatch/tablevoice/tv.py
+LOG=/tmp/livesubs-dev-debug.log
+ctl=$repo/tools/lsctl
+mkdir -p $WORK
+[[ -x $WORK/audio ]] || swiftc -O $here/audio.swift -o $WORK/audio
+[[ -f $WORK/table.wav ]] || python3 $here/clips.py $WORK >/dev/null
+[[ -x $ctl ]] || swiftc -O $repo/tools/lsctl.swift -o $ctl
+
+$WORK/audio out "$OUT" >/dev/null
+osascript -e "set volume output volume $vol"
+$ctl roomEcho:$ECHO; $ctl roomGate:$GATE; $ctl mic:off; $ctl stop; sleep 1
+from=$(($(wc -l < $LOG) + 1))
+$ctl mic:on; sleep 2
+t0=$(python3 -c "import time; print(int(time.time()) + 6)")
+at=$(python3 -c "import datetime; print(datetime.datetime.fromtimestamp($t0, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))")
+[[ $TABLE == on ]] && python3 $TV play $WORK/table.wav --at $at > $WORK/tv.out 2>&1 &
+python3 -c "import time; time.sleep(max(0, $t0 - time.time()))"
+if [[ $play == none ]]; then sleep 52; else afplay $WORK/$play.wav; fi
+wait; sleep 8
+$ctl hybridState; sleep 1
+$ctl mic:off; $ctl stop; sleep 3
+session=$(ls -td ~/Library/Application\ Support/LiveSubs\ Dev/Sessions/* | head -1)
+tail -n +$from $LOG > $WORK/round.log
+python3 - "$session" "$label" "$WORK/round.log" <<'PY'
+import json, re, sys
+session, label, log = sys.argv[1:]
+table = ["我同意这个数字", "等一下企业版具体涨了多少", "设计那个岗位很急", "好的没问题", "导出功能我们下周排期", "周四之前我会回复"]
+over = [False, True, False, True, True, False]
+lines = json.load(open(session + "/session.json"))["lines"]
+room = [l["src"] for l in lines if l.get("via") == "room"]
+mac = [l for l in lines if l.get("via") != "room"]
+text = "".join(room)
+english = [r for r in room if sum(c.isascii() and c.isalpha() for c in r) > 5]
+log = open(log).read()
+dropped = log.count("dropped as an echo")
+state = re.findall(r"hybrid state .*", log)
+echo = re.search(r"echo=(\S+) \[([^]]*)\]", state[-1]) if state else None
+cells = " ".join(("抢" if o else "空") + "%d%%" % round(100 * sum(c in text for c in t) / len(t)) for t, o in zip(table, over))
+print(f"== {label}: mac={len(mac)} room={len(room)} echo_dropped={dropped} english_room={len(english)} table: {cells}")
+if echo: print(f" echo={echo.group(1)} [{echo.group(2)}]")
+for r in room: print(" room|", r[:90])
+PY
diff --git a/AGENTS.md b/AGENTS.md
index 9d3f63f..d6735fd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl
- Mac surfaces: menu bar panel, live notes window (default) or subtitle bar while listening, main window (meeting records), settings, four-step onboarding (system audio, sample meeting, Ling key, speaking if wanted). A request that fits none of them gets pushed back before any UI is added.
- Nothing the user does needs the Terminal.
-- Listening: Core Audio process tap → on-device language detection and `SpeechAnalyzer` → translation. Voices: a bundled Core ML voiceprint model (`SpeakerID.swift`), compiled on first use. Speaking: hold right ⌥ or a shortcut → mic → Ming (with a Ling key) or on-device + translation → voice → BlackHole 2ch virtual mic.
+- Listening: Core Audio process tap → on-device language detection and `SpeechAnalyzer` → translation. Voices: a bundled Core ML voiceprint model (`SpeakerID.swift`). Speaking: hold right ⌥ → mic → Ming (with a Ling key) or on-device + translation → voice → BlackHole 2ch virtual mic.
## Hard rules
@@ -29,9 +29,9 @@ Cicada (知了, formerly Live Subs) turns what a computer plays into live transl
## Layout
-- `Sources/Cicada`: the app, one concern per file. Engines are UI-free (`ListenEngine`, `SpeakEngine`, `SpeakTest`, `Notes`, `Translator`, `Ling`, `VirtualMic`, `SessionStore`, `Updates`…); `AppModel` wires them and holds the debug commands. Settings keys: `AppSettings` in `Settings.swift`.
+- `Sources/Cicada`: the app, one concern per file. Engines are UI-free (`ListenEngine`, `SpeakEngine`, `Notes`, `Translator`, `Ling`, `VirtualMic`, `SessionStore`…); `AppModel` wires them and holds the debug commands. Settings keys: `AppSettings` in `Settings.swift`.
- `Sources/CicadaIcon`: renders the icon set. `site/`: the website, built by `scripts/site.py`.
-- The site is Chinese at `/`, English / Japanese / Korean under `/en/` `/ja/` `/ko/`; every `{{t.key}}` comes from `site/i18n/<lang>.json`. `start.html` is the setup page (`download.html` the downloads); its `img/start/` screenshots come from the app in each language. `tools/`: test helpers. `Tests/CicadaTests`: unit tests for the pure parts.
+- The site is Chinese at `/`, English / Japanese / Korean under `/en/` `/ja/` `/ko/`; every `{{t.key}}` comes from `site/i18n/<lang>.json`. `start.html` is the setup page (`download.html` the downloads); its `img/start/` shots come from the app per language. `tools/`: test helpers. `Tests/CicadaTests`: unit tests for the pure parts.
## Commands
@@ -48,7 +48,7 @@ scripts/deploy-site.sh # build and deploy the site (cicada.indal
- Run the app and check the behaviour, not just the build; check the English UI too.
- Drive the dev build with `tools/lsctl` (commands and testing tips in `tools/README.md`; the source of truth is `AppModel.debugCommand`). Use `afplay Resources/sample/sample.m4a` or `say -o` clips as input and read `/tmp/livesubs-dev-debug.log`.
-- A real voice, the BlackHole install, Input Monitoring and a Mac without permissions need a person.
+- Room mic and echo: `.claude/skills/room-test` (ESP32 as the table). A real voice, the BlackHole install, Input Monitoring and a Mac without permissions need a person.
## Conventions
diff --git a/tools/README.md b/tools/README.md
index acc9a00..07cfb18 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -7,7 +7,7 @@
- `lsctl <命令>`:通过分布式通知 `com.wquguru.cicada.debug` 遥控 App。
- 开关字幕:`start` / `stop`(`start:user` 当作用户点了开始听,纪要窗口立即出现;`start` 当作自动开始,等到有人说话)
- - 听哪里:`listenSource:<system|room|both>`(both 是电脑和会议室:再开一个听麦克风的识别,`hybridState` 把两边的状态写进日志;`roomEcho:off` / `roomGate:off` 下一场会议不用回声消除 / 不在电脑放人声时关麦克风,单独试每道防线,日志 `hybrid: room line dropped as an echo` / `kept`;`voiceMicRun:<on|off>` 只开回声消除单元看它对别的声音有没有影响)(room 用麦克风听会议室,日志里 `room mic started: <设备>`,念译文时 `room mic muted` / `open`),`roomPrompt:<room|no>` 等于在“在会议室里开会?”里点“改听会议室”或“不是”(听电脑 60 秒没声音才出现,日志 `mac silent true`);`micDeniedSim:<on|off>` 让“电脑和会议室”当作麦克风被拒(纪要窗口顶部提示、字幕条橙色标签、菜单栏橙点,纪要窗口收起 10 秒后发一次通知,日志 `problem:` 和 `menu bar: badge=`)
+ - 麦克风:`mic:<on|off>` 等于点“打开麦克风”/“关闭麦克风”(没在听时打开会开始听;旧的 `listenSource:<system|room|both>` 也还能用),`hybridState` 把两边的状态写进日志,含 `echo=` 和测量值(扬声器传到麦克风没有)、`music=`、`micSilent=`;`roomEcho:on` / `roomGate:off` 下一场会议用系统回声消除 / 不在电脑放人声时关麦克风,单独试每道防线,日志 `hybrid: room line dropped as an echo` / `kept`、`room echo: speakers reach the mic` / `none`;`roomEchoSim:<on|off|real>` 假装测出(或没测出)回声;`roomMicSilent:<on|off>` 让麦克风从下次打开起只给 0(日志 `room mic: silent since it started`,再 `still silent`,纪要窗口出“麦克风没声音”);`voiceMicRun:<on|off>` 只开回声消除单元看它对别的声音有没有影响;念译文时 `room mic muted` / `open`;`micDeniedSim:<on|off>` 让麦克风当作被拒(纪要窗口顶部提示、字幕条橙色标签、菜单栏橙点,纪要窗口收起 10 秒后发一次通知,日志 `problem:` 和 `menu bar: badge=`)。实测回声和桌边的话:`.claude/skills/room-test`
- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)
- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步
- 会议软件的麦克风:`micUsers` 把每个读麦克风的进程和列表写进日志,`micGuide:<bundle id 或名字>` 打开怎么改,`micGuideRender:<bundle id>=<png>`