知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat: Listen to › Mac + Room hears the online meeting and the people at the table together, and records each remote sentence once
wqugurue87615fb911d
diff --git a/README.en.md b/README.en.mdindex c3e76f8..f13955d 100644--- a/README.en.md+++ b/README.en.md@@ -58,6 +58,8 @@ Cicada detects the spoken language on device within seconds and translates intoFor a meeting around a table, set **Listen to** in the menu bar panel to **Room** and Cicada listens through the Mac's microphone, with the same subtitles, notes and records as an online meeting. Speak-back then reads the translation out of the speakers, no virtual mic needed, and the microphone stops listening while it does so the translation isn't recorded as someone else. If nothing plays on the Mac for a minute while it listens to the computer, the panel asks whether to listen to the room instead; every launch starts with the computer again.+When some people are in the room and others are online, choose **Mac + Room** (macOS 26): the online side is heard from the Mac's audio and the table from the microphone, each in its own language, in one meeting record. The online voices coming out of the speakers reach the microphone too; Cicada takes them out with macOS echo cancellation, so people at the table can talk over a remote speaker and both are kept. When echo cancellation isn't available, the microphone pauses while someone online is talking. As a last check, a room line that is almost the same as what the Mac just played isn't recorded twice.+### Speak back in their languageHold the right `⌥` key and speak so the room hears your translated voice through BlackHole 2ch, a virtual microphone you can install from the app with one click and that Cicada switches to automatically while interpreting is on. With an AI service key the other side hears natural voices (Gemini through OpenRouter or ZenMux, Ming through Ling), and Ling can also clone your own voice from an 8 to 30 second sample; without a key it uses macOS system voices.diff --git a/README.ja.md b/README.ja.mdindex 3c32c9f..1300db0 100644--- a/README.ja.md+++ b/README.ja.md@@ -60,6 +60,8 @@ Cicada は、話されている言語を数秒以内にデバイス上で検出テーブルを囲む会議では、メニューバーのパネルで **聞く場所** を **会議室** にすると、Cicada は Mac のマイクで聞き取り、オンライン会議と同じ字幕、メモ、記録を作ります。このとき話し返しは翻訳をスピーカーから読み上げるので、仮想マイクは要りません。読み上げている間はマイクが聞き取りを止めるので、翻訳がほかの人の発言として記録されることはありません。コンピューターの音を聞いている間に 1 分間何も再生されないと、代わりに会議室を聞くかどうかをパネルが尋ねます。起動するたびに、聞く場所はコンピューターに戻ります。+会議室にいる人とオンラインの人が混ざる会議では、**Mac と会議室** を選びます(macOS 26)。オンラインの人は Mac の音から、テーブルの人はマイクから聞き取り、それぞれの言語で一つの会議記録に残します。スピーカーから流れるオンラインの声はマイクにも入りますが、macOS のエコーキャンセルで取り除くので、テーブルの人がオンラインの人と同時に話しても両方残ります。エコーキャンセルが使えないときは、オンラインの人が話している間だけマイクが聞き取りを止めます。最後に文字でも比べ、Mac で流れたばかりの発言とほぼ同じ行は二重に記録しません。+### 相手の言語で話し返す右の `⌥` キーを押したまま話すと、BlackHole 2ch を通じて、翻訳された声が相手に届きます。BlackHole 2ch はアプリからワンクリックでインストールできる仮想マイクで、通訳がオンの間は Cicada が自動的に切り替えます。AI サービスのキーがあれば、相手には自然な音声(OpenRouter と ZenMux では Gemini、Ling では Ming)が聞こえ、Ling では 8〜30 秒のサンプルからあなた自身の声のクローンを作ることもできます。キーがない場合は、macOS のシステム音声を使います。diff --git a/README.ko.md b/README.ko.mdindex b9c835c..c0a1bdd 100644--- a/README.ko.md+++ b/README.ko.md@@ -58,6 +58,8 @@ Zoom, Teams, Feishu 회의부터 X Spaces, Discord 스테이지, YouTube 라이회의실에 모여 회의할 때는 메뉴 막대 패널의 **듣는 곳**을 **회의실**로 바꾸세요. Mac 마이크로 주변 사람들의 말을 듣고 온라인 회의와 똑같이 자막, 회의록, 기록을 남깁니다. 이때 동시통역은 가상 마이크 없이 스피커로 번역문을 읽어 주며, 읽는 동안에는 마이크가 잠시 멈춰 번역된 소리가 다른 사람의 발언으로 다시 기록되지 않습니다. 컴퓨터 소리를 듣는 상태에서 1분 동안 아무 소리가 나지 않으면 패널에서 회의실 듣기로 바꿀지 물어봅니다. 앱을 다시 실행하면 항상 컴퓨터 소리 듣기로 시작합니다.+회의실에 있는 사람과 온라인 참석자가 섞인 회의라면 **Mac과 회의실**을 고르세요(macOS 26). 온라인 참석자는 컴퓨터 소리로, 테이블의 사람은 마이크로 듣고, 각자의 언어로 하나의 회의 기록에 남깁니다. 스피커로 나오는 온라인 목소리는 마이크에도 들어가지만 macOS 에코 제거로 걷어내므로, 테이블에서 온라인 참석자와 동시에 말해도 둘 다 남습니다. 에코 제거를 쓸 수 없을 때는 온라인에서 누군가 말하는 동안 마이크가 잠시 듣지 않습니다. 마지막으로 글자도 비교해, 컴퓨터에서 방금 나온 말과 거의 같은 줄은 두 번 기록하지 않습니다.+### 상대방 언어로 말하기오른쪽 `⌥` 키를 누른 채 말하면 번역된 음성이 가상 마이크인 BlackHole 2ch를 통해 회의 앱으로 전달됩니다. BlackHole 2ch는 앱에서 클릭 한 번으로 설치할 수 있으며, 동시통역을 켜면 Cicada가 자동으로 마이크를 전환합니다. AI 서비스 키를 설정하면 자연스러운 음성(OpenRouter나 ZenMux의 Gemini, Ling의 Ming)을 쓸 수 있고, Ling에서는 8~30초 분량의 녹음으로 내 목소리를 복제할 수도 있습니다. 키가 없어도 macOS 기본 음성을 사용할 수 있습니다.diff --git a/README.md b/README.mdindex 3a3addf..00a131b 100644--- a/README.md+++ b/README.md@@ -56,6 +56,8 @@在会议室里开会时,把菜单栏面板的“听哪里”改成“会议室”,知了就用 Mac 的麦克风听桌边的人说话,字幕、纪要和会议记录跟线上会议一样。同声传译这时从扬声器念出译文,不需要虚拟麦克风,念的时候麦克风暂时不听,不会把译文再记成别人的话。听电脑声音时如果 1 分钟都没有声音,面板会问一句要不要改听会议室;每次启动都回到听电脑声音。+有人在会议室、有人在线上时,选“电脑和会议室”(需要 macOS 26):线上的人从电脑声音听,桌边的人从麦克风听,两边各认各的语言,记在同一份会议记录里。扬声器放出来的线上声音会被麦克风再听到一遍,知了用 macOS 的回声消除把它去掉,所以桌边的人跟线上的人同时说话也都能记下;回声消除用不了时,线上有人说话的那一会儿麦克风先不听。最后还会比一遍文字,跟电脑声音里刚说过的话几乎一样的那句不再记第二遍。+### 同声传译按住键盘右边的 `⌥` 键说话,对方在会议软件里就能直接听到翻译后的语音,打开同声传译时知了会自动把系统麦克风切到一键安装的虚拟驱动 BlackHole 2ch。填了 Ling API key 后可以用自然人声或用 8 到 30 秒录音克隆你自己的声音,不填也能用 Mac 自带语音。diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex 8b2eb55..22a34d4 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -923,6 +923,9 @@"电脑声音" = "This Mac";"电脑声音(线上会议、视频)" = "This Mac (online meetings, videos)";"会议室(用麦克风听桌边的人)" = "Room (the mic hears people at the table)";+"电脑和会议室" = "Mac + Room";+"电脑和会议室(线上和桌边的人都听)" = "Mac + Room (people online and at the table)";+"电脑和会议室 · %@" = "Mac + Room · %@";"系统" = "System";"系统麦克风还是 %@" = "System mic is still %@";"别的软件现在听不到你说话" = "Other apps can't hear you now";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 6300436..878eaaf 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -923,6 +923,9 @@"电脑声音" = "この Mac";"电脑声音(线上会议、视频)" = "この Mac(オンライン会議・動画)";"会议室(用麦克风听桌边的人)" = "会議室(マイクでテーブルの声を聞く)";+"电脑和会议室" = "Mac と会議室";+"电脑和会议室(线上和桌边的人都听)" = "Mac と会議室(オンラインとテーブルの両方)";+"电脑和会议室 · %@" = "Mac と会議室 · %@";"系统" = "システム";"系统麦克风还是 %@" = "システムのマイクがまだ %@ です";"别的软件现在听不到你说话" = "ほかのアプリにあなたの声が届きません";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex c3ce219..1de94c7 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -923,6 +923,9 @@"电脑声音" = "이 Mac";"电脑声音(线上会议、视频)" = "이 Mac (온라인 회의, 동영상)";"会议室(用麦克风听桌边的人)" = "회의실 (마이크로 테이블의 목소리를 들어요)";+"电脑和会议室" = "Mac과 회의실";+"电脑和会议室(线上和桌边的人都听)" = "Mac과 회의실 (온라인과 테이블 모두)";+"电脑和会议室 · %@" = "Mac과 회의실 · %@";"系统" = "시스템";"系统麦克风还是 %@" = "시스템 마이크가 아직 %@예요";"别的软件现在听不到你说话" = "다른 앱에 내 목소리가 들리지 않아요";diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 1d1b361..c71cbeb 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -17,7 +17,22 @@ final class AppModel: ObservableObject {let talkRight = RightOptionKey()let toggleKey = HotKey(id: 2, shortcut: .defaultToggle)lazy var listen = ListenEngine(settings: settings)- lazy var speak = SpeakEngine(settings: settings)+ /// The one echo-cancelling mic unit, shared by the talk key and 电脑和会议室's room.+ let voiceMic = VoiceMic()+ lazy var speak = SpeakEngine(settings: settings, voiceMic: voiceMic)+ /// 电脑和会议室: the microphone side, its own engine (language, pauses, model), as Feishu keeps the+ /// online and the room streams apart instead of mixing them into one track.+ lazy var roomListen = ListenEngine(settings: settings, role: .room)+ /// Debug (`roomEcho:off`, `roomGate:off`): the room without echo cancellation, or without the+ /// gate, to try each defence alone. Next meeting.+ var roomEchoCancel = true+ var roomEchoGate = true+ /// The Mac's lines of late (wall clock), and room lines waiting to be told apart from their echo.+ private var recentOnline: [EchoMatch.Heard] = []+ private var heldRoom: [(id: Int, seg: Segment, duration: Double, heard: EchoMatch.Heard)] = []+ /// What each engine shows as the line in progress, and when it last changed.+ private var liveMain = (src: "", dst: "", at: Date.distantPast)+ private var liveRoom = (src: "", dst: "", at: Date.distantPast)lazy var speakTester = SpeakTester(speak: speak, ling: ling, settings: settings)/// Key released → the room heard the first sound, from the latest real press or sound test.@Published var lastSpeakLatency: Double? = UserDefaults.standard.object(forKey: "lastSpeakLatency") as? Double {@@ -149,22 +164,24 @@ final class AppModel: ObservableObject {// A meeting or speaking holds the update notification until it ends (see stop()).updates.busy = { [weak self] in guard let self else { return false }; return self.running || self.speak.phase != .idle }listen.onSubtitle = { [weak self] src, dst in+ guard let self else { return }// Someone is speaking either way; only the wrong model's words aren't shown.- let visible = self?.listen.hidesSource == true ? "" : src- self?.liveSource = visible- self?.liveTranslation = dst- if !src.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { self?.heardSpeech(); self?.heardWords() }- guard let self, self.settings.displayMode == "bar" else { return }- self.overlay.clearStatus()- let shown = self.displayed(visible, dst)- self.overlay.setSubtitle(source: shown.source, translation: shown.translation)+ self.liveMain = (self.listen.hidesSource ? "" : src, dst, Date())+ self.showLive(spoke: src)+ }+ roomListen.onSubtitle = { [weak self] src, dst in+ guard let self else { return }+ self.liveRoom = (self.roomListen.hidesSource ? "" : src, dst, Date())+ self.showLive(spoke: src)}listen.onStatus = { [weak self] text inself?.status = textself?.overlay.setStatus(text)}listen.onStateChange = { [weak self] in self?.refresh() }- listen.onFinal = { [weak self] seg, duration in self?.recordHeard(seg, duration: duration) }+ listen.onFinal = { [weak self] seg, duration in self?.heardOnline(seg, duration: duration) }+ roomListen.onFinal = { [weak self] seg, duration in self?.heardInRoom(seg, duration: duration) }+ roomListen.onStatus = { debugLog("room engine: \($0)") }speakers.onVoice = { [weak self] line, voice inguard let self else { return }self.store.setVoice(lineID: line, voice)@@ -173,13 +190,10 @@ final class AppModel: ObservableObject {speakerSetting = settings.$speakerVoices.sink { [weak self] on inTranscriptExport.voices = onself?.listen.router.setVoiceCapture(on)+ self?.roomListen.router.setVoiceCapture(on)}- listen.onTranslated = { [weak self] segID, text in- guard let self else { return }- if self.heldJoin?.seg.id == segID { self.heldJoin?.translation = text }- guard let line = self.lineForSegment[segID] else { return }- self.store.setTranslation(lineID: line, text)- }+ listen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }+ roomListen.onTranslated = { [weak self] segID, text in self?.translated(segID, text) }diagnostics.enabled = { [weak self] in self?.settings.diagnostics ?? false }diagnostics.folder = { [weak self] in@@ -187,6 +201,7 @@ final class AppModel: ObservableObject {return self.store.folder(id)}listen.onTiming = { [weak self] in self?.diagnostics.record($0) }+ roomListen.onTiming = { [weak self] in self?.diagnostics.record($0) }speak.onTiming = { [weak self] in self?.diagnostics.record($0) }speak.onLatency = { [weak self] in self?.lastSpeakLatency = $0 }speakTester.onLatency = { [weak self] in self?.lastSpeakLatency = $0 }@@ -200,12 +215,27 @@ final class AppModel: ObservableObject {ling.config = { [weak self] in self?.settings.aiConfig ?? AIConfig(provider: .ling, base: AIProvider.ling.base, textModel: "Ling-3.1-flash") }listen.translator = translator+ roomListen.translator = translator+ roomListen.voiceMic = voiceMic+ listen.voiceMic = voiceMic // 会议室 alone: lets go of a leftover unit before the plain mic+ // Making or letting go of the echo-cancelling unit silences, for good, audio already flowing in+ // this process: the voice output (the room would hear nothing) and the Mac's audio tap (the+ // meeting would go unheard; measured: no line after it). Each is started anew.+ voiceMic.onUnitChanged = { [weak self] in+ Task { @MainActor in+ guard let self else { return }+ self.speak.newOutputEngine()+ if self.listen.isRunning { self.listen.reconnectAudio() }+ if self.roomListen.isRunning, !self.roomListen.hearsEchoCancelled { self.roomListen.reconnectAudio() }+ }+ }translator.glossary = { [weak self] in self?.notes.glossary ?? [] }importer.onFinished = { [weak self] id in self?.importFinished(id) }notes.language = { [weak self] id inTranslationService.englishName(self?.notesLanguageCode(id) ?? "zh-CN")}listen.translationOff = { [weak self] in self?.subtitles == "original" }+ roomListen.translationOff = { [weak self] in self?.subtitles == "original" }applyAIService()installer.speakThrough = { [weak self] text, lang, device in@@ -222,6 +252,7 @@ final class AppModel: ObservableObject {speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }speak.inputDevice = { [weak self] in self?.systemMic.recordingDevice }listen.roomDevice = { AudioDevices.roomMic }+ roomListen.roomDevice = { AudioDevices.roomMic }applyVoice()speak.onStatus = { [weak self] text in self?.status = text }speak.onLive = { [weak self] phase, src, dst in@@ -309,7 +340,7 @@ final class AppModel: ObservableObject {refresh()// Listening starts by itself at launch: never with the microphone open. 会议室 is chosen// for the meeting at hand, not kept for the next login.- if settings.listensToRoom { settings.listenSource = "system" }+ if settings.hearsRoom { settings.listenSource = "system" }start()if settings.speakEnabled { enableSpeaking(true) }}@@ -318,7 +349,8 @@ final class AppModel: ObservableObject {running = listen.isRunning// Once the tap has run, the permission is there: pausing doesn't take it away.systemAudioOK = systemAudioOK || (listen.isRunning && !settings.listensToRoom)- summary = settings.listensToRoom ? L("会议室 · \(listen.languageSummary())") : listen.languageSummary()+ summary = settings.listensToRoom ? L("会议室 · \(listen.languageSummary())")+ : settings.hearsBoth ? L("电脑和会议室 · \(listen.languageSummary())") : listen.languageSummary()candidates = listen.candidatesinstalled = listen.installedLocaleslet ask = listen.asksLanguage ? listen.askChoices : []@@ -505,6 +537,10 @@ final class AppModel: ObservableObject {lineForSegment = [:]lastHeard = nilheldJoin = nil+ recentOnline = []+ heldRoom = []+ liveMain = ("", "", .distantPast)+ liveRoom = ("", "", .distantPast)speechHeard = falseroomPromptDismissed = falsemeetingSubtitles = nil@@ -516,7 +552,8 @@ final class AppModel: ObservableObject {speak.setRecording(store.micAudioURL(session.id))}listen.start()- if settings.listensToRoom { store.markLiveInRoom() }+ if listen.isRunning, settings.hearsBoth { startRoomSide() }+ if settings.hearsRoom { store.markLiveInRoom() }notes.begin(session.id)if listen.isRunning {showDisplay(force: byUser)@@ -532,6 +569,7 @@ final class AppModel: ObservableObject {endWatch = nilsetEnding(nil)diagnostics.end()+ stopRoomSide()listen.stop()listen.router.setRecording(nil)speak.setRecording(nil)@@ -709,15 +747,20 @@ final class AppModel: ObservableObject {// MARK: Settings actions- /// 听哪里 in the panel: "system" or "room".+ /// 听哪里 in the panel: "system", "room" or "both".var listenSourceSelection: String {get { settings.listenSource }set {guard newValue != settings.listenSource else { return }- settings.listenSource = newValue == "room" ? "room" : "system"+ let wasRoomOnly = settings.listensToRoom+ settings.listenSource = ["room", "both"].contains(newValue) ? newValue : "system"roomPromptDismissed = true- if listen.isRunning && settings.listensToRoom { store.markLiveInRoom() }- listen.listenSourceChanged()+ if listen.isRunning && settings.hearsRoom { store.markLiveInRoom() }+ // The main engine changes only between the Mac and the room alone; "both" adds the room side.+ if wasRoomOnly != settings.listensToRoom { listen.listenSourceChanged() }+ if listen.isRunning {+ if settings.hearsBoth { startRoomSide() } else { stopRoomSide() }+ }applySystemMic()refreshMicUsers()refresh()@@ -737,12 +780,14 @@ final class AppModel: ObservableObject {private func muteRoomWhileSpeaking(_ phase: SpeakEngine.Phase) {if phase != .idle {listen.setRoomMuted(true)+ roomListen.setRoomMuted(true)return}DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] inMainActor.assumeIsolated {guard let self, self.speak.phase == .idle else { return }self.listen.setRoomMuted(false)+ self.roomListen.setRoomMuted(false)}}}@@ -1130,6 +1175,96 @@ final class AppModel: ObservableObject {}}+ // MARK: 电脑和会议室++ private func startRoomSide() {+ // macOS 14/15: two live recognizers interrupt each other (docs/macos-legacy-plan.md 2, 10).+ guard !roomListen.isRunning, !Recognition.legacy else { return }+ roomListen.echoCancelled = roomEchoCancel+ // A, the gate: only the plain room mic heeds it (echo cancellation keeps talk over a remote speaker).+ listen.router.setOnLoud(roomEchoGate ? { [gate = roomListen.echoGate] in gate.hold() } : nil)+ roomListen.start()+ debugLog("hybrid: room side started (echo cancellation \(roomEchoCancel ? "on" : "off"), gate \(roomEchoGate ? "on" : "off"))")+ }++ private func stopRoomSide() {+ listen.router.setOnLoud(nil)+ guard roomListen.isRunning else { return }+ roomListen.stop()+ // Room lines still waiting for their echo check are what was said: kept.+ let held = heldRoom+ heldRoom = []+ for h in held { recordRoom(h) }+ liveRoom = ("", "", .distantPast)+ debugLog("hybrid: room side stopped")+ }++ /// A sentence from the Mac's audio: recorded, and remembered to tell the room's copy of it.+ private func heardOnline(_ seg: Segment, duration: Double) {+ if roomListen.isRunning {+ let now = CFAbsoluteTimeGetCurrent()+ recentOnline.append(.init(text: seg.text, start: now - duration, end: now))+ recentOnline.removeAll { $0.end < now - 20 }+ heldRoom.removeAll { h in+ guard EchoMatch.isEcho(h.heard, online: recentOnline) else { return false }+ debugLog("hybrid: room line dropped as an echo (\(h.seg.text.count) chars)")+ return true+ }+ }+ recordHeard(seg, duration: duration)+ }++ /// A sentence from the room mic: an echo of the Mac's audio is dropped; the rest waits a moment+ /// for the Mac's line it may echo (`EchoMatch.hold`), then is recorded where it was said.+ private func heardInRoom(_ seg: Segment, duration: Double) {+ let now = CFAbsoluteTimeGetCurrent()+ let heard = EchoMatch.Heard(text: seg.text, start: now - duration, end: now)+ if EchoMatch.isEcho(heard, online: recentOnline) {+ debugLog("hybrid: room line dropped as an echo (\(seg.text.count) chars)")+ return+ }+ // The Mac has played nothing for a while: there is nothing for this to echo, no need to wait.+ if listen.router.stats().silenceRun >= EchoMatch.window {+ recordRoom((seg.id, seg, duration, heard))+ return+ }+ heldRoom.append((seg.id, seg, duration, heard))+ DispatchQueue.main.asyncAfter(deadline: .now() + EchoMatch.hold) { [weak self] in+ MainActor.assumeIsolated {+ guard let self, let i = self.heldRoom.firstIndex(where: { $0.id == seg.id }) else { return }+ let h = self.heldRoom.remove(at: i)+ self.recordRoom(h)+ }+ }+ }++ private func recordRoom(_ h: (id: Int, seg: Segment, duration: Double, heard: EchoMatch.Heard)) {+ let waited = CFAbsoluteTimeGetCurrent() - h.heard.end+ debugLog("hybrid: room line kept (\(h.seg.text.count) chars)")+ recordHeard(h.seg, duration: h.duration + waited)+ }++ private func translated(_ segID: Int, _ text: String) {+ if heldJoin?.seg.id == segID { heldJoin?.translation = text }+ if let i = heldRoom.firstIndex(where: { $0.id == segID }) { heldRoom[i].seg.translation = text }+ guard let line = lineForSegment[segID] else { return }+ store.setTranslation(lineID: line, text)+ }++ /// The line in progress: the engine that changed it last and still has words, so the room and the+ /// Mac take turns on the one caption.+ private func showLive(spoke src: String) {+ let room = !liveRoom.src.isEmpty && (liveMain.src.isEmpty || liveRoom.at > liveMain.at)+ let (visible, dst) = room ? (liveRoom.src, liveRoom.dst) : (liveMain.src, liveMain.dst)+ liveSource = visible+ liveTranslation = dst+ if !src.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { heardSpeech(); heardWords() }+ guard settings.displayMode == "bar" else { return }+ overlay.clearStatus()+ let shown = displayed(visible, dst)+ overlay.setSubtitle(source: shown.source, translation: shown.translation)+ }+private func recordHeard(_ seg: Segment, duration: Double) {guard let start = store.liveStart else { return }let t = max(0, Date().timeIntervalSince(start) - duration)@@ -1192,7 +1327,8 @@ final class AppModel: ObservableObject {let id = "h\(lineCounter)-\(seg.id)"lineForSegment[seg.id] = idstore.append(TranscriptLine(id: id, t: t, speaker: "them", src: seg.text, dst: translation ?? seg.translation,- srcLang: seg.sourceCode, dstLang: listen.resolvedTarget))+ srcLang: seg.sourceCode, dstLang: listen.resolvedTarget,+ via: seg.id >= ListenEngine.roomIDs ? "room" : nil))var kept = segkept.voiceSamples = nillastHeard = (kept, id)@@ -1629,6 +1765,20 @@ final class AppModel: ObservableObject {case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)case "speakFile": speak.speakFile(URL(fileURLWithPath: arg))case "speakVP": speak.echoCancel = arg != "off"+ case "voiceMicRun":+ // voiceMicRun:<on|off> runs the echo-cancelling unit with nobody listening (what it does to the rest).+ if arg == "off" { voiceMic.detach("debug") } else if let d = AudioDevices.roomMic {+ voiceMic.prepare(input: d.id) { [voiceMic] ok in+ debugLog("voiceMicRun: \(ok && voiceMic.attach("debug", input: d.id) { _ in } ? "running" : "failed")")+ }+ }+ case "roomEcho": roomEchoCancel = arg != "off"+ case "roomGate": roomEchoGate = arg != "off"+ case "hybridState":+ debugLog("hybrid state source=\(settings.listenSource) main=\(listen.isRunning) room=\(roomListen.isRunning) "+ + "echoCancelled=\(roomListen.hearsEchoCancelled) roomLang=\(roomListen.activeLang?.locale ?? "-") "+ + "mainLang=\(listen.activeLang?.locale ?? "-") held=\(heldRoom.count) voiceMic=\(voiceMic.inUse) "+ + String(format: "roomVoiced=%.1fs mainVoiced=%.1fs", roomListen.router.stats().voicedTotal, listen.router.stats().voicedTotal))case "speakTest":// speakTest:<sample|voice>: open settings › 同声传译 with the 试一句 sheet and run it.settingsSection = .speakdiff --git a/Sources/Cicada/AudioRouter.swift b/Sources/Cicada/AudioRouter.swiftindex 924b7ef..d1743c7 100644--- a/Sources/Cicada/AudioRouter.swift+++ b/Sources/Cicada/AudioRouter.swift@@ -72,6 +72,10 @@ final class AudioRouter: @unchecked Sendable {}}+ /// On this queue, for each block at the speech line (电脑和会议室 gates the room mic with it).+ private var onLoud: (() -> Void)?+ func setOnLoud(_ f: (() -> Void)?) { queue.async { [self] in onLoud = f } }+private var recordURL: URL?private var recorder: AVAudioFile?@@ -102,6 +106,8 @@ final class AudioRouter: @unchecked Sendable {let rms = (sum / Float(n)).squareRoot()peak = max(peak, rms)let seconds = Double(n) / mono.format.sampleRate+ // Before the onset is confirmed: the first 30 ms of a remote sentence are already echo in the room.+ if let onLoud, rms >= activity.gate.threshold { onLoud() }let voiced = activity.feed(UnsafeBufferPointer(start: data[0], count: n), rate: mono.format.sampleRate,clock: fed, pauses: sink != nil)diff --git a/Sources/Cicada/EchoMatch.swift b/Sources/Cicada/EchoMatch.swiftnew file mode 100644index 0000000..0bd7ed5--- /dev/null+++ b/Sources/Cicada/EchoMatch.swift@@ -0,0 +1,67 @@+import Foundation++/// 电脑和会议室's last line of defence against hearing a remote sentence twice: once from the Mac's+/// audio, once more from the speakers into the room mic. Echo cancellation and the gate stop most of+/// it; a room line still made mostly of what the Mac played around the same time is dropped. Feishu+/// dedupes across streams the same way (same time, text alike).+///+/// The room's copy is heard worse and cut differently, so it is matched by containment: how much of+/// the room line is found in the Mac's lines near it, in word pairs (characters for Chinese, Japanese+/// and Korean).+enum EchoMatch {+ struct Heard: Equatable {+ var text: String+ /// Wall-clock seconds (`CFAbsoluteTime`).+ var start: Double+ var end: Double+ }++ /// Seconds around the room line where the Mac's lines count.+ static let window = 3.0+ /// How long a room line waits for the Mac's line it may echo (the two recognizers end lines apart).+ static let hold = 2.5+ /// Share of the room line found in the Mac's lines that makes it an echo.+ static let contained = 0.6++ static func isEcho(_ room: Heard, online: [Heard]) -> Bool {+ let near = online.filter { $0.end >= room.start - window && $0.start <= room.end + window }+ guard !near.isEmpty else { return false }+ let r = units(room.text)+ guard !r.isEmpty else { return false }+ let o = near.map { units($0.text) }+ // A word or two ("OK", "对"): the very same words near it.+ if r.count <= 2 { return o.contains { $0 == r } }+ let mine = Set(pairs(r))+ let theirs = Set(o.flatMap(pairs))+ return Double(mine.intersection(theirs).count) / Double(mine.count) >= contained+ }++ /// Lower-case words, each CJK character on its own; punctuation and spacing don't count.+ static func units(_ text: String) -> [String] {+ var out: [String] = [], word = ""+ for c in text.lowercased() {+ if c.unicodeScalars.contains(where: cjk) {+ if !word.isEmpty { out.append(word); word = "" }+ out.append(String(c))+ } else if c.isLetter || c.isNumber {+ word.append(c)+ } else if !word.isEmpty {+ out.append(word)+ word = ""+ }+ }+ if !word.isEmpty { out.append(word) }+ return out+ }++ private static func pairs(_ u: [String]) -> [String] {+ u.count < 2 ? u : (1..<u.count).map { u[$0 - 1] + " " + u[$0] }+ }++ private static func cjk(_ s: Unicode.Scalar) -> Bool {+ switch s.value {+ case 0x3040...0x30FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xAC00...0xD7AF, 0xF900...0xFAFF: return true+ default: return false+ }+ }+}diff --git a/Sources/Cicada/ListenEngine.swift b/Sources/Cicada/ListenEngine.swiftindex c6c0f33..a55e34d 100644--- a/Sources/Cicada/ListenEngine.swift+++ b/Sources/Cicada/ListenEngine.swift@@ -18,8 +18,15 @@ struct Segment {/// System audio → language detection → on-device transcription → translation./// UI-free: it reports through the callbacks below.+/// 电脑和会议室 runs two: the main one on the Mac's audio, a `.room` one on the microphone, each+/// with its own language, pauses and model, as Feishu keeps online and room streams apart.@MainActorfinal class ListenEngine {+ enum Role { case main, room }+ /// Segment ids from here up are the room engine's.+ static let roomIDs = 1_000_000+ /// `.room`: the microphone side of 电脑和会议室 (no prompts, offers or remembered language).+ let role: Role// Outputsvar onSubtitle: ((_ source: String, _ translation: String) -> Void)?var onStatus: ((String) -> Void)?@@ -111,7 +118,9 @@ final class ListenEngine {private(set) var macSilent = falseprivate var recognizer: RecognitionStream?private var resultsTask: Task<Void, Never>?- private var generation = 0+ /// The room engine's clocks and segment ids start far above the main one's, so lines from the two+ /// never look like one recognizer's (joins, translations).+ private var generation: Intprivate var pendingSwitch: Lang?private var needsDetection = trueprivate var nextPeriodicDetection = 30.0@@ -150,7 +159,7 @@ final class ListenEngine {private var failureStreak = 0private var segments: [Segment] = []- private var nextSegmentID = 0+ private var nextSegmentID: Int/// Segments joined onto the line before: a retry of theirs would translate half a sentence.private var joinedAway: Set<Int> = []private var volatileText = ""@@ -172,8 +181,11 @@ final class ListenEngine {/// Final transcript time and how long after the last word it came, per segment, until its translation lands.private var finalTiming: [Int: (at: Date, recognize: Double?)] = [:]- init(settings: AppSettings) {+ init(settings: AppSettings, role: Role = .main) {self.settings = settings+ self.role = role+ generation = role == .room ? Self.roomIDs : 0+ nextSegmentID = role == .room ? Self.roomIDs : 0// A download that failed for want of a network resumes when there is one again.pathMonitor.pathUpdateHandler = { [weak self] path inlet up = path.status == .satisfied@@ -386,8 +398,12 @@ final class ListenEngine {@discardableResultprivate func startTap() -> Bool {- router.setRoomGate(settings.listensToRoom)- if settings.listensToRoom { return startRoomMic() }+ // Two restarts close together (the echo-cancelling unit made, then let go of) must not leave two sources.+ audioTap?.stop()+ audioTap = nil+ let room = role == .room || settings.listensToRoom+ router.setRoomGate(room)+ if room { return startRoomMic() }if SystemAudioPermission.status() == .denied {debugLog("audio tap: system audio recording was refused")isRunning = false@@ -419,7 +435,7 @@ final class ListenEngine {AVCaptureDevice.requestAccess(for: .audio) { [weak self] granted inDispatchQueue.main.async {MainActor.assumeIsolated {- guard let self, self.isRunning, self.settings.listensToRoom, self.audioTap == nil else { return }+ guard let self, self.isRunning, self.role == .room || self.settings.listensToRoom, self.audioTap == nil else { return }if granted { if self.startRoomMic() { self.setStatus(L("正在听")) } } else { self.roomMicDenied() }}}@@ -429,8 +445,26 @@ final class ListenEngine {roomMicDenied()return false}+ // 电脑和会议室: the remote voices from the speakers are taken out of the mic (`VoiceMic`).+ if role == .room, echoCancelled, let voiceMic, let device = roomDevice?() {+ let mic = EchoCancelledRoomMic(mic: voiceMic, device: device)+ mic.muted = roomMuted+ let router = self.router+ mic.onAudio = { pcm in router.push(pcm) }+ mic.onFailed = { [weak self] in+ DispatchQueue.main.async {+ MainActor.assumeIsolated { self?.echoCancellationFailed(mic) }+ }+ }+ try? mic.start()+ audioTap = mic+ return true+ }+ // A unit left over from echo cancellation would starve the plain mic (one unit or none).+ if let voiceMic, !voiceMic.inUse { voiceMic.release() }let mic = RoomMic(device: roomDevice?())mic.muted = roomMuted+ if role == .room { mic.echoGate = echoGate }let router = self.routermic.onAudio = { pcm in router.push(pcm) }do {@@ -452,6 +486,27 @@ final class ListenEngine {}}+ /// 电脑和会议室: take the online voices out of the room mic with the echo-cancelling unit. Off,+ /// or when the unit can't be had, the plain mic is gated while the Mac plays speech (`gateEcho`).+ var echoCancelled = true+ var voiceMic: VoiceMic?+ /// Whether the room is heard through the echo-cancelling unit right now.+ var hearsEchoCancelled: Bool { audioTap is EchoCancelledRoomMic }++ private func echoCancellationFailed(_ mic: EchoCancelledRoomMic) {+ guard isRunning, audioTap === mic else { return }+ mic.stop()+ audioTap = nil+ // Nobody else may hold the unit while the plain mic is used: it would starve it.+ if voiceMic?.inUse == false { voiceMic?.release() }+ echoCancelled = false+ if !startRoomMic() { debugLog("room mic: plain mic failed too") }+ }++ /// Closed by the main engine while the Mac plays speech: the plain room mic then hears silence,+ /// since what it hears is the speakers (unused through the echo-cancelling unit).+ let echoGate = EchoGate()+private func roomMicDenied() {debugLog("room mic: microphone not allowed")if isRunning { stop() }@@ -463,7 +518,8 @@ final class ListenEngine {guard on != roomMuted else { return }roomMuted = on(audioTap as? RoomMic)?.muted = on- if settings.listensToRoom { debugLog("room mic \(on ? "muted" : "open")") }+ (audioTap as? EchoCancelledRoomMic)?.muted = on+ if role == .room || settings.listensToRoom { debugLog("room mic \(on ? "muted" : "open")") }}/// 听哪里 changed: while listening, the new source takes over in the same meeting.@@ -851,7 +907,7 @@ final class ListenEngine {updateHold()flushUnconfirmed()pendingSwitch = nil- UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")+ if role == .main { UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected") }renderSubtitles()return}@@ -864,7 +920,7 @@ final class ListenEngine {languageConfirmed = trueunconfirmed = []pendingSwitch = nil- UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")+ if role == .main { UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected") }Task { await switchTranscriber(to: best.lang, replaySeconds: replay) }} else {pendingSwitch = best.lang@@ -973,7 +1029,7 @@ final class ListenEngine {unsureStreak = 0sureStreak = 0modelProblem = nil- UserDefaults.standard.set(lang.locale, forKey: "lastDetected")+ if role == .main { UserDefaults.standard.set(lang.locale, forKey: "lastDetected") }if lang == activeLang, recognizer != nil {updateHold()flushUnconfirmed()@@ -1102,7 +1158,7 @@ final class ListenEngine {cloudLang = langif settings.sourceMode == .auto, activeLang != lang {activeLang = lang- UserDefaults.standard.set(lang.locale, forKey: "lastDetected")+ if role == .main { UserDefaults.standard.set(lang.locale, forKey: "lastDetected") }}}@@ -1142,7 +1198,7 @@ final class ListenEngine {guard self.ticks % 4 == 0 else { return }self.translateVolatile()self.maybeDetectLanguage()- let silent = RoomPrompt.asks(room: self.settings.listensToRoom,+ let silent = self.role == .main && RoomPrompt.asks(room: self.settings.hearsRoom,listened: Date().timeIntervalSince(self.startedAt),voiced: self.router.stats().voicedTotal)if silent != self.macSilent {diff --git a/Sources/Cicada/RoomMic.swift b/Sources/Cicada/RoomMic.swiftindex 03872b9..76f07b4 100644--- a/Sources/Cicada/RoomMic.swift+++ b/Sources/Cicada/RoomMic.swift@@ -40,12 +40,13 @@ enum RoomMicPlan {struct VoiceGate {static let fixed: Float = 0.01static let lowest: Float = 0.0015- /// About a second of the mic's ~85 ms blocks.+ /// The mic tap's ~85 ms blocks to a second (the default length of a block). The echo-cancelling+ /// unit's are ~11 ms: the window is counted in seconds, not blocks.static let blocksPerSecond = 12var adaptive = falseprivate var quietest: [Float] = []private var second: Float = .infinity- private var blocks = 0+ private var elapsed = 0.0init(adaptive: Bool = false) { self.adaptive = adaptive }@@ -56,16 +57,16 @@ struct VoiceGate {return min(Self.fixed, max(Self.lowest, floor * 2))}- mutating func voiced(_ rms: Float) -> Bool {+ mutating func voiced(_ rms: Float, seconds: Double = 1.0 / Double(blocksPerSecond)) -> Bool {let on = rms >= thresholdguard adaptive else { return on }second = min(second, rms)- blocks += 1- if blocks >= Self.blocksPerSecond {+ elapsed += seconds+ if elapsed >= 1 - 1e-9 {quietest.append(second)if quietest.count > 30 { quietest.removeFirst() }second = .infinity- blocks = 0+ elapsed = 0}return on}@@ -111,11 +112,31 @@ extension AudioDevices {}}+/// 电脑和会议室 without echo cancellation: while the Mac plays speech, the room mic hears that speech+/// again from the speakers. The main engine's audio queue `hold`s the gate on every loud block of the+/// Mac's audio; the room mic hears silence until `hang` after the last one (the speakers' tail and the+/// room's echo). Room speech over a remote speaker is lost this way: what `VoiceMic` is for.+final class EchoGate: @unchecked Sendable {+ static let hang = 0.4+ private let lock = NSLock()+ private var until: Double = 0++ func hold(now: Double = CFAbsoluteTimeGetCurrent()) {+ lock.withLock { until = max(until, now + Self.hang) }+ }++ func closed(now: Double = CFAbsoluteTimeGetCurrent()) -> Bool {+ lock.withLock { now < until }+ }+}+/// A microphone as an audio source. While `muted`, silence goes on in its place: the Mac reading a/// translation aloud, or you holding the talk key, would otherwise come back as someone in the room./// Silence rather than nothing keeps the recognizer's clock and the recording in step.final class RoomMic: AudioSource {var onAudio: ((AVAudioPCMBuffer) -> Void)?+ /// 电脑和会议室 without echo cancellation: silence while the Mac plays speech.+ var echoGate: EchoGate?private var engine = AVAudioEngine()private let device: OutputDevice?private let lock = NSLock()@@ -175,7 +196,7 @@ final class RoomMic: AudioSource {out.frameLength = buf.frameLengthlet n = Int(buf.frameLength)let channels = Int(buf.format.channelCount)- if self.muted || channels == 0 || buf.floatChannelData == nil {+ if self.muted || self.echoGate?.closed() == true || channels == 0 || buf.floatChannelData == nil {dst.update(repeating: 0, count: n)} else if let src = buf.floatChannelData {dst.update(from: src[0], count: n)diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swiftindex 044967a..b35d5f3 100644--- a/Sources/Cicada/SessionStore.swift+++ b/Sources/Cicada/SessionStore.swift@@ -15,6 +15,8 @@ struct TranscriptLine: Codable, Identifiable, Equatable {var dstLang: String/// Which of the other side's voices said it (SpeakerID.swift); nil when unknown.var voice: Int? = nil+ /// 电脑和会议室: "room" when the room mic heard it; absent for the Mac's audio (or older records).+ var via: String? = nil}/// A name Ling found for a voice, and the line it is based on ("00:06 “Sure, Emma…”").diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swiftindex b15b854..86a764b 100644--- a/Sources/Cicada/Settings.swift+++ b/Sources/Cicada/Settings.swift@@ -174,11 +174,16 @@ final class AppSettings: ObservableObject {}/// Record per-sentence timings (never text) and show the 诊断 tab. On by default in dev builds.- /// 听哪里: "system" (what the Mac plays) or "room" (a real microphone, for a meeting in the room).+ /// 听哪里: "system" (what the Mac plays), "room" (a real microphone, for a meeting in the room) or+ /// "both" (电脑和会议室: people online and in the room, each heard on its own).@Published var listenSource: String {didSet { save() }}+ /// Only the room: nothing is in a call on this Mac (the translation is read out of the speakers).var listensToRoom: Bool { listenSource == "room" }+ /// The room mic is open: 会议室 or 电脑和会议室.+ var hearsRoom: Bool { listenSource != "system" }+ var hearsBoth: Bool { listenSource == "both" }@Published var diagnostics: Bool {didSet { save() }@@ -225,7 +230,7 @@ final class AppSettings: ObservableObject {endWithApp = defaults.object(forKey: "endWithApp") as? Bool ?? truesilenceEnd = defaults.string(forKey: "silenceEnd") ?? "prompt"silenceMinutes = defaults.object(forKey: "silenceMinutes") as? Double ?? 10- listenSource = defaults.string(forKey: "listenSource") == "room" ? "room" : "system"+ listenSource = ["room", "both"].contains(defaults.string(forKey: "listenSource")) ? defaults.string(forKey: "listenSource")! : "system"diagnostics = defaults.object(forKey: "diagnostics") as? Bool ?? DevBuild.isDevnotesCapturable = defaults.bool(forKey: "notesCapturable")// Off by default while it was an experiment, and save() stores every key, so a stored falsediff --git a/Sources/Cicada/SpeakEngine.swift b/Sources/Cicada/SpeakEngine.swiftindex b7950d6..d1768a7 100644--- a/Sources/Cicada/SpeakEngine.swift+++ b/Sources/Cicada/SpeakEngine.swift@@ -103,12 +103,13 @@ final class SpeakEngine {private(set) var phase: Phase = .idleprivate let mic = AVAudioEngine()- /// The mic with echo cancellation, tried first when `echoCancel` is on (`VoiceMic`).- private let voiceMic = VoiceMic()+ /// The mic with echo cancellation, shared with 电脑和会议室's room (`VoiceMic`): used when+ /// `echoCancel` is on, or whenever the room already has it running.+ private let voiceMic: VoiceMic/// Debug (`speakVP:on`) until a person has checked it with a real voice; off: the plain mic.var echoCancel = false {didSet {- if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel { voiceMic.release() }+ if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel, !voiceMic.inUse { voiceMic.release() }}}/// The real mic to cancel the echo for; nil when it is unknown or virtual (nothing to cancel there).@@ -144,12 +145,10 @@ final class SpeakEngine {/// Debug: also write synthesized speech here.var debugOutputURL: URL?- init(settings: AppSettings) {+ init(settings: AppSettings, voiceMic: VoiceMic) {self.settings = settings+ self.voiceMic = voiceMicwireOutput()- voiceMic.onUnitChanged = { [weak self] in- Task { @MainActor in self?.newOutputEngine() }- }}private func wireOutput() {@@ -164,7 +163,7 @@ final class SpeakEngine {/// Making or letting go of the echo-cancelling unit leaves an output engine that was already/// there silent for good (still running, no notification; a restart doesn't help), so the room/// would hear nothing: a new engine plays again. Not in the middle of a sentence.- private func newOutputEngine() {+ func newOutputEngine() {// `player.isPlaying` stays true after the last buffer: the phase says whether a sentence is going out.if phase == .speaking {DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in@@ -347,11 +346,11 @@ final class SpeakEngine {}private func startMic(format: AVAudioFormat, input cont: RecognitionStream) {- if echoCancel, let device = echoInput {+ if echoCancel || voiceMic.inUse, let device = echoInput {let conv = converterlet queue = micQueuefeeding = true- let started = voiceMic.start(input: device) { [weak self] buf in+ let started = voiceMic.attach("press", input: device) { [weak self] buf inqueue.async {guard let self, self.feeding, let c = conv.convert(buf, to: format) else { return }cont.append(c)@@ -362,7 +361,9 @@ final class SpeakEngine {debugLog("speak: mic \(started ? "with echo cancellation" : "plain, echo cancellation not ready")")if started { return }}- voiceMic.release() // a unit left over (toggled off mid-press, a virtual mic) would starve the plain mic+ // A unit left over (toggled off mid-press, a virtual mic) would starve the plain mic; one the+ // room is using stays (the talk key is then on another mic).+ if !voiceMic.inUse { voiceMic.release() }let inputNode = mic.inputNodeAudioDevices.pinInput(mic, to: inputDevice?())let inFormat = inputNode.outputFormat(forBus: 0)@@ -428,12 +429,12 @@ final class SpeakEngine {private func stopMic() {micQueue.sync { feeding = false }- voiceMic.stop()+ voiceMic.detach("press")if mic.isRunning {mic.inputNode.removeTap(onBus: 0)mic.stop()}- if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel { voiceMic.release() }+ if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel, !voiceMic.inUse { voiceMic.release() }}private func finishUtterance() {diff --git a/Sources/Cicada/Views.swift b/Sources/Cicada/Views.swiftindex 0088855..1976c7c 100644--- a/Sources/Cicada/Views.swift+++ b/Sources/Cicada/Views.swift@@ -193,8 +193,10 @@ struct MenuPanelView: View {UpdateBanner(updates: model.updates, model: model)VStack(spacing: 6) {- ChoiceRow(label: L("听哪里"), value: settings.listensToRoom ? L("会议室") : L("电脑声音"),- compact: true, options: [("system", L("电脑声音(线上会议、视频)")), ("room", L("会议室(用麦克风听桌边的人)"))]) {+ ChoiceRow(label: L("听哪里"), value: settings.listensToRoom ? L("会议室") : settings.hearsBoth ? L("电脑和会议室") : L("电脑声音"),+ compact: true, options: [("system", L("电脑声音(线上会议、视频)")), ("room", L("会议室(用麦克风听桌边的人)"))]+ // Two recognizers at once: macOS 26 only (14/15's interrupt each other).+ + (Recognition.legacy ? [] : [("both", L("电脑和会议室(线上和桌边的人都听)"))])) {model.listenSourceSelection = $0}ChoiceRow(label: L("听到"), value: heardValue.0, badge: heardValue.1, compact: true, sections: sourceSections) {diff --git a/Sources/Cicada/VoiceActivity.swift b/Sources/Cicada/VoiceActivity.swiftindex 1b2ee46..9253197 100644--- a/Sources/Cicada/VoiceActivity.swift+++ b/Sources/Cicada/VoiceActivity.swift@@ -66,7 +66,7 @@ struct VoiceActivity {// The room's line already sits at twice its noise: half of it is the fan, and speech would never end.let hold = gate.adaptive ? 1 : tuning.holdlet line = gate.threshold- let loud = gate.voiced(rms) || (speaking && rms >= line * hold)+ let loud = gate.voiced(rms, seconds: seconds) || (speaking && rms >= line * hold)if !loud {speaking = falsesilenceRun += pending + secondsdiff --git a/Sources/Cicada/VoiceMic.swift b/Sources/Cicada/VoiceMic.swiftindex 7e3648a..e9ab129 100644--- a/Sources/Cicada/VoiceMic.swift+++ b/Sources/Cicada/VoiceMic.swift@@ -2,10 +2,13 @@ import AVFoundationimport AudioToolboximport CoreAudio-/// The talk key's microphone with the system's echo cancellation (VoiceProcessingIO): with speakers-/// on, the meeting's own voices reach the mic, and Cicada would translate them and speak them back-/// into the room. Measured with a clip on the MacBook speakers at 60 %: 38–39 of 43 words recognized-/// from the bare mic, none through this.+/// The microphone with the system's echo cancellation (VoiceProcessingIO): with speakers on, the+/// online meeting's voices reach the mic. The talk key would translate them and speak them back, and+/// 电脑和会议室 would write each remote sentence twice. Measured with a clip on the MacBook speakers+/// at 60 %: 38–39 of 43 words recognized from the bare mic, none through this.+///+/// One unit in the process, or none: the room (listening the whole meeting) and the talk key (each+/// press) share it as consumers, and it runs while anyone is attached.////// The raw unit, because AVAudioEngine's voice processing fails ('bfmt') when the default input is/// the virtual mic, which 同声传译 makes it. Making the unit takes ~1.8 s, so it is made ahead and@@ -24,10 +27,12 @@ final class VoiceMic: @unchecked Sendable {private var builtFor: (input: AudioObjectID, output: AudioObjectID)?private var building = falseprivate var running = false- private var onAudio: ((AVAudioPCMBuffer) -> Void)?+ private var consumers: [String: (AVAudioPCMBuffer) -> Void] = [:]+ private var waiting: [(Bool) -> Void] = []private var scratch = [Float](repeating: 0, count: 8192)- /// After a unit is made or let go of: any output engine already running in this process is- /// silent from then on (measured: playing into BlackHole stops), and must be made anew.+ /// After a unit is made or let go of: audio already flowing in this process goes silent for good+ /// (measured: an output engine playing into BlackHole, and the system audio tap), and must be+ /// started anew.var onUnitChanged: (() -> Void)?deinit {@@ -37,56 +42,75 @@ final class VoiceMic: @unchecked Sendable {}}- /// Makes the unit for `input` and the current output in the background, unless it already is.- func prepare(input: AudioObjectID) {- guard let output = SystemAudioTap.defaultOutputDevice() else { return }+ /// Whether anyone is attached (then nobody may use the plain mic, which the unit starves).+ var inUse: Bool { lock.withLock { !consumers.isEmpty } }++ /// Makes the unit for `input` and the current output in the background, unless it already is;+ /// `then` hears whether it is ready (at once when it already was).+ func prepare(input: AudioObjectID, then: ((Bool) -> Void)? = nil) {+ guard let output = SystemAudioTap.defaultOutputDevice() else { then?(false); return }lock.lock()let ready = builtFor.map { $0 == (input, output) } ?? false- if ready || building { lock.unlock(); return }+ if ready { lock.unlock(); then?(true); return }+ if let then { waiting.append(then) }+ if building { lock.unlock(); return }building = truelock.unlock()queue.async { [self] inlet t0 = Date()let made = make(input: input, output: output)- lock.withLock {+ let (ok, told) = lock.withLock { () -> (Bool, [(Bool) -> Void]) inif let old = unit, !running { AudioComponentInstanceDispose(old); unit = nil; builtFor = nil }- if let made, unit == nil { unit = made; builtFor = (input, output) } else if let made { AudioComponentInstanceDispose(made) }+ var ok = false+ if let made, unit == nil { unit = made; builtFor = (input, output); ok = true } else if let made { AudioComponentInstanceDispose(made) }building = false+ defer { waiting = [] }+ return (ok, waiting)}- debugLog(String(format: "voice mic: %@ in %.1f s (input %u, output %u)", made == nil ? "failed" : "ready",+ debugLog(String(format: "voice mic: %@ in %.1f s (input %u, output %u)", ok ? "ready" : "failed",Date().timeIntervalSince(t0), input, output))onUnitChanged?()+ told.forEach { $0(ok) }}}- /// Starts hearing `input` if the unit is ready for it and the current output; otherwise false,- /// and the caller uses the plain mic for this press, then `prepare`s for the next.- func start(input: AudioObjectID, onAudio: @escaping (AVAudioPCMBuffer) -> Void) -> Bool {+ /// `key` hears `input` from now on, if the unit is ready for it and the current output (it starts+ /// with the first consumer). Otherwise false: the caller uses the plain mic this time, after+ /// `release` when nobody else is attached; a new unit is made later, not while the plain mic runs.+ func attach(_ key: String, input: AudioObjectID, onAudio: @escaping (AVAudioPCMBuffer) -> Void) -> Bool {guard let output = SystemAudioTap.defaultOutputDevice() else { return false }lock.lock()- guard let unit, let b = builtFor, b == (input, output), !running else {- let busy = running- lock.unlock()- // Made again after the press (`prepare`), not during it: a new unit would starve the plain mic.- if !busy { release() }- return false- }- self.onAudio = onAudio+ guard let unit, let b = builtFor, b == (input, output) else { lock.unlock(); return false }+ consumers[key] = onAudio+ let first = !runningrunning = truelock.unlock()+ guard first else { return true }let status = AudioOutputUnitStart(unit)if status != noErr {debugLog("voice mic: start failed \(status)")- lock.withLock { running = false; self.onAudio = nil; builtFor = nil }+ lock.withLock { running = false; consumers = [:]; builtFor = nil }return false}+ debugLog("voice mic: started for \(key)")return true}- /// Lets go of the unit (not while it runs), so the plain mic hears again.+ /// `key` stops hearing; the unit stops with the last consumer.+ func detach(_ key: String) {+ lock.lock()+ guard consumers.removeValue(forKey: key) != nil else { lock.unlock(); return }+ guard consumers.isEmpty, running, let unit else { lock.unlock(); return }+ running = false+ lock.unlock()+ AudioOutputUnitStop(unit)+ debugLog("voice mic: stopped (\(key) was the last)")+ }++ /// Lets go of the unit (not while anyone is attached), so the plain mic hears again.func release() {let old: AudioUnit? = lock.withLock {- guard !running, let u = unit else { return nil }+ guard !running, consumers.isEmpty, let u = unit else { return nil }unit = nilbuiltFor = nilreturn u@@ -98,15 +122,6 @@ final class VoiceMic: @unchecked Sendable {}}- func stop() {- lock.lock()- guard running, let unit else { lock.unlock(); return }- running = false- lock.unlock()- AudioOutputUnitStop(unit)- lock.withLock { onAudio = nil }- }-private func make(input: AudioObjectID, output: AudioObjectID) -> AudioUnit? {var desc = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_VoiceProcessingIO,componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)@@ -146,11 +161,59 @@ final class VoiceMic: @unchecked Sendable {var list = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 1, mDataByteSize: frames * 4, mData: p.baseAddress))return AudioUnitRender(unit, flags, ts, 1, frames, &list)}- guard status == noErr, let onAudio, let out = AVAudioPCMBuffer(pcmFormat: Self.format, frameCapacity: frames),+ let listeners = lock.withLock { Array(consumers.values) }+ guard status == noErr, !listeners.isEmpty, let out = AVAudioPCMBuffer(pcmFormat: Self.format, frameCapacity: frames),let dst = out.floatChannelData?[0] else { return status }out.frameLength = framesscratch.withUnsafeBufferPointer { dst.update(from: $0.baseAddress!, count: Int(frames)) }- onAudio(out)+ listeners.forEach { $0(out) }return noErr}}++/// 会议室 heard through the echo-cancelling unit (电脑和会议室): an `AudioSource` like `RoomMic`, so the+/// rest of listening is unchanged. The unit is made on `start` (~1.8 s, the room is heard from then);+/// `onFailed` says it couldn't be, and the caller falls back to the plain mic. While `muted` (the+/// Mac reading aloud, the talk key held), silence goes on in its place, as with `RoomMic`.+final class EchoCancelledRoomMic: AudioSource, @unchecked Sendable {+ var onAudio: ((AVAudioPCMBuffer) -> Void)?+ var onFailed: (() -> Void)?+ private let mic: VoiceMic+ private let device: OutputDevice+ private let lock = NSLock()+ private var _muted = false+ private var stopped = false+ var muted: Bool {+ get { lock.withLock { _muted } }+ set { lock.withLock { _muted = newValue } }+ }+ var deviceName: String { device.name }++ init(mic: VoiceMic, device: OutputDevice) {+ self.mic = mic+ self.device = device+ }++ func start() throws {+ mic.prepare(input: device.id) { [weak self] ok in+ guard let self, !self.lock.withLock({ self.stopped }) else { return }+ let attached = ok && self.mic.attach("room", input: self.device.id) { [weak self] buf in self?.deliver(buf) }+ if !attached {+ debugLog("room mic: echo cancellation unavailable, plain mic instead")+ self.onFailed?()+ } else {+ debugLog("room mic started with echo cancellation: \(self.device.name)")+ }+ }+ }++ func stop() {+ lock.withLock { stopped = true }+ mic.detach("room")+ }++ private func deliver(_ buf: AVAudioPCMBuffer) {+ if muted, let d = buf.floatChannelData?[0] { d.update(repeating: 0, count: Int(buf.frameLength)) }+ onAudio?(buf)+ }+}diff --git a/Tests/CicadaTests/HybridTests.swift b/Tests/CicadaTests/HybridTests.swiftnew file mode 100644index 0000000..98dbc75--- /dev/null+++ b/Tests/CicadaTests/HybridTests.swift@@ -0,0 +1,56 @@+import Foundation+import Testing+@testable import Cicada++@Suite struct EchoMatchTests {+ private func h(_ t: String, _ s: Double, _ e: Double) -> EchoMatch.Heard { .init(text: t, start: s, end: e) }++ @Test func theRoomsCopyOfARemoteSentenceIsAnEcho() {+ let online = [h("Revenue grew by 12%, mostly from the new region.", 10, 14)]+ // Heard worse from the speakers, and a word lost.+ #expect(EchoMatch.isEcho(h("revenue grew by 12% mostly from new region", 10.3, 14.2), online: online))+ }++ @Test func cutDifferentlyStillMatches() {+ let online = [h("我们先看一下这个季度的数据。", 0, 2), h("收入增长了百分之十二,主要来自新的市场。", 2.2, 5)]+ #expect(EchoMatch.isEcho(h("这个季度的数据收入增长了百分之十二", 0.8, 4), online: online))+ }++ @Test func roomSpeechIsKept() {+ let online = [h("Revenue grew by 12%, mostly from the new region.", 10, 14)]+ #expect(!EchoMatch.isEcho(h("I think we should check the numbers for Europe first", 11, 15), online: online))+ #expect(!EchoMatch.isEcho(h("我觉得应该先看一下欧洲的情况", 11, 15), online: online))+ }++ @Test func theSameWordsLongAfterAreNotAnEcho() {+ let online = [h("Can everyone hear me okay?", 0, 2)]+ #expect(!EchoMatch.isEcho(h("can everyone hear me okay", 20, 22), online: online))+ }++ @Test func shortLinesMatchOnlyExactly() {+ let online = [h("OK.", 5, 5.5)]+ #expect(EchoMatch.isEcho(h("ok", 5.2, 5.6), online: online))+ #expect(!EchoMatch.isEcho(h("no", 5.2, 5.6), online: online))+ }++ @Test func gateClosesForTheHang() {+ let g = EchoGate()+ #expect(!g.closed(now: 100))+ g.hold(now: 100)+ #expect(g.closed(now: 100.3))+ #expect(!g.closed(now: 100 + EchoGate.hang + 0.01))+ }+}++@Suite struct VoiceGateBlockTests {+ /// The echo-cancelling unit's ~11 ms blocks learn the room's floor per second, as the mic tap's do.+ @Test func smallBlocksLearnTheFloorPerSecond() {+ var g = VoiceGate(adaptive: true)+ let block = 171.0 / 16000+ // Ten seconds of talk at 0.012, one quiet block (0.002) in each second.+ for i in 0..<Int(10 / block) { _ = g.voiced(i % 94 == 0 ? 0.002 : 0.012, seconds: block) }+ #expect(g.threshold < 0.006)+ let voice = g.voiced(0.012, seconds: block)+ #expect(voice)+ }+}diff --git a/site/changelog.json b/site/changelog.jsonindex 3d6c087..75c0b84 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -6,6 +6,14 @@"summary": "修复 Windows、Linux、Android 上说话声音较小时被当成底噪、不出字幕的问题;修复 Linux 设置里不出现 key 输入框的问题。","image": null,"items": [+ {+ "kind": "new",+ "platforms": [+ "mac"+ ],+ "title": "“听哪里”多了“电脑和会议室”:线上和桌边的人一起听,同一句话不记两遍。",+ "text": "线上的人从电脑声音听,桌边的人从麦克风听,各认各的语言。扬声器里的线上声音用 macOS 的回声消除从麦克风里去掉,桌边的人插话也能记下;用不了时线上有人说话那一会儿麦克风先不听,最后再按文字去掉重复的一句。"+ },{"kind": "new","platforms": [diff --git a/tools/README.md b/tools/README.mdindex aa76095..7c0a37d 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>`(room 用麦克风听会议室,日志里 `room mic started: <设备>`,念译文时 `room mic muted` / `open`),`roomPrompt:<room|no>` 等于在“在会议室里开会?”里点“改听会议室”或“不是”(听电脑 60 秒没声音才出现,日志 `mac silent true`)+ - 听哪里:`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`)- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步- 会议软件的麦克风:`micUsers` 把每个读麦克风的进程和列表写进日志,`micGuide:<bundle id 或名字>` 打开怎么改,`micGuideRender:<bundle id>=<png>`@@ -22,7 +22,7 @@- 导入录音或视频:`import:<路径>[,<路径>…]`(等于拖进会议记录窗口),`importState` 把进度写进日志,`importCancel` 停止转写,`importRetry:<会议 id>[=<locale>]` 重新转写(带 locale 等于在“这场会议只留下了录音”里选了这种语言),`importNotify` 把通知权限写进日志- 新手引导与窗口:`onboarding:<步骤>[,skip|ask|setup]`(1–5,5 是收尾页;skip 是第 3 步点了“先不接”,ask / setup 是第 4 步的二选一 / 清单)、`samplePlay`、`speakers:<on|off>`(“说话人识别”)、`speakerGuess:<会议 id>`(马上让 Ling 认一遍名字)、`speakersRender:<会议 id>=<png>`、`voiceprintFile:<音频>=<json>`(用 app 里的声纹模型算整个文件的声纹,和参考模型对比)、`closeWindow:<main|settings|onboarding>`、`settings:<overlay|language|speak|records|ai|diagnostics>`、`about`- 显示与字幕:`display:<notes|bar|none>`、`subtitles:<both|translation|original>`、`meetingSubtitles:<…>`、`overlayState`、`overlayToggle`、`pillClick`(等于点主窗口顶部的“正在听”)、`overlayAuto[:off]`、`hideAfter:<秒>`- - 纪要:`notesLang:<mine|source>`、`meetingNotesLang:<…>`、`notesRegenerate:<id>=<mine|source>`、`notesWindow[:x,y,w,h]`、`notesClose`、`notesMinimize`、`notesFrame`、`notesNow`、`notesState`、`notesShow:<id>`、`notesReplay:<id>`、`notesCapturable[:off]`(只改窗口能否被截屏)、`notesShare:<on|off>`(改“共享屏幕时让对方看到”这个设置,等于点图标或开关)+ - 纪要:`notesLang:<mine|source>`、`meetingNotesLang:<…>`、`notesRegenerate:<id>=<mine|source>`、`notesWindow[:x,y,w,h]`、`notesClose`、`notesMinimize`、`notesFrame`、`notesNow`、`notesState`、`notesShow:<id>`、`notesReplay:<id>[,<每次几句>]`(按会议时的节奏重写一遍纪要,默认每次 4 句;回复被 max_tokens 截断时日志写 `cut at max_tokens`)、`notesCapturable[:off]`(只改窗口能否被截屏)、`notesShare:<on|off>`(改“共享屏幕时让对方看到”这个设置,等于点图标或开关)- 结束会议:`endSim:<应用名>[,…]` 假装这些会议应用在通话(`endSim:` 全部挂断,`endSim:off` 回到真实情况),`endTimes:<静默秒>,<倒计时秒>,<挂断宽限秒>` 缩短等待(`endTimes:` 回到设置),`endKeep` 等于点“继续记录”,`endState` 写进日志- 渲染(不需要录屏权限):`panelRender:<png>`(菜单栏面板,离屏画)、`windowsRender:<目录>`、`settingsRender:<栏目>=<png>`、`notesRender:<png>`、`mainShow:<id>[,transcript]`、`mainWindow:x,y,宽,高`(摆好主窗口并暂时浮在最上层,方便模拟点击;不带参数恢复)、`mainRender:<png>`、`speakTestRender:<png>`- AI:`aiKeyFile:<路径>`(从 0600 文件读 key,不经过日志;测完就删掉文件)、`aiCheck`、`aiRemove`、`aiHide:<on|off>`(只在内存里当作没有 key,文件不动;用于截图)、`aiState`、`lingSimulate:<429|hijack|timeout|off>`、`translateFail:<n>`(接下来 n 句在所有翻译来源都失败,用来测重试)