知了 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
chore: optional echo cancellation for the talk key's mic, off by default (lsctl speakVP:on)
wquguru2d83529cd47d
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex f4fc3cb..1d1b361 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -1628,6 +1628,7 @@ final class AppModel: ObservableObject {case "speakOff": enableSpeaking(false)case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)case "speakFile": speak.speakFile(URL(fileURLWithPath: arg))+ case "speakVP": speak.echoCancel = arg != "off"case "speakTest":// speakTest:<sample|voice>: open settings › 同声传译 with the 试一句 sheet and run it.settingsSection = .speakdiff --git a/Sources/Cicada/SpeakEngine.swift b/Sources/Cicada/SpeakEngine.swiftindex 69c5096..b7950d6 100644--- a/Sources/Cicada/SpeakEngine.swift+++ b/Sources/Cicada/SpeakEngine.swift@@ -103,6 +103,19 @@ 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()+ /// 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() }+ }+ }+ /// The real mic to cancel the echo for; nil when it is unknown or virtual (nothing to cancel there).+ private var echoInput: AudioObjectID? {+ guard let d = inputDevice?(), !d.isVirtualMic else { return nil }+ return d.id+ }private let micQueue = DispatchQueue(label: "com.wquguru.cicada.mic", qos: .userInitiated)private let converter = PCMConverter()private var analyzerFormat: AVAudioFormat?@@ -121,8 +134,9 @@ final class SpeakEngine {private nonisolated static let pressLimit = 16_000 * 60private let synth = AVSpeechSynthesizer()- private let out = AVAudioEngine()- private let player = AVAudioPlayerNode()+ private var out = AVAudioEngine()+ private var player = AVAudioPlayerNode()+ private var outObserver: NSObjectProtocol?private var outFormat: AVAudioFormat?private var outDeviceUID: String?/// The device the latest `speak` call played to.@@ -132,14 +146,43 @@ final class SpeakEngine {init(settings: AppSettings) {self.settings = settings+ wireOutput()+ voiceMic.onUnitChanged = { [weak self] in+ Task { @MainActor in self?.newOutputEngine() }+ }+ }++ private func wireOutput() {out.attach(player)// Pointing the output at a device (the first sentence, BlackHole installed, headphones// plugged in) stops the engine, and the player stays silent until it is wired up again.- NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: out, queue: .main) { [weak self] _ in+ outObserver = NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: out, queue: .main) { [weak self] _ inMainActor.assumeIsolated { self?.outputChanged() }}}+ /// 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() {+ // `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+ MainActor.assumeIsolated { self?.newOutputEngine() }+ }+ return+ }+ if let outObserver { NotificationCenter.default.removeObserver(outObserver) }+ player.stop()+ out.stop()+ out = AVAudioEngine()+ player = AVAudioPlayerNode()+ outFormat = nil+ outDeviceUID = nil+ wireOutput()+ debugLog("voice output: new engine after the voice mic changed")+ }+var targetCode: String {if settings.speakTo != "room" { return settings.speakTo }let room = roomLanguage?() ?? "en"@@ -168,6 +211,7 @@ final class SpeakEngine {analyzerFormat = await Recognition.format(lang.locale, drafts: true)analyzerLocale = lang.localedebugLog("speak transcriber ready locale=\(lang.locale)")+ if echoCancel, let d = echoInput { voiceMic.prepare(input: d) }} catch {debugLog("speak transcriber failed: \(error)")onStatus?(L("无法准备语音识别:\(error.localizedDescription)"))@@ -303,6 +347,22 @@ final class SpeakEngine {}private func startMic(format: AVAudioFormat, input cont: RecognitionStream) {+ if echoCancel, let device = echoInput {+ let conv = converter+ let queue = micQueue+ feeding = true+ let started = voiceMic.start(input: device) { [weak self] buf in+ queue.async {+ guard let self, self.feeding, let c = conv.convert(buf, to: format) else { return }+ cont.append(c)+ self.recordMic(c)+ self.keepForMing(c)+ }+ }+ 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 miclet inputNode = mic.inputNodeAudioDevices.pinInput(mic, to: inputDevice?())let inFormat = inputNode.outputFormat(forBus: 0)@@ -368,10 +428,12 @@ final class SpeakEngine {private func stopMic() {micQueue.sync { feeding = false }+ voiceMic.stop()if mic.isRunning {mic.inputNode.removeTap(onBus: 0)mic.stop()}+ if echoCancel, let d = echoInput { voiceMic.prepare(input: d) } else if !echoCancel { voiceMic.release() }}private func finishUtterance() {diff --git a/Sources/Cicada/VoiceMic.swift b/Sources/Cicada/VoiceMic.swiftnew file mode 100644index 0000000..7e3648a--- /dev/null+++ b/Sources/Cicada/VoiceMic.swift@@ -0,0 +1,156 @@+import AVFoundation+import AudioToolbox+import 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 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+/// only started (~40 ms) and stopped per press; made but stopped, it doesn't hold the mic open, but+/// it does starve AVAudioEngine's input on the same mic (−56 dB peaks): it is let go of before the+/// plain mic is used.+/// AGC is off (it lifts the room's noise with the voice, which recognition likes less), and other+/// audio's ducking is set to its minimum: the meeting must stay audible while you talk.+final class VoiceMic: @unchecked Sendable {+ static let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)!++ private let queue = DispatchQueue(label: "com.wquguru.cicada.voicemic")+ private let lock = NSLock()+ private var unit: AudioUnit?+ /// The devices the unit was made for: another mic or output means making it again.+ private var builtFor: (input: AudioObjectID, output: AudioObjectID)?+ private var building = false+ private var running = false+ private var onAudio: ((AVAudioPCMBuffer) -> 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.+ var onUnitChanged: (() -> Void)?++ deinit {+ if let unit {+ AudioOutputUnitStop(unit)+ AudioComponentInstanceDispose(unit)+ }+ }++ /// 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 }+ lock.lock()+ let ready = builtFor.map { $0 == (input, output) } ?? false+ if ready || building { lock.unlock(); return }+ building = true+ lock.unlock()+ queue.async { [self] in+ let t0 = Date()+ let made = make(input: input, output: output)+ lock.withLock {+ if 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) }+ building = false+ }+ debugLog(String(format: "voice mic: %@ in %.1f s (input %u, output %u)", made == nil ? "failed" : "ready",+ Date().timeIntervalSince(t0), input, output))+ onUnitChanged?()+ }+ }++ /// 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 {+ 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+ running = true+ lock.unlock()+ let status = AudioOutputUnitStart(unit)+ if status != noErr {+ debugLog("voice mic: start failed \(status)")+ lock.withLock { running = false; self.onAudio = nil; builtFor = nil }+ return false+ }+ return true+ }++ /// Lets go of the unit (not while it runs), so the plain mic hears again.+ func release() {+ let old: AudioUnit? = lock.withLock {+ guard !running, let u = unit else { return nil }+ unit = nil+ builtFor = nil+ return u+ }+ if let old {+ AudioComponentInstanceDispose(old)+ debugLog("voice mic: released")+ onUnitChanged?()+ }+ }++ 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)+ guard let comp = AudioComponentFindNext(nil, &desc) else { return nil }+ var made: AudioUnit?+ guard AudioComponentInstanceNew(comp, &made) == noErr, let u = made else { return nil }+ func set<T>(_ property: AudioUnitPropertyID, _ scope: AudioUnitScope, _ element: AudioUnitElement, _ value: T) -> Bool {+ let status = withUnsafeBytes(of: value) {+ AudioUnitSetProperty(u, property, scope, element, $0.baseAddress, UInt32($0.count))+ }+ if status != noErr { debugLog("voice mic: property \(property) failed \(status)") }+ return status == noErr+ }+ // Element 1 is the mic, element 0 the output the echo is heard against.+ var ok = set(kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 1, input)+ && set(kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, output)+ _ = set(kAUVoiceIOProperty_VoiceProcessingEnableAGC, kAudioUnitScope_Global, 0, UInt32(0))+ _ = set(kAUVoiceIOProperty_OtherAudioDuckingConfiguration, kAudioUnitScope_Global, 0,+ AUVoiceIOOtherAudioDuckingConfiguration(mEnableAdvancedDucking: false, mDuckingLevel: .min))+ let asbd = Self.format.streamDescription.pointee+ ok = ok && set(kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, asbd)+ && set(kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, asbd)+ ok = ok && set(kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0,+ AURenderCallbackStruct(inputProc: { ref, flags, ts, _, frames, _ in+ Unmanaged<VoiceMic>.fromOpaque(ref).takeUnretainedValue().render(flags, ts, frames)+ }, inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()))+ if ok, AudioUnitInitialize(u) == noErr { return u }+ AudioComponentInstanceDispose(u)+ return nil+ }++ /// On the real-time thread, as `SystemAudioTap.render`.+ private func render(_ flags: UnsafeMutablePointer<AudioUnitRenderActionFlags>, _ ts: UnsafePointer<AudioTimeStamp>,+ _ frames: UInt32) -> OSStatus {+ guard let unit, frames > 0, Int(frames) <= scratch.count else { return noErr }+ let status = scratch.withUnsafeMutableBufferPointer { p -> OSStatus in+ 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 dst = out.floatChannelData?[0] else { return status }+ out.frameLength = frames+ scratch.withUnsafeBufferPointer { dst.update(from: $0.baseAddress!, count: Int(frames)) }+ onAudio(out)+ return noErr+ }+}diff --git a/tools/README.md b/tools/README.mdindex fbb8f98..aa76095 100644--- a/tools/README.md+++ b/tools/README.md@@ -14,7 +14,7 @@- 快捷键:`talkKey:right` 或 `talkKey:<keyCode>:<Carbon 修饰键>` 换说话键(被拒的原因写进日志),`toggleKey:…` 同理,`shortcuts` 把当前状态写进日志- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置- 系统麦克风:`sysMic` 把状态、默认输入、要换回的麦克风和知了实际在录的麦克风写进日志,`sysMicSet:<设备名片段>` 假装别人改了系统麦克风,`sysMicRestore` 还原,`sysMicSwitch` 换成虚拟麦克风,`sysMicAuto:<on|off>`,`speakMic:<设备名片段>` 固定知了用的麦克风(留空 = 自动)。会改本机的系统麦克风:测完 `sysMicRestore` 或退出 App- - 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风)+ - 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风),`speakVP:<on|off>` 按键说话时用带回声消除的麦克风(默认关;日志 `voice mic: ready`、`speak: mic with echo cancellation`)- 试一句:`speakTest:sample`(Mac 读一句示例)或 `speakTest:voice`(再发 `speakTestBegin` / `speakTestEnd` 当作按住、松开),结果以 `speak test:` 写进日志;`speakTestState`、`speakTestRender:<png>`、`speakTestClose`- 识别引擎:`recognizer:legacy` 在 macOS 26 上改用 14 / 15 的识别(`SFSpeechRecognizer`,第一次会要“语音识别”权限),`recognizer:auto` 换回;下一次开始听起生效(或启动时 `open --env CICADA_RECOGNIZER=legacy`),日志里 `transcriber started recognizer=…`- 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`