知了 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: Run on macOS 14.4 and 15, with the older on-device speech recognizer
wquguru900c36e3ac1c
diff --git a/.gitignore b/.gitignoreindex 8444840..af68da2 100644--- a/.gitignore+++ b/.gitignore@@ -20,6 +20,7 @@ test-shots/tools/*!tools/*.swift!tools/README.md+!tools/macos-vm/# Windows: build output, spike results and clips (windows/spike/make-clips.sh, ming_asr.py)windows/**/bin/diff --git a/Package.swift b/Package.swiftindex a5ab42d..cdb9434 100644--- a/Package.swift+++ b/Package.swift@@ -3,7 +3,7 @@ import PackageDescriptionlet package = Package(name: "LiveSubs",- platforms: [.macOS("26.0")],+ platforms: [.macOS("14.4")],targets: [.executableTarget(name: "LiveSubs", path: "Sources/LiveSubs"),.executableTarget(name: "LiveSubsIcon", path: "Sources/LiveSubsIcon"),diff --git a/README.en.md b/README.en.mdindex 9b2df58..89940d8 100644--- a/README.en.md+++ b/README.en.md@@ -16,7 +16,7 @@</p><p align="center">- <img src="https://img.shields.io/badge/macOS-26%2B-black" alt="macOS 26+">+ <img src="https://img.shields.io/badge/macOS-14.4%2B-black" alt="macOS 14.4+"><img src="https://img.shields.io/badge/Apple%20silicon-only-black" alt="Apple silicon"><img src="https://img.shields.io/badge/Swift-5-orange" alt="Swift 5"><img src="https://img.shields.io/badge/license-Apache--2.0-blue" alt="Apache-2.0">@@ -58,7 +58,7 @@ Every session saves its bilingual transcript, notes, and audio recording on your## Privacy & Permissions-Audio capture, language detection, speech recognition (Apple SpeechAnalyzer), and meeting recordings all stay on your Mac. The only data that leaves your device is the recognized text sent for translation and meeting notes, plus the short audio clips you speak while holding the talk key when using a Ling API key. Without an API key, subtitles, translation (via Google with Apple on-device fallback), meeting records, and push-to-talk interpreting all work. Live meeting notes, one-step voice translation, and voice cloning use your own Ling API key (Ant Group's model service, see [below](#ling-api-key)), and an hour of live notes costs roughly ¥0.15 to ¥1 at current Ling pricing. Ling gives ¥10 of credit every month, enough for about 10 to 50 hours of meetings.+Audio capture, language detection, speech recognition (Apple SpeechAnalyzer; on macOS 14.4–15, SFSpeechRecognizer in on-device mode), and meeting recordings all stay on your Mac. The only data that leaves your device is the recognized text sent for translation and meeting notes, plus the short audio clips you speak while holding the talk key when using a Ling API key. Without an API key, subtitles, translation (via Google, with Apple on-device fallback on macOS 26), meeting records, and push-to-talk interpreting all work. Live meeting notes, one-step voice translation, and voice cloning use your own Ling API key (Ant Group's model service, see [below](#ling-api-key)), and an hour of live notes costs roughly ¥0.15 to ¥1 at current Ling pricing. Ling gives ¥10 of credit every month, enough for about 10 to 50 hours of meetings.Cicada asks for a permission only when you use the feature that needs it, and everything else keeps working if you decline.@@ -80,9 +80,9 @@ Without a Ling key, everything runs on Apple's on-device models plus Google Tran| Feature | With a Ling key | Without a key / fallback ||---|---|---|-| Speech recognition and language detection | Apple `SpeechAnalyzer` / `SpeechTranscriber` (on device) | same |-| Translating finished sentences | Ling `Ling-3.1-flash` (or `Ling-3.0-flash`, set in Settings › AI Service) | Google Translate → Apple `Translation` (on device) |-| Translating the sentence still being spoken | Google Translate (saves Ling's rate limit) | Apple `Translation` (on device) |+| Speech recognition and language detection | Apple `SpeechAnalyzer` / `SpeechTranscriber` (on device); macOS 14.4–15: `SFSpeechRecognizer` (on device, needs Dictation) | same |+| Translating finished sentences | Ling `Ling-3.1-flash` (or `Ling-3.0-flash`, set in Settings › AI Service) | Google Translate → Apple `Translation` (on device, macOS 26 only) |+| Translating the sentence still being spoken | Google Translate (saves Ling's rate limit) | Apple `Translation` (on device, macOS 26 only) || Live notes and the final version | Ling `Ling-3.1-flash` (same setting) | not available || Checking the key | Ling `Ling-3.0-tiny` (one token) | — || Interpreting: hearing and translating what you say | Ming `Ming-3.0-audio-flash`, one step | Apple on-device transcript, then the translation chain above |@@ -99,7 +99,7 @@ Without a Ling key, everything runs on Apple's on-device models plus Google Tran## Requirements & Installation-Requires **macOS 26 or later** on **Apple silicon**. The UI is available in English, Chinese, Japanese, and Korean, following your macOS language or set per app in **System Settings › General › Language & Region**.+Requires **macOS 14.4 or later** on **Apple silicon**. macOS 26 uses the newer on-device speech recognizer, which is more accurate; on 14.4–15 Cicada uses the system's earlier recognizer, which needs **Dictation** turned on in **System Settings › Keyboard**, with each language you want heard added to its languages. The UI is available in English, Chinese, Japanese, and Korean, following your macOS language or set per app in **System Settings › General › Language & Region**.Download `Cicada-<version>-macOS-AppleSilicon.dmg` from [Releases](https://github.com/wquguru/cicada/releases/latest) or [the website](https://cicada.indaloop.app), open it, and drag **Cicada** into **Applications**. Builds are ad-hoc signed and not notarized yet (see [roadmap](#roadmap)), so if macOS blocks the first launch, open **System Settings › Privacy & Security** and click **Open Anyway**. Each release includes `checksums.txt`, which you can verify with `shasum -a 256 Cicada-*.dmg`. For questions, reach out to the author [@wquguru](https://x.com/wquguru) on X.@@ -114,7 +114,6 @@ The first-launch guide asks for one permission, plays a short two-person sampleIn rough order; tell us what you need in Issues.- **Recording what you say**, listening to your microphone during meetings with echo cancellation so your own proposals and to-dos are included in the transcript and notes.-- **Older macOS support (targeting macOS 14.4+)**, falling back to earlier system speech recognition and translation APIs on older versions.- **Developer ID signing and notarization**, removing the "Open Anyway" prompt on first launch and storing the AI key in the macOS Keychain.- **Speaker recognition**, building on today's experimental speaker identification to remember frequent meeting participants by voice on your Mac, so they're named in the next meeting too.- **Local notes without an API key** using Apple's on-device model on supported Macs, plus **custom AI providers** for any OpenAI-compatible endpoint.diff --git a/README.md b/README.mdindex 5897f6c..1e7a801 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@</p><p align="center">- <img src="https://img.shields.io/badge/macOS-26%2B-black" alt="macOS 26+">+ <img src="https://img.shields.io/badge/macOS-14.4%2B-black" alt="macOS 14.4+"><img src="https://img.shields.io/badge/Apple%20silicon-only-black" alt="Apple 芯片"><img src="https://img.shields.io/badge/Swift-5-orange" alt="Swift 5"><img src="https://img.shields.io/badge/license-Apache--2.0-blue" alt="Apache-2.0">@@ -58,7 +58,7 @@## 隐私与权限-声音采集、语言识别、语音识别(Apple SpeechAnalyzer)和会议录音全部在本机完成。会离开电脑的只有识别出来的文字(发去做翻译和生成纪要),以及填了 Ling API key 并按住说话键用同声传译时你说的那几句语音。不填 API key 时,实时字幕、翻译(走 Google 或退回 Apple 本机翻译)、会议记录和同声传译都能正常用。实时纪要、一步语音翻译和声音克隆需要你自己的 Ling(蚂蚁集团的大模型服务)API key(配置方法见[下文](#配置-ling-api-key)),开一小时会大约花 0.15 到 1 元人民币,Ling 每月赠送 10 元额度,约够 10 到 50 小时会议。+声音采集、语言识别、语音识别(Apple SpeechAnalyzer,macOS 14.4–15 上是 SFSpeechRecognizer 的本机模式)和会议录音全部在本机完成。会离开电脑的只有识别出来的文字(发去做翻译和生成纪要),以及填了 Ling API key 并按住说话键用同声传译时你说的那几句语音。不填 API key 时,实时字幕、翻译(走 Google 或退回 Apple 本机翻译,本机翻译只在 macOS 26 上有)、会议记录和同声传译都能正常用。实时纪要、一步语音翻译和声音克隆需要你自己的 Ling(蚂蚁集团的大模型服务)API key(配置方法见[下文](#配置-ling-api-key)),开一小时会大约花 0.15 到 1 元人民币,Ling 每月赠送 10 元额度,约够 10 到 50 小时会议。知了只在用到某项功能时才请求对应的权限,拒绝后其他功能照常可用。@@ -80,9 +80,9 @@| 功能 | 填了 Ling key | 不填 key / 退回 ||---|---|---|-| 语音识别、语言识别 | Apple `SpeechAnalyzer` / `SpeechTranscriber`(本机) | 同左 |-| 整句翻译 | Ling `Ling-3.1-flash`(可在“设置 › AI 服务”改为 `Ling-3.0-flash`) | Google 翻译 → Apple `Translation`(本机) |-| 正在说的半句话的翻译 | Google 翻译(不占 Ling 的频率额度) | Apple `Translation`(本机) |+| 语音识别、语言识别 | Apple `SpeechAnalyzer` / `SpeechTranscriber`(本机);macOS 14.4–15 是 `SFSpeechRecognizer`(本机,要打开听写) | 同左 |+| 整句翻译 | Ling `Ling-3.1-flash`(可在“设置 › AI 服务”改为 `Ling-3.0-flash`) | Google 翻译 → Apple `Translation`(本机,仅 macOS 26) |+| 正在说的半句话的翻译 | Google 翻译(不占 Ling 的频率额度) | Apple `Translation`(本机,仅 macOS 26) || 实时纪要、会后完整版 | Ling `Ling-3.1-flash`(同上设置) | 不可用 || 检查 key 是否有效 | Ling `Ling-3.0-tiny`(只用一个 token) | — || 同声传译:听懂并翻译你说的话 | Ming `Ming-3.0-audio-flash`,一步完成 | Apple 本机识别,再走上面的翻译链 |@@ -98,7 +98,7 @@## 系统要求与安装-需要 macOS 26 或更新版本、Apple 芯片的 Mac。界面有中文、英文、日文和韩文,默认跟随系统语言,也可以在系统设置的语言与地区里单独给知了指定。+需要 macOS 14.4 或更新版本、Apple 芯片的 Mac。macOS 26 上用新的本机语音识别,更准;14.4–15 上用系统较早的识别,要在系统设置 › 键盘里打开“听写”,并把要听的语言加进听写语言。界面有中文、英文、日文和韩文,默认跟随系统语言,也可以在系统设置的语言与地区里单独给知了指定。从 [Releases 页面](https://github.com/wquguru/cicada/releases/latest) 或 [官网](https://cicada.indaloop.app) 下载 `Cicada-<版本>-macOS-AppleSilicon.dmg`,打开后把知了拖进应用程序文件夹。应用目前是本地签名,还没有苹果公证(见[路线图](#路线图)),第一次打开被拦下时,去系统设置的隐私与安全性里点仍要打开。下载页同时提供 `checksums.txt`,可以用 `shasum -a 256 Cicada-*.dmg` 核对。有疑问可以去 X 找作者 [@wquguru](https://x.com/wquguru)。@@ -113,7 +113,6 @@按先后排,想要哪一项欢迎在 Issues 里说。- **记录我的发言**,开会时持续听麦克风并做回声消除,把你直接开口说的话也记进文字记录和纪要。-- **支持更早的 macOS(14.4 起)**,在旧系统上改用较早的系统语音识别与翻译接口。- **正式签名与公证**,首次打开不再需要点仍要打开,AI key 也能放回系统钥匙串。- **声纹识别**,在现有的说话人识别基础上,在本机记住常一起开会的人的声音,下次开会也能自动认出。- **不用 key 也有纪要**,在支持的 Mac 上用 Apple 本机模型整理纪要,以及**自选 AI 服务**接入其他兼容 OpenAI 接口的服务。diff --git a/Resources/Info.plist b/Resources/Info.plistindex ec9ba24..8593aee 100644--- a/Resources/Info.plist+++ b/Resources/Info.plist@@ -35,7 +35,7 @@<key>LSHasLocalizedDisplayName</key><true/><key>LSMinimumSystemVersion</key>- <string>26.0</string>+ <string>14.4</string><key>LSUIElement</key><false/><key>NSAudioCaptureUsageDescription</key>diff --git a/Sources/LiveSubs/AISettings.swift b/Sources/LiveSubs/AISettings.swiftindex 2c4f393..a265313 100644--- a/Sources/LiveSubs/AISettings.swift+++ b/Sources/LiveSubs/AISettings.swift@@ -18,7 +18,8 @@ struct AISettingsView: View {usageRow(L("实时纪要"), tag: ling.usable ? L("用 Ling") : L("需要 key"), on: ling.usable,note: ling.usable ? L("会中每 45 秒更新") : L("填好 key 后可用"))usageRow(L("翻译"), tag: ling.usable ? L("用 Ling") : "Google", on: ling.usable,- note: ling.usable ? L("整句用 Ling;不行时换 Google、本机") : L("没有 key 时照常可用"))+ note: ling.usable ? (Recognition.hasOnDeviceTranslation ? L("整句用 Ling;不行时换 Google、本机") : L("整句用 Ling;不行时换 Google"))+ : L("没有 key 时照常可用"))usageRow(L("语音识别"), tag: L("本机"), on: false, note: L("更快,不花钱"))SettingsRow(title: L("同声传译的声音"), detail: ling.usable ? L("Ming 的声音或你自己的声音") : L("没有 key 时用本机声音"),divider: false) {diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex c19d369..5302694 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -3,6 +3,8 @@ import AVFoundationimport Carbon.HIToolboximport Combineimport SwiftUI+import Speech+import UserNotifications/// Wires the engines, the meeting store, the subtitle bar and the UI together.@MainActor@@ -61,6 +63,15 @@ final class AppModel: ObservableObject {}}@Published var systemAudioOK = false+ /// 系统音频录制 was refused. Turned on later in System Settings, it only takes once Cicada is+ /// reopened (macOS says so too), so the guide offers that.+ @Published var systemAudioRefused = false+ /// Quitting to reopen (`relaunch`): closing the guide now isn't finishing it.+ var relaunching = false+ /// Speech recognition can run: always on macOS 26; below it, Dictation on and 语音识别 allowed.+ @Published var speechOK = Recognition.ready+ /// Step 1 of the guide is done.+ var listenReady: Bool { systemAudioOK && speechOK }@Published var micStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)@Published var liveSource = ""@Published var liveTranslation = ""@@ -346,6 +357,32 @@ final class AppModel: ObservableObject {func openMicrophoneSettings() { openSettingsPane("Privacy_Microphone") }+ /// Quits and opens Cicada again: a permission turned on after it was refused takes only then.+ func relaunch() {+ // Quitting closes the guide, which would count as finishing it: it carries on after the reopen.+ relaunching = true+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/bin/sh")+ p.arguments = ["-c", "while kill -0 \(getpid()) 2>/dev/null; do sleep 0.2; done; open \"$0\"", Bundle.main.bundlePath]+ try? p.run()+ NSApp.terminate(nil)+ }++ /// macOS 14/15: asks for 语音识别, then opens Keyboard settings if Dictation is still off.+ func requestSpeech() {+ Task {+ if await Recognition.authorize() {+ if !Recognition.dictationEnabled,+ let url = URL(string: "x-apple.systempreferences:com.apple.Keyboard-Settings.extension") {+ NSWorkspace.shared.open(url)+ }+ } else {+ openSettingsPane("Privacy_SpeechRecognition")+ }+ refreshPermissions()+ }+ }+private func openSettingsPane(_ anchor: String) {if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?\(anchor)") {NSWorkspace.shared.open(url)@@ -1494,7 +1531,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {func windowWillClose(_ notification: Notification) {let w = notification.object as? NSWindowupdateActivationPolicy(closing: w)- if w == onboardingWindow {+ if w == onboardingWindow, !model.relaunching {model.sample.stop()UserDefaults.standard.set(true, forKey: "onboarded")// Done (or 稍后): land on the records window rather than nothing but the menu bar icon.diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swiftindex dccaac6..ba2a512 100644--- a/Sources/LiveSubs/AudioRouter.swift+++ b/Sources/LiveSubs/AudioRouter.swift@@ -3,7 +3,6 @@ import AVFoundationimport AudioToolboximport CoreAudioimport CoreMedia-import Speech// MARK: - Audio routing@@ -52,7 +51,7 @@ final class AudioRouter: @unchecked Sendable {private let queue = DispatchQueue(label: "com.wquguru.cicada.audio", qos: .userInitiated)private let converter = PCMConverter()private var format: AVAudioFormat?- private var continuation: AsyncStream<AnalyzerInput>.Continuation?+ private var sink: RecognitionStream?private var ring: [(buffer: AVAudioPCMBuffer, seconds: Double, voiced: Bool)] = []private var ringSeconds = 0.0private let ringLimit = 10.0@@ -89,7 +88,7 @@ final class AudioRouter: @unchecked Sendable {}private func keepVoice(_ mono: AVAudioPCMBuffer) {- guard voiceCapture, continuation != nil,+ guard voiceCapture, sink != nil,let b = voiceConverter.convert(mono, to: voiceFormat), let d = b.floatChannelData else { return }if voice.isEmpty { voiceStart = fed }voice.append(contentsOf: UnsafeBufferPointer(start: d[0], count: Int(b.frameLength)))@@ -129,7 +128,7 @@ final class AudioRouter: @unchecked Sendable {let seconds = Double(n) / mono.format.sampleRatelet voiced = rms >= voiceThresholdif voiced {- if silenceRun >= 0.12, continuation != nil { pause = (fed, silenceRun) }+ if silenceRun >= 0.12, sink != nil { pause = (fed, silenceRun) }if silenceRun >= Self.gapSeconds { sinceGap = 0 }voicedTotal += secondssilenceRun = 0@@ -139,9 +138,9 @@ final class AudioRouter: @unchecked Sendable {sinceGap += secondsguard let format, let converted = converter.convert(mono, to: format) else { return }- continuation?.yield(AnalyzerInput(buffer: converted))+ sink?.append(converted)keepVoice(mono)- if continuation != nil { fed += seconds }+ if sink != nil { fed += seconds }record(converted)ring.append((converted, seconds, voiced))ringSeconds += seconds@@ -178,7 +177,8 @@ final class AudioRouter: @unchecked Sendable {queue.sync { (fed, silenceRun, pause) }}- func attach(format: AVAudioFormat, continuation: AsyncStream<AnalyzerInput>.Continuation, replaySeconds: Double = 0) {+ func attach(_ stream: RecognitionStream, replaySeconds: Double = 0) {+ let format = stream.formatqueue.sync {fed = 0pause = (0, 0)@@ -197,27 +197,24 @@ final class AudioRouter: @unchecked Sendable {acc += item.secondsreplay.append(item.buffer)}- for buffer in replay.reversed() { continuation.yield(AnalyzerInput(buffer: buffer)) }+ for buffer in replay.reversed() { stream.append(buffer) }fed = accvoice = Array(keptVoice.suffix(Int(acc * 16000)))}self.format = format- self.continuation?.finish()- self.continuation = continuation+ self.sink = stream}}func detach() {queue.sync {- continuation?.finish()- continuation = nil+ sink = nil}}func reset() {queue.sync {- continuation?.finish()- continuation = nil+ sink = nilring.removeAll()ringSeconds = 0voice = []diff --git a/Sources/LiveSubs/Compat.swift b/Sources/LiveSubs/Compat.swiftnew file mode 100644index 0000000..3f47c1f--- /dev/null+++ b/Sources/LiveSubs/Compat.swift@@ -0,0 +1,43 @@+import AppKit+import SwiftUI++/// SwiftUI that macOS 14 lacks, with what it gets instead.+extension View {+ /// The pointing hand over something clickable.+ @ViewBuilder func linkPointer() -> some View {+ if #available(macOS 15, *) {+ pointerStyle(.link)+ } else {+ onHover { inside in if inside { NSCursor.pointingHand.push() } else { NSCursor.pop() } }+ }+ }++ /// Where a scroll view's content sits against its bottom edge. macOS 14 doesn't report it:+ /// there the transcript keeps following new lines even after the reader scrolls up.+ @ViewBuilder func onScrollEdgeChange(_ action: @escaping (ScrollEdge, ScrollEdge) -> Void) -> some View {+ if #available(macOS 15, *) {+ onScrollGeometryChange(for: ScrollEdge.self) { g in+ ScrollEdge(distance: g.contentSize.height - g.contentOffset.y - g.containerSize.height,+ height: g.contentSize.height, container: g.containerSize.height)+ } action: { old, new in action(old, new) }+ } else {+ self+ }+ }++ /// The content scrolled (macOS 15 and later).+ @ViewBuilder func onScrolled(_ action: @escaping () -> Void) -> some View {+ if #available(macOS 15, *) {+ onScrollGeometryChange(for: CGFloat.self) { $0.contentOffset.y } action: { _, _ in action() }+ } else {+ self+ }+ }+}++/// How far the content's bottom is below the visible area, the content's height and the view's.+struct ScrollEdge: Equatable {+ var distance: CGFloat+ var height: CGFloat+ var container: CGFloat+}diff --git a/Sources/LiveSubs/DMGBackground.swift b/Sources/LiveSubs/DMGBackground.swiftindex 50d9ac7..94d4a72 100644--- a/Sources/LiveSubs/DMGBackground.swift+++ b/Sources/LiveSubs/DMGBackground.swift@@ -71,9 +71,11 @@ enum DMGBackground {color: secondary, centerX: size.width / 2, top: 298)let steps: [(title: String, hint: String, art: (CGContext, CGRect) -> Void)] = [- ("点完成", "别点移到废纸篓", drawAlert),+ // macOS 14's sheet has only 好 (OK); 15 and later have 完成 and 移到废纸篓.+ ("点完成或好", "别点移到废纸篓", drawAlert),("打开系统设置", "左边选隐私与安全性", drawSettings),- ("点仍要打开", "在安全性一栏,输一次密码", drawOpenAnyway),+ // 14 asks once more after the password: 打开.+ ("点仍要打开", "在安全性一栏,按提示输密码确认", drawOpenAnyway),]let w: CGFloat = 188, gap: CGFloat = 14var x = (size.width - w * 3 - gap * 2) / 2diff --git a/Sources/LiveSubs/LanguageDetector.swift b/Sources/LiveSubs/LanguageDetector.swiftindex db880cc..f7f0885 100644--- a/Sources/LiveSubs/LanguageDetector.swift+++ b/Sources/LiveSubs/LanguageDetector.swift@@ -3,7 +3,6 @@ import AVFoundationimport AudioToolboximport CoreAudioimport CoreMedia-import Speech// MARK: - Spoken language detection@@ -32,43 +31,9 @@ enum LanguageDetector {}private static func evaluate(_ clip: [AVAudioPCMBuffer], lang: Lang) async -> Candidate? {- let transcriber = SpeechTranscriber(locale: Locale(identifier: lang.locale),- transcriptionOptions: [],- reportingOptions: [],- attributeOptions: [.transcriptionConfidence])- guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber]) else { return nil }- let converter = PCMConverter()- let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self)- for buffer in clip {- if let b = converter.convert(buffer, to: format) { continuation.yield(AnalyzerInput(buffer: b)) }- }- continuation.finish()-- let collector = Task { () -> (String, Double, Int) in- var text = ""- var weighted = 0.0- var chars = 0- for try await result in transcriber.results {- text += String(result.text.characters)- for run in result.text.runs {- guard let c = run.transcriptionConfidence else { continue }- let len = result.text[run.range].characters.filter { !$0.isWhitespace && !$0.isPunctuation }.count- weighted += c * Double(len)- chars += len- }- }- return (text, chars > 0 ? weighted / Double(chars) : 0, chars)- }- do {- let analyzer = SpeechAnalyzer(inputSequence: stream, modules: [transcriber])- try await analyzer.finalizeAndFinishThroughEndOfInput()- let (text, conf, chars) = try await collector.value- return Candidate(lang: lang, confidence: conf, chars: chars, text: text,- score: score(conf: conf, chars: chars, text: text, lang: lang))- } catch {- collector.cancel()- return nil- }+ guard let heard = await Recognition.transcribe(clip, locale: lang.locale) else { return nil }+ return Candidate(lang: lang, confidence: heard.confidence, chars: heard.letters, text: heard.text,+ score: score(conf: heard.confidence, chars: heard.letters, text: heard.text, lang: lang))}static func score(conf: Double, chars: Int, text: String, lang: Lang) -> Double {diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 5168e41..10b6a4f 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -107,8 +107,8 @@ final class ListenEngine {// MARK: Modelsfunc refreshInstalledLocales() async {- let installed = await SpeechTranscriber.installedLocales- installedLocales = Set(installed.map { $0.identifier(.bcp47) })+ installedLocales = await Recognition.installedLocales()+ if let simulatedModels { installedLocales.formIntersection(simulatedModels) }candidates = sourceLanguages.filter { installedLocales.contains($0.locale) }debugLog("installed speech models: \(installedLocales.sorted()) candidates=\(candidates.map(\.locale))")onStateChange?()@@ -118,10 +118,14 @@ final class ListenEngine {func start() {guard !isRunning else { return }- guard SpeechTranscriber.isAvailable else {+ guard Recognition.isAvailable else {setStatus(L("此 Mac 不支持本机语音识别"))return}+ guard !Recognition.authorizationDenied else {+ setStatus(Recognition.notAllowed.localizedDescription)+ return+ }languageConfirmed = falsependingSwitch = nilneedsDetection = true@@ -158,10 +162,10 @@ final class ListenEngine {router.reset()resultsTask?.cancel()resultsTask = nil- if let analyzer {- Task { await analyzer.cancelAndFinishNow() }+ if let recognizer {+ Task { await recognizer.cancel() }}- analyzer = nil+ recognizer = nilsegments.removeAll()volatileText = ""volatileTranslation = ""@@ -253,9 +257,9 @@ final class ListenEngine {router.detach()resultsTask?.cancel()resultsTask = nil- if let old = analyzer {- analyzer = nil- await old.cancelAndFinishNow()+ if let old = recognizer {+ recognizer = nil+ await old.cancel()}guard isRunning, gen == generation else { return }@@ -273,35 +277,27 @@ final class ListenEngine {lastCutThrough = 0onStateChange?()- let transcriber = SpeechTranscriber(locale: Locale(identifier: lang.locale),- transcriptionOptions: [],- reportingOptions: [.volatileResults, .fastResults],- attributeOptions: [.transcriptionConfidence])do {try await ensureModel(for: transcriber, lang: lang)guard isRunning, gen == generation else { return }- let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber])- ?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!- let analyzer = SpeechAnalyzer(modules: [transcriber])- try await analyzer.prepareToAnalyze(in: format)+ let stream = try await Recognition.start(lang.locale, drafts: true, confidence: true)guard isRunning, gen == generation else {- await analyzer.cancelAndFinishNow()+ await stream.cancel()return}- let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self, bufferingPolicy: .unbounded)- router.attach(format: format, continuation: continuation, replaySeconds: replaySeconds)- self.analyzer = analyzer+ router.attach(stream, replaySeconds: replaySeconds)+ updateHold()+ self.recognizer = streamresultsTask = Task { [weak self] indo {- for try await result in transcriber.results {- self?.handle(result, generation: gen)+ for try await piece in stream.results {+ self?.handle(piece, generation: gen)}} catch {self?.recognitionFailed(error, generation: gen)}}- try await analyzer.start(inputSequence: stream)- debugLog("transcriber started locale=\(lang.locale) format=\(format)")+ debugLog("transcriber started recognizer=\(Recognition.name) locale=\(lang.locale) format=\(stream.format)")setStatus(L("正在听"))} catch {debugLog("transcriber start failed locale=\(lang.locale): \(error)")@@ -324,10 +320,10 @@ final class ListenEngine {}}- private func handle(_ result: SpeechTranscriber.Result, generation gen: Int) {+ private func handle(_ result: Recognition.Piece, generation gen: Int) {guard gen == generation, isRunning else { return }failureStreak = 0- var text = String(result.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)+ var text = result.text.trimmingCharacters(in: .whitespacesAndNewlines)if result.isFinal {text = HeardText.clean(text)let fuller = HeardText.fuller(final: text, draft: volatileText)@@ -341,27 +337,20 @@ final class ListenEngine {// A "." or "…" from a breath or a click is no sentence: Ling would answer it with a note that// there was nothing to translate, and it would sit in the record as a line.guard text.contains(where: \.isLetter) else { renderSubtitles(); return }- var weighted = 0.0, chars = 0- for run in result.text.runs {- guard let c = run.transcriptionConfidence else { continue }- let len = result.text[run.range].characters.count- weighted += c * Double(len)- chars += len- }- let conf = chars > 0 ? weighted / Double(chars) : 1+ let conf = result.confidence ?? 1let provisional = volatileTranslation.isEmpty ? nil : volatileTranslationvar seg = Segment(id: nextSegmentID, text: text, sourceCode: activeLang?.code ?? "auto", translation: provisional)- seg.start = CMTimeGetSeconds(result.range.start)- seg.end = CMTimeGetSeconds(result.range.end)+ seg.start = result.start+ seg.end = result.endseg.clock = genseg.cut = cutAskedcutAsked = falseif settings.speakerVoices {- seg.voiceSamples = router.voiceSamples(from: CMTimeGetSeconds(result.range.start), to: CMTimeGetSeconds(result.range.end))+ seg.voiceSamples = router.voiceSamples(from: result.start, to: result.end)}nextSegmentID += 1// How long ago, in real time, the sentence's last word was spoken.- let ago = router.fedSeconds() - CMTimeGetSeconds(result.range.end)+ let ago = router.fedSeconds() - result.endfinalTiming[seg.id] = (Date(), ago.isFinite && ago >= 0 && ago < 30 ? ago : nil)if finalTiming.count > 40, let oldest = finalTiming.keys.min() { finalTiming[oldest] = nil }var shown = seg@@ -373,7 +362,7 @@ final class ListenEngine {volatileTranslation = ""lastVolatileSent = ""contentLog(String(format: "FINAL conf=%.2f [%@] %@", conf, activeLang?.locale ?? "?", text))- let duration = max(0, CMTimeGetSeconds(result.range.duration))+ let duration = max(0, result.end - result.start)// Only confirmed-language sentences go into the meeting record; earlier ones wait.let spoken = duration.isFinite ? duration : 0if recordable {@@ -607,7 +596,7 @@ final class ListenEngine {/// line in progress is ended at the next small pause: a dip in the sound, or no new words for/// a moment.private func maybeCutSentence() {- guard isRunning, !cutting, let analyzer, !volatileText.isEmpty, volatileText != lastCut else { return }+ guard isRunning, !cutting, let recognizer, !volatileText.isEmpty, volatileText != lastCut else { return }let cjk = joiner(for: activeLang?.code ?? "") == ""let long = cjk ? volatileText.count >= 24 : volatileText.split(separator: " ").count >= 10guard long else { return }@@ -633,7 +622,7 @@ final class ListenEngine {let chars = volatileText.countTask { [weak self] indo {- try await analyzer.finalize(through: CMTime(seconds: through, preferredTimescale: 1000))+ try await recognizer.finalize(through: through)debugLog(String(format: "cut: line of %d chars ended after %.1f s (%@) at %.1f s of %.1f s",chars, held, why, through, c.fed))} catch {diff --git a/Sources/LiveSubs/Onboarding.swift b/Sources/LiveSubs/Onboarding.swiftindex d3636a5..cad62f3 100644--- a/Sources/LiveSubs/Onboarding.swift+++ b/Sources/LiveSubs/Onboarding.swift@@ -378,7 +378,7 @@ struct OnboardingView: View {.onChange(of: step) { _, _ in sample.reset() }// Only the moment it turns on moves on by itself: when it was already on (the guide// reopened from Settings), step 1 stays put with a plain 继续.- .onChange(of: model.systemAudioOK) { was, now in+ .onChange(of: model.listenReady) { was, now inguard !was, now, step == 1 else { return }DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {MainActor.assumeIsolated { if step == 1 { step = 2 } }@@ -426,7 +426,7 @@ struct OnboardingView: View {}Spacer()switch step {- case 1 where !model.systemAudioOK:+ case 1 where !model.listenReady:Text("打开后自动继续").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.secondary).padding(.horizontal, 24).frame(height: 44)@@ -528,11 +528,28 @@ struct OnboardingView: View {private var permissions: some View {VStack(alignment: .leading, spacing: 24) {title(L("让知了听到电脑里的声音"), L("字幕和纪要都从这里来。去系统设置打开,回来会自动识别。"))- whiteCard {- row(icon: "speaker.wave.2", title: L("听电脑里的声音"), detail: L("只听声音,不录屏幕画面")) {- if model.systemAudioOK { done(L("已打开")) } else { primary(L("去开启")) { model.requestSystemAudio() } }+ whiteCard { VStack(spacing: 0) {+ row(icon: "speaker.wave.2", title: L("听电脑里的声音"),+ detail: model.systemAudioRefused ? L("在系统设置里打开后,要重新打开知了") : L("只听声音,不录屏幕画面")) {+ if model.systemAudioOK {+ done(L("已打开"))+ } else if model.systemAudioRefused {+ HStack(spacing: 8) {+ secondary(L("重新打开")) { model.relaunch() }+ primary(L("去开启")) { model.requestSystemAudio() }+ }+ } else {+ primary(L("去开启")) { model.requestSystemAudio() }+ }}- }+ // macOS 14/15: the older recognizer needs Dictation on and its own permission.+ if Recognition.legacy {+ Divider().padding(.horizontal, 22)+ row(icon: "waveform", title: L("识别语音"), detail: L("打开“听写”,允许“语音识别”")) {+ if model.speechOK { done(L("已打开")) } else { primary(L("去开启")) { model.requestSpeech() } }+ }+ }+ } }Label("声音只在本机识别", systemImage: "lock").font(.system(size: 12)).foregroundStyle(Palette.secondary)}diff --git a/Sources/LiveSubs/Recognition.swift b/Sources/LiveSubs/Recognition.swiftnew file mode 100644index 0000000..fe2a662--- /dev/null+++ b/Sources/LiveSubs/Recognition.swift@@ -0,0 +1,690 @@+import AVFoundation+import CoreMedia+import Speech++/// On-device speech recognition, whatever the macOS. On 26 and later it is `SpeechAnalyzer`; on+/// 14.4–15 it is the older `SFSpeechRecognizer` (on-device only: audio never leaves the Mac, as on+/// 26). The engines only see this file, so the version check lives in one place.+enum Recognition {+ /// Dev builds can run the older recognizer on macOS 26, which is where most of its testing+ /// happens: `lsctl recognizer:legacy`, or `open --env CICADA_RECOGNIZER=legacy` from launch.+ /// Not kept in settings: two dev copies share them.+ nonisolated(unsafe) static var forceLegacy = DevBuild.isDev && ProcessInfo.processInfo.environment["CICADA_RECOGNIZER"] == "legacy"++ static var legacy: Bool {+ if #available(macOS 26, *) { return forceLegacy }+ return true+ }++ static var name: String { legacy ? "legacy" : "analyzer" }++ /// Apple's on-device translation can be made outside a SwiftUI view only on 26 (`Translator.viaApple`).+ static var hasOnDeviceTranslation: Bool {+ if #available(macOS 26, *) { return true }+ return false+ }++ /// What a recognizer heard: a draft of the line in progress, or a finished one. Times are+ /// seconds on the stream's clock (the audio appended to it).+ struct Piece: Sendable {+ var text: String+ var isFinal: Bool+ var start: Double+ var end: Double+ /// Mean word confidence (0–1), nil when the recognizer gave none.+ var confidence: Double?+ }++ enum ModelStatus { case installed, downloadable, unsupported }++ static var isAvailable: Bool {+ if !legacy, #available(macOS 26, *) { return SpeechTranscriber.isAvailable }+ return true+ }++ /// The older recognizer asks for 语音识别 permission; 26 doesn't. False when it was refused.+ static func authorize() async -> Bool {+ guard legacy else { return true }+ switch SFSpeechRecognizer.authorizationStatus() {+ case .authorized: return true+ case .denied, .restricted: return false+ default:+ return await withCheckedContinuation { cont in+ SFSpeechRecognizer.requestAuthorization { cont.resume(returning: $0 == .authorized) }+ }+ }+ }++ static var authorizationDenied: Bool {+ legacy && [.denied, .restricted].contains(SFSpeechRecognizer.authorizationStatus())+ }++ /// The older recognizer only runs while Siri or Dictation is on (系统设置 › 键盘 › 听写);+ /// otherwise every line fails at once (`kLSRErrorDomain` 201).+ static var dictationEnabled: Bool {+ guard legacy else { return true }+ let domain = "com.apple.assistant.support" as CFString+ func on(_ key: String) -> Bool {+ (CFPreferencesCopyAppValue(key as CFString, domain) as? NSNumber)?.boolValue ?? false+ }+ return on("Dictation Enabled") || on("Assistant Enabled")+ }++ /// Everything the recognizer needs from the user is in place (always, on 26).+ static var ready: Bool {+ !legacy || (dictationEnabled && SFSpeechRecognizer.authorizationStatus() == .authorized)+ }++ /// Thrown when Dictation is off; the engines show its message rather than a retry count.+ static let dictationOff = NSError(domain: "LiveSubsSpeech", code: 3,+ userInfo: [NSLocalizedDescriptionKey: L("请在系统设置 › 键盘里打开“听写”")])+ static let notAllowed = NSError(domain: "LiveSubsSpeech", code: 2,+ userInfo: [NSLocalizedDescriptionKey: L("请在系统设置里允许知了使用“语音识别”")])++ /// A problem only the user can fix in System Settings.+ static func needsUser(_ error: Error) -> Bool {+ let ns = error as NSError+ return ns.domain == "LiveSubsSpeech" && [2, 3, 4].contains(ns.code)+ }++ /// BCP-47 ids of the languages that can be recognized right now without a download.+ static func installedLocales() async -> Set<String> {+ if !legacy, #available(macOS 26, *) {+ return Set(await SpeechTranscriber.installedLocales.map { $0.identifier(.bcp47) })+ }+ return Set(sourceLanguages.map(\.locale).filter { LegacyStream.onDevice($0) })+ }++ static func status(_ locale: String) async -> ModelStatus {+ if !legacy, #available(macOS 26, *) {+ switch await AssetInventory.status(forModules: [Analyzer.transcriber(locale)]) {+ case .installed: return .installed+ case .unsupported: return .unsupported+ default: return .downloadable+ }+ }+ // The older recognizer can't fetch a model: macOS downloads it for each Dictation language,+ // and only while Dictation is on. A language not there yet is the user's to add.+ return LegacyStream.onDevice(locale) ? .installed : .downloadable+ }++ /// Fetches the model for `locale` when it isn't on the Mac; `progress` is called once a+ /// download starts. Throws when this Mac can't recognize the language.+ static func install(_ locale: String, progress: (Progress) -> Void = { _ in }) async throws {+ if !legacy, #available(macOS 26, *) {+ let t = Analyzer.transcriber(locale)+ if await AssetInventory.status(forModules: [t]) == .unsupported { throw unsupported(locale) }+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [t]) {+ progress(request.progress)+ try await request.downloadAndInstall()+ }+ return+ }+ guard dictationEnabled else { throw dictationOff }+ if !LegacyStream.onDevice(locale) { throw addToDictation(locale) }+ }++ /// The models this app holds (macOS keeps five per app), as BCP-47 ids; none on 14/15,+ /// where Dictation owns them.+ static func reservedLocales() async -> [String] {+ guard !legacy, #available(macOS 26, *) else { return [] }+ return await AssetInventory.reservedLocales.map { $0.identifier(.bcp47) }+ }++ /// Gives a held model back to the system, making room under the five-model limit.+ static func release(_ locale: String) async -> Bool {+ guard !legacy, #available(macOS 26, *) else { return false }+ return await AssetInventory.release(reservedLocale: Locale(identifier: locale.replacingOccurrences(of: "-", with: "_")))+ }++ static func addToDictation(_ locale: String) -> NSError {+ let name = sourceLanguages.first { $0.locale == locale }?.name ?? locale+ return NSError(domain: "LiveSubsSpeech", code: 4,+ userInfo: [NSLocalizedDescriptionKey: L("请在系统设置 › 键盘 › 听写里添加\(name)")])+ }++ static func unsupported(_ locale: String) -> NSError {+ let name = sourceLanguages.first { $0.locale == locale }?.name ?? locale+ return NSError(domain: "LiveSubsSpeech", code: 1, userInfo: [NSLocalizedDescriptionKey: L("本机不支持\(name)识别")])+ }++ /// A recognizer for a stream of audio in `locale`: append buffers in `stream.format`, read+ /// `stream.results`. `drafts` adds lines in progress; `confidence` asks for word confidences.+ /// `speaking`: what the user says while holding the talk key. On macOS 14/15 it has the+ /// recognizer to itself meanwhile (the meeting's lines wait); on 26 both run at once.+ static func start(_ locale: String, drafts: Bool, confidence: Bool = false, speaking: Bool = false) async throws -> RecognitionStream {+ if !legacy, #available(macOS 26, *) {+ return try await Analyzer.start(locale, drafts: drafts, confidence: confidence)+ }+ guard await authorize() else { throw notAllowed }+ guard dictationEnabled else { throw dictationOff }+ return try LegacyStream(locale: locale, drafts: drafts, role: speaking ? .speak : drafts ? .listen : .other)+ }++ /// The audio format `start(locale, drafts:)` will want, known before starting one.+ static func format(_ locale: String, drafts: Bool) async -> AVAudioFormat {+ if !legacy, #available(macOS 26, *) {+ return await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [Analyzer.transcriber(locale, drafts: drafts)])+ ?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!+ }+ return LegacyStream.audioFormat+ }++ /// A stream that takes audio at once (in `format`, from `format(locale, drafts:)`) and starts+ /// recognizing as soon as the recognizer is ready: the talk key opens the mic without waiting.+ /// It is what the user says (`speaking` above).+ static func startNow(_ locale: String, drafts: Bool, format: AVAudioFormat) -> RecognitionStream {+ DeferredStream(locale, drafts: drafts, format: format)+ }++ /// Transcribes recorded audio (a clip, one press of the talk key): the finished lines joined,+ /// their confidence and how many letters they hold. Nil when the language can't be recognized.+ static func transcribe(_ buffers: [AVAudioPCMBuffer], locale: String) async -> (text: String, confidence: Double, letters: Int)? {+ guard await status(locale) == .installed else { return nil }+ // The older recognizer can't run two tasks at once (both come back "no speech"): a clip+ // waits for a pause in the live line, which meanwhile holds its audio back.+ let gated = legacy+ if gated {+ guard await LegacyStream.Gate.enterClip() else { return nil }+ }+ defer { if gated { LegacyStream.Gate.leaveClip() } }+ guard let stream = try? await start(locale, drafts: false, confidence: true) else { return nil }+ let collector = Task { () -> [Piece] in+ var out: [Piece] = []+ do { for try await p in stream.results where p.isFinal { out.append(p) } } catch {}+ return out+ }+ let conv = PCMConverter()+ for b in buffers { if let c = conv.convert(b, to: stream.format) { stream.append(c) } }+ await stream.finish()+ let pieces = await collector.value+ var weighted = 0.0, letters = 0+ for p in pieces {+ let n = p.text.filter { !$0.isWhitespace && !$0.isPunctuation }.count+ letters += n+ weighted += (p.confidence ?? 0) * Double(n)+ }+ let text = pieces.map { $0.text.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }.joined(separator: " ")+ return (text, letters > 0 ? weighted / Double(letters) : 0, letters)+ }+}++/// One running recognition. `append` may be called from any thread.+protocol RecognitionStream: AnyObject, Sendable {+ var format: AVAudioFormat { get }+ var results: AsyncThrowingStream<Recognition.Piece, Error> { get }+ func append(_ buffer: AVAudioPCMBuffer)+ /// Ends the line in progress at `seconds` (or now), so it comes back finished.+ func finalize(through seconds: Double) async throws+ /// No more audio: returns once every line has come back and `results` has ended.+ func finish() async+ func cancel() async+}++// MARK: - macOS 26: SpeechAnalyzer++@available(macOS 26, *)+final class Analyzer: RecognitionStream, @unchecked Sendable {+ let format: AVAudioFormat+ let results: AsyncThrowingStream<Recognition.Piece, Error>+ private let analyzer: SpeechAnalyzer+ private let input: AsyncStream<AnalyzerInput>.Continuation+ private let reader: Task<Void, Never>++ static func transcriber(_ locale: String, drafts: Bool = false, confidence: Bool = false) -> SpeechTranscriber {+ // Without `.fastResults` Chinese only reports every ~11 s of audio; with it, text trails+ // speech by about a second.+ SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [],+ reportingOptions: drafts ? [.volatileResults, .fastResults] : [],+ attributeOptions: confidence ? [.transcriptionConfidence] : [])+ }++ static func start(_ locale: String, drafts: Bool, confidence: Bool) async throws -> Analyzer {+ let t = transcriber(locale, drafts: drafts, confidence: confidence)+ let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t])+ ?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!+ let analyzer = SpeechAnalyzer(modules: [t])+ try await analyzer.prepareToAnalyze(in: format)+ let (stream, input) = AsyncStream.makeStream(of: AnalyzerInput.self, bufferingPolicy: .unbounded)+ let me = Analyzer(t, analyzer: analyzer, format: format, input: input)+ try await analyzer.start(inputSequence: stream)+ return me+ }++ private init(_ t: SpeechTranscriber, analyzer: SpeechAnalyzer, format: AVAudioFormat,+ input: AsyncStream<AnalyzerInput>.Continuation) {+ self.analyzer = analyzer+ self.format = format+ self.input = input+ let (results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)+ self.results = results+ reader = Task {+ do {+ for try await r in t.results {+ var weighted = 0.0, chars = 0+ for run in r.text.runs {+ guard let c = run.transcriptionConfidence else { continue }+ let len = r.text[run.range].characters.count+ weighted += c * Double(len)+ chars += len+ }+ out.yield(.init(text: String(r.text.characters), isFinal: r.isFinal,+ start: CMTimeGetSeconds(r.range.start), end: CMTimeGetSeconds(r.range.end),+ confidence: chars > 0 ? weighted / Double(chars) : nil))+ }+ out.finish()+ } catch {+ out.finish(throwing: error)+ }+ }+ }++ func append(_ buffer: AVAudioPCMBuffer) { input.yield(AnalyzerInput(buffer: buffer)) }++ func finalize(through seconds: Double) async throws {+ try await analyzer.finalize(through: CMTime(seconds: seconds, preferredTimescale: 1000))+ }++ func finish() async {+ input.finish()+ do { try await analyzer.finalizeAndFinishThroughEndOfInput() } catch { debugLog("analyzer finish: \(error)") }+ await reader.value+ }++ func cancel() async {+ input.finish()+ await analyzer.cancelAndFinishNow()+ }+}++// MARK: - macOS 14.4–15: SFSpeechRecognizer++/// `SFSpeechRecognizer` has no sentences of its own: a task's text grows until its audio ends.+/// So each line is one task, ended at a pause (or when asked to, for a long line), and the next+/// line starts a new task. The clock counts every buffer appended, as `SpeechAnalyzer`'s does.+final class LegacyStream: RecognitionStream, @unchecked Sendable {+ static let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!+ let format = LegacyStream.audioFormat+ let results: AsyncThrowingStream<Recognition.Piece, Error>+ private let out: AsyncThrowingStream<Recognition.Piece, Error>.Continuation+ private let recognizer: SFSpeechRecognizer+ private let drafts: Bool+ private let queue = OperationQueue()+ private let lock = NSLock()++ /// Below this RMS a buffer is quiet (as `AudioRouter`).+ private static let quiet: Float = 0.01+ /// A pause this long ends the line; a line this long is ended anyway.+ private static let pause = 0.7+ private static let longest = 45.0+ private static let preroll = 0.3+ private static let holdLimit = 6.0++ private struct Line {+ let request: SFSpeechAudioBufferRecognitionRequest+ var task: SFSpeechRecognitionTask?+ let start: Double+ var draft = ""+ /// Where its audio ended, less the pause that ended it.+ var endAt: Double?+ }+ /// One task at a time across the app: live lines and short clips (language checks) take turns.+ enum Gate {+ private static let lock = NSLock()+ nonisolated(unsafe) private static var liveLines = 0+ nonisolated(unsafe) private static var clips = 0++ /// Waits (up to 4 s) for no live line to be open, then holds new ones back. False: gave up.+ static func enterClip() async -> Bool {+ for _ in 0..<40 {+ let ok = lock.withLock { () -> Bool in+ guard liveLines == 0 else { return false }+ clips += 1+ return true+ }+ if ok { return true }+ try? await Task.sleep(nanoseconds: 100_000_000)+ }+ debugLog("legacy recognizer: no pause for a language check")+ return false+ }+ static func leaveClip() { lock.withLock { clips -= 1 } }+ static var clipRunning: Bool { lock.withLock { clips > 0 } }+ nonisolated(unsafe) private static var speakers = 0+ /// The talk key is held: the meeting's live stream holds its audio until it's let go.+ static var speaking: Bool { lock.withLock { speakers > 0 } }+ static func speaker(_ delta: Int) { lock.withLock { speakers += delta } }+ static func liveLine(_ delta: Int) { lock.withLock { liveLines += delta } }+ }++ private var lines: [Int: Line] = [:]+ private var current: Int?+ private var nextID = 0+ private var fed = 0.0+ private var silence = 0.0+ private var heardVoice = false+ private var recent: [AVAudioPCMBuffer] = []+ private var recentSeconds = 0.0+ /// Speech that came during a language check or the talk key, waiting in `recent`.+ private var holding = false+ private var heldVoice = false+ private var finished = false+ private var finishWaiter: CheckedContinuation<Void, Never>?+ /// A draft of the next line held back until the line before it has come back finished, so+ /// the engine never sees a draft that belongs after a line still to be finished.+ private var heldDraft: (id: Int, piece: Recognition.Piece)?++ static func onDevice(_ locale: String) -> Bool {+ guard let r = SFSpeechRecognizer(locale: Locale(identifier: locale)) else { return false }+ return r.supportsOnDeviceRecognition+ }++ /// What the stream hears: the meeting (gives way while the user speaks), the user holding the+ /// talk key, or anything else (a file, a clip).+ enum Role { case listen, speak, other }+ private let role: Role+ private var spoke = false++ init(locale: String, drafts: Bool, role: Role = .other) throws {+ guard let r = SFSpeechRecognizer(locale: Locale(identifier: locale)), r.supportsOnDeviceRecognition else {+ throw Recognition.unsupported(locale)+ }+ recognizer = r+ self.drafts = drafts+ self.role = role+ queue.maxConcurrentOperationCount = 1+ recognizer.queue = queue+ (results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)+ if role == .speak { Gate.speaker(1); spoke = true }+ if drafts { debugLog("legacy recognizer \(locale) available=\(r.isAvailable)") }+ }++ func append(_ buffer: AVAudioPCMBuffer) {+ let n = Int(buffer.frameLength)+ guard n > 0, let d = buffer.floatChannelData else { return }+ var sum: Float = 0+ for i in 0..<n { sum += d[0][i] * d[0][i] }+ let voiced = (sum / Float(n)).squareRoot() >= Self.quiet+ let seconds = Double(n) / buffer.format.sampleRate+ lock.lock()+ defer { lock.unlock() }+ guard !finished else { return }+ if role == .listen, Gate.speaking {+ // The user is speaking: the line in progress ends now, and the meeting's last few+ // seconds wait for the talk key to be let go (two tasks at once both come back empty).+ if current != nil { end() }+ recent.append(buffer)+ recentSeconds += seconds+ fed += seconds+ holding = true+ if voiced { heldVoice = true }+ while recentSeconds > Self.holdLimit, recent.count > 1 {+ recentSeconds -= Double(recent.removeFirst().frameLength) / buffer.format.sampleRate+ }+ return+ }+ if current == nil {+ // The line before is still being finished, or a language check is running: starting a+ // task now would make the other come back empty. Keep the words until then (a few seconds).+ if voiced || holding, (!lines.isEmpty || Gate.clipRunning), recentSeconds < Self.holdLimit {+ recent.append(buffer)+ recentSeconds += seconds+ fed += seconds+ holding = true+ if voiced { heldVoice = true }+ return+ }+ // Held audio with no speech in it (the meeting was quiet while the user spoke) is just+ // the quiet before the next line, not the start of one.+ if holding, !heldVoice, !voiced { holding = false }+ if voiced || holding {+ let spokenBefore = heldVoice+ holding = false+ heldVoice = false+ // The quiet just before the first word belongs to it: a soft onset is still heard.+ begin(at: fed - recentSeconds)+ for b in recent { lines[current!]?.request.append(b) }+ recent = []+ recentSeconds = 0+ // Held speech counts: the next pause ends this line.+ if spokenBefore { heardVoice = true }+ } else {+ recent.append(buffer)+ recentSeconds += seconds+ while !holding, recentSeconds > Self.preroll, recent.count > 1 {+ recentSeconds -= Double(recent.removeFirst().frameLength) / buffer.format.sampleRate+ }+ fed += seconds+ return+ }+ }+ guard let id = current, let line = lines[id] else { return }+ line.request.append(buffer)+ fed += seconds+ if voiced { silence = 0; heardVoice = true } else { silence += seconds }+ if (heardVoice && silence >= Self.pause) || fed - line.start >= Self.longest { end() }+ }++ /// Called with the lock held.+ private func begin(at start: Double) {+ let request = SFSpeechAudioBufferRecognitionRequest()+ request.requiresOnDeviceRecognition = true+ request.shouldReportPartialResults = drafts+ request.addsPunctuation = true+ request.taskHint = .dictation+ let id = nextID+ nextID += 1+ lines[id] = Line(request: request, start: max(0, start))+ if drafts { Gate.liveLine(1) }+ current = id+ silence = 0+ heardVoice = false+ lines[id]?.task = recognizer.recognitionTask(with: request) { [weak self] result, error in+ self?.deliver(id, result, error)+ }+ }++ /// Called with the lock held.+ private func end() {+ guard let id = current else { return }+ current = nil+ lines[id]?.endAt = fed - silence+ lines[id]?.request.endAudio()+ silence = 0+ // A line that never comes back (the recognizer can drop one) is closed with its draft. A+ // slow Mac (or a virtual one, with no Neural Engine) takes longer than the line itself.+ let wait = 10 + 2 * (fed - (lines[id]?.start ?? fed))+ DispatchQueue.global().asyncAfter(deadline: .now() + wait) { [weak self] in+ guard let self else { return }+ self.lock.withLock { self.close(id, text: nil, confidence: nil) }+ }+ }++ private func deliver(_ id: Int, _ result: SFSpeechRecognitionResult?, _ error: Error?) {+ lock.lock()+ defer { lock.unlock() }+ guard let line = lines[id] else { return }+ if let result {+ let text = result.bestTranscription.formattedString+ if result.isFinal {+ let segs = result.bestTranscription.segments+ var weighted = 0.0, chars = 0+ for s in segs where s.confidence > 0 {+ weighted += Double(s.confidence) * Double(s.substring.count)+ chars += s.substring.count+ }+ let end = segs.last.map { line.start + $0.timestamp + $0.duration }+ close(id, text: text, end: end, confidence: chars > 0 ? weighted / Double(chars) : nil)+ return+ }+ lines[id]?.draft = text+ let piece = Recognition.Piece(text: text, isFinal: false, start: line.start, end: fed, confidence: nil)+ // A line before this one is still being finished: its final comes first.+ if lines.keys.contains(where: { $0 < id }) { heldDraft = (id, piece) } else { out.yield(piece) }+ } else if let error {+ let ns = error as NSError+ // Siri and Dictation are off (or turned off meanwhile): no line can succeed.+ if ns.domain == "kLSRErrorDomain" && ns.code == 201 {+ debugLog("legacy recognizer: Siri and Dictation are off")+ fail(Recognition.dictationOff)+ return+ }+ // "No speech detected" and the like: the line ends with whatever its draft held.+ if !(ns.domain == "kAFAssistantErrorDomain" && [1110, 216].contains(ns.code)) {+ debugLog("legacy recognizer line \(id): \(ns.domain) \(ns.code) \(ns.localizedDescription)")+ }+ close(id, text: nil, confidence: nil)+ }+ }++ /// Ends line `id` once: yields it finished (its final text, else its draft). Lock held.+ private func close(_ id: Int, text: String?, end: Double? = nil, confidence: Double?) {+ guard let line = lines.removeValue(forKey: id) else { return }+ if drafts { Gate.liveLine(-1) }+ if drafts {+ debugLog(String(format: "legacy line %d: %.1f–%.1f s, %@, %d chars", id, line.start, line.endAt ?? fed,+ text == nil ? "draft" : "final", (text ?? line.draft).count))+ }+ if current == id { current = nil }+ line.task?.cancel()+ let words = (text ?? line.draft).trimmingCharacters(in: .whitespacesAndNewlines)+ if !words.isEmpty {+ out.yield(.init(text: words, isFinal: true, start: line.start,+ end: max(line.start, end ?? line.endAt ?? fed), confidence: confidence))+ }+ if let held = heldDraft, !lines.keys.contains(where: { $0 < held.id }) {+ heldDraft = nil+ if lines[held.id] != nil { out.yield(held.piece) }+ }+ if finished, lines.isEmpty {+ releaseSpeaker()+ out.finish()+ finishWaiter?.resume()+ finishWaiter = nil+ }+ }++ /// The talk key's stream is done: the meeting may have the recognizer back. Lock held.+ private func releaseSpeaker() {+ guard spoke else { return }+ spoke = false+ Gate.speaker(-1)+ }++ deinit { if spoke { Gate.speaker(-1) } }++ /// Lines given audio that haven't come back yet.+ var backlog: Int { lock.withLock { lines.count } }++ func finalize(through seconds: Double) async throws {+ lock.withLock { end() }+ }++ func finish() async {+ await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in+ lock.lock()+ finished = true+ if current == nil, holding {+ // Words held back for the line before: they still need a line of their own.+ holding = false+ begin(at: fed - recentSeconds)+ for b in recent { lines[current!]?.request.append(b) }+ recent = []+ recentSeconds = 0+ }+ end()+ if lines.isEmpty {+ releaseSpeaker()+ out.finish()+ lock.unlock()+ cont.resume()+ } else {+ finishWaiter = cont+ lock.unlock()+ }+ }+ }++ func cancel() async {+ lock.withLock { fail(nil) }+ }++ /// Stops every line; `results` ends with `error`. Lock held.+ private func fail(_ error: Error?) {+ finished = true+ releaseSpeaker()+ for line in lines.values { line.task?.cancel() }+ if drafts { Gate.liveLine(-lines.count) }+ lines = [:]+ current = nil+ out.finish(throwing: error)+ finishWaiter?.resume()+ finishWaiter = nil+ }+}++// MARK: - Started late++/// Holds the audio until the recognizer behind it has started, then passes everything through.+final class DeferredStream: RecognitionStream, @unchecked Sendable {+ let format: AVAudioFormat+ let results: AsyncThrowingStream<Recognition.Piece, Error>+ private let lock = NSLock()+ private var pending: [AVAudioPCMBuffer] = []+ private var real: RecognitionStream?+ private var closed = false+ private var opening: Task<RecognitionStream?, Never>?+ private var forwarding: Task<Void, Never>?++ init(_ locale: String, drafts: Bool, format: AVAudioFormat) {+ self.format = format+ let (results, out) = AsyncThrowingStream.makeStream(of: Recognition.Piece.self)+ self.results = results+ opening = Task { [self] in+ do {+ let s = try await Recognition.start(locale, drafts: drafts, speaking: true)+ lock.withLock {+ real = s+ if !closed { for b in pending { s.append(b) } }+ pending = []+ }+ forwarding = Task {+ do {+ for try await p in s.results { out.yield(p) }+ out.finish()+ } catch {+ out.finish(throwing: error)+ }+ }+ return s+ } catch {+ debugLog("recognizer start failed: \(error)")+ out.finish(throwing: error)+ return nil+ }+ }+ }++ func append(_ buffer: AVAudioPCMBuffer) {+ lock.withLock {+ guard !closed else { return }+ if let real { real.append(buffer) } else { pending.append(buffer) }+ }+ }++ func finalize(through seconds: Double) async throws {+ try await opening?.value?.finalize(through: seconds)+ }++ func finish() async {+ guard let s = await opening?.value else { return }+ lock.withLock { closed = true }+ await s.finish()+ await forwarding?.value+ }++ func cancel() async {+ lock.withLock { closed = true; pending = [] }+ await opening?.value?.cancel()+ }+}diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftindex 094ffa6..b4e9df4 100644--- a/Sources/LiveSubs/SpeakEngine.swift+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -158,16 +158,9 @@ final class SpeakEngine {func prepare() async {let lang = settings.speakFromLangguard analyzerLocale != lang.locale || analyzerFormat == nil else { return }- let t = SpeechTranscriber(locale: Locale(identifier: lang.locale), transcriptionOptions: [],- reportingOptions: [.volatileResults, .fastResults], attributeOptions: [])do {- if await AssetInventory.status(forModules: [t]) != .installed,- let req = try await AssetInventory.assetInstallationRequest(supporting: [t]) {- onStatus?(L("正在下载 \(lang.name) 语音模型…"))- try await req.downloadAndInstall()- }- analyzerFormat = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t])- ?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!+ try await Recognition.install(lang.locale) { _ in self.onStatus?(L("正在下载 \(lang.name) 语音模型…")) }+ analyzerFormat = await Recognition.format(lang.locale, drafts: true)analyzerLocale = lang.localedebugLog("speak transcriber ready locale=\(lang.locale)")} catch {@@ -177,7 +170,7 @@ final class SpeakEngine {}func teardownAnalyzer() async {- utterance?.input.finish()+ if let input = utterance?.input { Task { await input.cancel() } }utterance = nilanalyzerFormat = nilanalyzerLocale = ""@@ -186,42 +179,29 @@ final class SpeakEngine {/// One press = one analyzer over a finite stream. Finishing the stream and/// awaiting `finalizeAndFinishThroughEndOfInput` guarantees every word/// spoken during the press is in the result before we translate it.- private var utterance: (input: AsyncStream<AnalyzerInput>.Continuation, text: Task<String, Never>)?+ private var utterance: (input: RecognitionStream, text: Task<String, Never>)?- private func beginUtterance() -> AsyncStream<AnalyzerInput>.Continuation? {- guard analyzerFormat != nil else { return nil }+ private func beginUtterance() -> RecognitionStream? {+ guard let format = analyzerFormat else { return nil }let lang = settings.speakFromLang- // Without `.fastResults` Chinese only reports every ~11 s of audio, so the bar stays- // empty for a whole sentence or two; with it, text trails speech by about a second.- let t = SpeechTranscriber(locale: Locale(identifier: lang.locale), transcriptionOptions: [],- reportingOptions: [.volatileResults, .fastResults], attributeOptions: [])- let (stream, cont) = AsyncStream.makeStream(of: AnalyzerInput.self)+ let stream = Recognition.startNow(lang.locale, drafts: true, format: format)finals = []volatile = ""micQueue.sync { pressSamples = []; pressConverter = PCMConverter() }let task = Task { [weak self] () -> String in- let collector = Task { [weak self] in- do {- for try await r in t.results { self?.handle(r) }- } catch {- debugLog("speak recognition error: \(error)")- }- }- let analyzer = SpeechAnalyzer(inputSequence: stream, modules: [t])do {- try await analyzer.finalizeAndFinishThroughEndOfInput()+ for try await r in stream.results { self?.handle(r) }} catch {- debugLog("speak analyzer error: \(error)")+ debugLog("speak recognition error: \(error)")}- await collector.valuereturn self?.currentText ?? ""}- utterance = (cont, task)- return cont+ utterance = (stream, task)+ return stream}- private func handle(_ r: SpeechTranscriber.Result) {- let text = String(r.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)+ private func handle(_ r: Recognition.Piece) {+ let text = r.text.trimmingCharacters(in: .whitespacesAndNewlines)if r.isFinal {if !text.isEmpty { finals.append(text) }volatile = ""@@ -256,7 +236,7 @@ final class SpeakEngine {func pressCancelled() {guard phase == .listening else { return }stopMic()- utterance?.input.finish()+ if let input = utterance?.input { Task { await input.cancel() } }utterance = nilmicQueue.sync { pressSamples = [] }finals = []@@ -306,7 +286,7 @@ final class SpeakEngine {let conv = PCMConverter()for buf in buffers {if let c = conv.convert(buf, to: format) {- input.yield(AnalyzerInput(buffer: c))+ input.append(c)micQueue.sync { keepForMing(c) }}let seconds = Double(buf.frameLength) / buf.format.sampleRate@@ -317,7 +297,7 @@ final class SpeakEngine {return true}- private func startMic(format: AVAudioFormat, input cont: AsyncStream<AnalyzerInput>.Continuation) {+ private func startMic(format: AVAudioFormat, input cont: RecognitionStream) {let inputNode = mic.inputNodeAudioDevices.pinInput(mic, to: inputDevice?())let inFormat = inputNode.outputFormat(forBus: 0)@@ -334,7 +314,7 @@ final class SpeakEngine {queue.async {guard let self, self.feeding else { return }if let c = conv.convert(buf, to: format) {- cont.yield(AnalyzerInput(buffer: c))+ cont.append(c)self.recordMic(c)self.keepForMing(c)}@@ -396,7 +376,7 @@ final class SpeakEngine {self.probe = nilguard let u = utterance else { phase = .idle; probe?.finish(); return }utterance = nil- u.input.finish()+ Task { await u.input.finish() }let released = releasedAt ?? Date()releasedAt = nillet wav = takePressWAV()@@ -493,19 +473,7 @@ final class SpeakEngine {private func synthesize(_ text: String, language: String, voiceID: String?) async -> [AVAudioPCMBuffer] {let u = AVSpeechUtterance(string: text)u.voice = voice(for: language, identifier: voiceID)- return await withCheckedContinuation { cont in- var buffers: [AVAudioPCMBuffer] = []- var done = false- synth.write(u) { buf in- guard !done else { return }- guard let pcm = buf as? AVAudioPCMBuffer, pcm.frameLength > 0 else {- done = true- cont.resume(returning: buffers)- return- }- buffers.append(pcm)- }- }+ return await SpeechWriter.write(u, with: synth)}/// `device` overrides the chosen output (the virtual mic sound test).@@ -640,3 +608,38 @@ final class SpeakEngine {Task { await speak(targetCode.hasPrefix("zh") ? "这是对方会听到的声音。" : "This is the voice the room will hear.", language: targetCode) }}}++/// The Mac's voice rendered to buffers. `AVSpeechSynthesizer.write` ends with an empty buffer, but+/// on macOS 14 that last buffer never comes (all the audio does): the delegate's didFinish, which+/// does come, ends it too, whichever is first.+final class SpeechWriter: NSObject, AVSpeechSynthesizerDelegate, @unchecked Sendable {+ private let lock = NSLock()+ private var buffers: [AVAudioPCMBuffer] = []+ private var cont: CheckedContinuation<[AVAudioPCMBuffer], Never>?++ static func write(_ u: AVSpeechUtterance, with synth: AVSpeechSynthesizer) async -> [AVAudioPCMBuffer] {+ let writer = SpeechWriter()+ let previous = synth.delegate+ synth.delegate = writer+ defer { synth.delegate = previous }+ return await withCheckedContinuation { cont in+ writer.cont = cont+ synth.write(u) { buf in+ guard let pcm = buf as? AVAudioPCMBuffer, pcm.frameLength > 0 else { writer.end(); return }+ writer.lock.withLock { writer.buffers.append(pcm) }+ }+ }+ }++ private func end() {+ let done = lock.withLock { () -> (CheckedContinuation<[AVAudioPCMBuffer], Never>, [AVAudioPCMBuffer])? in+ guard let c = cont else { return nil }+ cont = nil+ return (c, buffers)+ }+ done?.0.resume(returning: done!.1)+ }++ func speechSynthesizer(_ s: AVSpeechSynthesizer, didFinish u: AVSpeechUtterance) { end() }+ func speechSynthesizer(_ s: AVSpeechSynthesizer, didCancel u: AVSpeechUtterance) { end() }+}diff --git a/Sources/LiveSubs/SpeakTest.swift b/Sources/LiveSubs/SpeakTest.swiftindex ebf3dcc..57e8e47 100644--- a/Sources/LiveSubs/SpeakTest.swift+++ b/Sources/LiveSubs/SpeakTest.swift@@ -515,19 +515,7 @@ final class SpeakTester: ObservableObject {let lang = locale.hasPrefix("zh") ? "zh-CN" : localeu.voice = AVSpeechSynthesisVoice.speechVoices().filter { $0.language == lang && !$0.voiceTraits.contains(.isNoveltyVoice) }.max { $0.quality.rawValue < $1.quality.rawValue } ?? AVSpeechSynthesisVoice(language: lang)- let buffers: [AVAudioPCMBuffer] = await withCheckedContinuation { cont in- var out: [AVAudioPCMBuffer] = []- var done = false- synth.write(u) { buf in- guard !done else { return }- guard let pcm = buf as? AVAudioPCMBuffer, pcm.frameLength > 0 else {- done = true- cont.resume(returning: out)- return- }- out.append(pcm)- }- }+ let buffers = await SpeechWriter.write(u, with: synth)_ = synthreturn buffers}@@ -535,11 +523,7 @@ final class SpeakTester: ObservableObject {/// The room's audio transcribed again in its language, downloading the model if needed.private static func transcribe(_ buffers: [AVAudioPCMBuffer], code: String) async -> String {let locale = sourceLanguages.first { $0.code == code }?.locale ?? (code == "zh-TW" ? "zh-TW" : code)- let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [], reportingOptions: [], attributeOptions: [])- if await AssetInventory.status(forModules: [t]) != .installed,- let req = try? await AssetInventory.assetInstallationRequest(supporting: [t]) {- try? await req.downloadAndInstall()- }+ try? await Recognition.install(locale)return await LoopbackTest.transcribe(buffers, locale: locale)}}diff --git a/Sources/LiveSubs/SystemAudioTap.swift b/Sources/LiveSubs/SystemAudioTap.swiftindex c4fe2c1..38bc9d7 100644--- a/Sources/LiveSubs/SystemAudioTap.swift+++ b/Sources/LiveSubs/SystemAudioTap.swift@@ -10,6 +10,24 @@ import Speech/// Captures the audio that is currently going to the default output device./// This uses Core Audio process taps, so it only needs the "System Audio/// Recording" privacy grant and never asks for Screen Recording.+/// Whether 系统音频录制 was allowed. Refused, the tap still starts and hears only silence, so+/// starting proves nothing; TCC's own preflight is the one way to tell (loaded at run time; nil+/// when it isn't there, and then starting is taken as allowed, as before).+enum SystemAudioPermission {+ enum Status { case granted, denied, unknown }++ static func status() -> Status? {+ typealias Preflight = @convention(c) (CFString, CFDictionary?) -> Int32+ guard let tcc = dlopen("/System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC", RTLD_LAZY),+ let sym = dlsym(tcc, "TCCAccessPreflight") else { return nil }+ switch unsafeBitCast(sym, to: Preflight.self)("kTCCServiceAudioCapture" as CFString, nil) {+ case 0: return .granted+ case 1: return .denied+ default: return .unknown+ }+ }+}+final class SystemAudioTap {/// Called on the real-time audio thread. Must not block.var onAudio: ((AVAudioPCMBuffer) -> Void)?diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftindex bf90e8e..ee2e526 100644--- a/Sources/LiveSubs/Translator.swift+++ b/Sources/LiveSubs/Translator.swift@@ -239,7 +239,9 @@ final class TranslationService {return out}+ /// Apple's on-device translation, made outside a SwiftUI view: only on macOS 26.private func viaApple(_ text: String, source: String, target: String) async -> String? {+ guard #available(macOS 26, *) else { return nil }guard source != "auto" else { return nil }let from = Locale.Language(identifier: Self.appleCode(source))let to = Locale.Language(identifier: Self.appleCode(target))diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex 3fffc48..963cb89 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -117,7 +117,8 @@ struct MenuPanelView: View {return [(nil, [("auto", auto.isEmpty ? L("自动识别") : L("自动识别(\(auto))"))]),(nil, ready.map { ($0.locale, $0.name) }),- (L("选中后自动下载语音模型"), missing.map { ($0.locale, $0.name) }),+ // macOS 14/15 can't download one: the language is added to Dictation in System Settings.+ (Recognition.legacy ? L("要先加进系统的听写语言") : L("选中后自动下载语音模型"), missing.map { ($0.locale, $0.name) }),]}diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swiftindex dfd82e8..d833bd4 100644--- a/Sources/LiveSubs/VirtualMic.swift+++ b/Sources/LiveSubs/VirtualMic.swift@@ -208,26 +208,7 @@ enum LoopbackTest {}static func transcribe(_ buffers: [AVAudioPCMBuffer], locale: String) async -> String {- let t = SpeechTranscriber(locale: Locale(identifier: locale), transcriptionOptions: [],- reportingOptions: [], attributeOptions: [])- guard await AssetInventory.status(forModules: [t]) == .installed,- let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t]) else { return "" }- let (stream, cont) = AsyncStream.makeStream(of: AnalyzerInput.self)- let conv = PCMConverter()- for b in buffers { if let c = conv.convert(b, to: format) { cont.yield(AnalyzerInput(buffer: c)) } }- cont.finish()- let collector = Task { () -> String in- var parts: [String] = []- do {- for try await r in t.results where r.isFinal {- parts.append(String(r.text.characters).trimmingCharacters(in: .whitespaces))- }- } catch {}- return parts.joined(separator: " ")- }- let analyzer = SpeechAnalyzer(inputSequence: stream, modules: [t])- try? await analyzer.finalizeAndFinishThroughEndOfInput()- return await collector.value+ await Recognition.transcribe(buffers, locale: locale)?.text ?? ""}}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex c82e85b..470339c 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -6,7 +6,6 @@ In rough order, and subject to change. Tell us what you need in Issues.**Next (Mac)**- **Recording what you say.** Cicada only hears what your Mac plays, so what you say into the meeting isn't captured; only the lines you speak while holding the talk key are recorded as "you". A switch will let it listen to your microphone throughout the meeting, so your proposals and the to-dos you take on make it into the transcript and notes. Without headphones, echo cancellation keeps the other side's voice from being recorded twice. While it's on, the microphone indicator in the menu bar stays lit.-- **Older macOS support (targeting macOS 14.4+).** Today Cicada requires macOS 26 because `SpeechAnalyzer` and offline translation are new in 26, even though system audio capture works from 14.2. On older versions, Cicada will fall back to the earlier on-device speech recognizer (fewer languages and lower accuracy). Offline translation works on macOS 15+, while macOS 14 will use online translation only.- **Developer ID signing and notarization.** Removes the "Open Anyway" prompt on first launch and stores the AI key in the macOS Keychain.- **Speaker recognition.** Speaker identification (experimental, since 1.0) already tells the other side's voices apart within a meeting, lets you rename them and names to-do owners, but forgets them when the meeting ends. Next, Cicada will remember frequent meeting participants by voice so they're named in the next meeting too. Because voiceprints are biometric data, they stay on your Mac, require opt-in, and can be deleted anytime.- **Local notes without an API key.** Use Apple's on-device model to generate meeting notes on supported Macs, keeping all audio and text local.diff --git a/docs/ROADMAP.zh-CN.md b/docs/ROADMAP.zh-CN.mdindex f030308..d63203b 100644--- a/docs/ROADMAP.zh-CN.md+++ b/docs/ROADMAP.zh-CN.md@@ -6,7 +6,6 @@**接下来(Mac)**- **记录我的发言**。现在知了只听电脑播放出来的声音,你在会上直接开口说的话录不到,只有按住说话键说的几句会记成“你”。之后会加一个开关,打开后开会时持续听麦克风,把你说的话也记进文字记录和纪要,你提的方案和答应的待办就不会漏掉。不戴耳机时会用回声消除,避免把扬声器里对方的声音再记一遍。开着时菜单栏的麦克风指示灯会一直亮。-- **支持更早的 macOS(目标 macOS 14.4 起)**。现在要求 macOS 26,是因为本机语音识别 `SpeechAnalyzer` 和离线翻译只在 26 上有,而系统声音采集从 14.2 起就支持了。旧系统上会换成较早的系统语音识别(准确率和支持的语言少一些),离线翻译在 15 起可用,14 上只用在线翻译。- **正式签名与公证**。首次打开不再需要去“隐私与安全性”里点“仍要打开”,AI key 也能放回系统钥匙串。- **声纹识别**。1.0 起的实验功能“说话人识别”已经能在一场会议里把对方的不同人分开、改名,待办也会标上是谁的,但会议结束就忘了。之后会记住常一起开会的人的声音,下次开会自动认出是谁。声纹属于敏感生物特征,只保存在本机,由你手动开启,随时可以删掉。- **不用 key 也有纪要**。在支持的 Mac 上用 Apple 的本机模型整理纪要,声音和文字都不出电脑。diff --git a/docs/macos-legacy-plan.md b/docs/macos-legacy-plan.mdnew file mode 100644index 0000000..12a6c0f--- /dev/null+++ b/docs/macos-legacy-plan.md@@ -0,0 +1,59 @@+# 知了 支持 macOS 14 / 15 技术方案++状态:已实现并验证(2026-11-04)。最低系统 14.4;在 macOS 26 本机和 macOS 14.5 虚拟机里都跑过主流程。++## 和 Windows / Android 的区别++Windows、Android 是另起的代码库,只共享规格。低版本 macOS **是同一个 app、同一个二进制**:`Package.swift` 和 `Info.plist` 的最低系统是 14.4,运行时按系统选识别引擎。26 上的行为不变。++## 差多少(实测)++把平台改成 14.2 / 15.0 编译,报出的“只在新系统可用”:++| API | 最低系统 | 处理 |+|---|---|---|+| `SpeechAnalyzer`、`SpeechTranscriber`、`AnalyzerInput`、`AssetInventory` | 26 | 收进 `Recognition.swift`,引擎只用它 |+| `TranslationSession(installedSource:target:)` | 26 | 离线翻译兜底只在 26;14 / 15 用 Ling → Google |+| `onScrollGeometryChange`、`pointerStyle` | 15 | `Compat.swift`:14 上纪要跟随不感知手动上翻,链接光标用 `NSCursor` |+| `AVAudioFile.close()` | 15 | 测试里改成出作用域关闭 |+| Core Audio process tap | 14.2 | 不动;下限定 14.4(“录制系统声音”权限从 14.4 起是独立的一项) |++## 实现++- `Recognition.swift`:`Recognition.start / transcribe / status / install / format / startNow`,协议 `RecognitionStream`。+ - 26:`Analyzer`,包住 `SpeechAnalyzer`,行为和原来一样。+ - 14.4–15:`LegacyStream`,用 `SFSpeechRecognizer`(`requiresOnDeviceRecognition`,声音不出电脑)。它没有“句子”:一句一个任务,停顿 0.7 秒或 `finalize` 时结束,满 45 秒强制结束。+ - `DeferredStream`:按住说话键时麦克风先开,识别器准备好再把缓存的声音交过去。+- `AudioRouter.attach(stream)` 喂 `RecognitionStream`;`ListenEngine`、`SpeakEngine`、`LanguageDetector`、`VirtualMic`、`SpeakTest`、`FileImport` 都改用它。导入文件在 26 上仍用 `SpeechAnalyzer(inputAudioFile:)`,旧系统按行喂给 `LegacyStream`,再按句号拆句、按字数估时间。+- 开发版 `lsctl recognizer:legacy` 或 `open --env CICADA_RECOGNIZER=legacy`:在 26 上跑旧引擎。++## 实测发现++1. **旧识别器要打开“听写”**(系统设置 › 键盘 › 听写,`com.apple.assistant.support` 的 `Dictation Enabled`)。关着时每个任务立刻失败(`kLSRErrorDomain` 201)。语言要加进听写语言才有本机模型(`supportsOnDeviceRecognition`)。引导第一步在旧系统上多一行“识别语音”,按钮先请求“语音识别”权限,再打开键盘设置;状态栏和面板提示“请在系统设置 › 键盘里打开“听写””或“……听写里添加 X”。+2. **两个识别任务不能同时跑**:同时跑时两边都回“No speech detected”(1110)。所以:上一句的结果回来前,下一句的声音先攒着(最多 6 秒);语言检测的短片段等实时那句结束后才跑(最多等 4 秒,等不到就跳过这次),跑的时候实时这边也先攒着。+3. **输出设备自带麦克风时读错声道**(与系统版本无关):聚合设备的输入是“输出设备自己的输入声道 + tap”,原来固定读前两个声道。输出设备有麦克风(虚拟机的声卡、USB 耳机)时读到的是麦克风。`SystemAudioTap` 现在用 `kAudioOutputUnitProperty_ChannelMap` 跳过这些声道。也因为聚合里有这个设备,这类设备上开始听会先弹“麦克风”权限。+4. 慢的 Mac(虚拟机没有神经引擎)一句话的结果可能比这句话还长才回来:兜底关句的超时是 10 秒 + 2 倍句长。+5. 权限顺序(14.5,首次开始听):麦克风(仅当输出设备带麦克风)→ 录制系统声音 → 语音识别。+6. 小屏幕(1024×768):菜单栏面板高约 700 点,放不下时顶部被推出屏幕。现在超过屏幕可用高度就在面板里滚动。主窗口、设置、引导、试一句都放得下。+7. 自动更新:以后的版本如果提高最低系统,旧 Mac 会装上打不开的版本。`Updater` 现在先看新版本的 `LSMinimumSystemVersion`,不满足就提示“新版本需要 macOS X 或更新版本”,不替换。+8. 文案:14 / 15 没有本机翻译,AI 服务页的“不行时换 Google、本机”在旧系统上去掉“本机”;“听到”菜单里没装的语言写“要先加进系统的听写语言”,而不是“选中后自动下载”。+10. **开会时按住说话键**(以及“会议室”模式,两边都用麦克风):两个实时识别同时跑会互相打断,会议那边只剩空句,你说的只剩最后几个词。旧系统上按住说话键时识别归你:会议那句当场结束,会议声音最多攒 6 秒,松开后接着识别(攒的全是静音就丢掉,时间戳不会提前)。26 上两边照旧同时跑。+11. **Mac 自带声音念译文卡住**:14.5 上 `AVSpeechSynthesizer.write` 给完所有音频后不发结尾的空缓冲(26 上会发),没有 Ling key 时的同声传译、“试一句”、虚拟麦克风试音都一直卡在“正在播放”。现在以结尾缓冲或代理的 didFinish 先到者为准(`SpeechWriter`)。虚拟麦克风(BlackHole)在虚拟机里能装:下载、校验 SHA-256、输管理员密码、加载、切换系统麦克风、试音都通过。+12. **拒绝过“录制系统声音”**:拒绝后 tap 照样能开,只是全是静音,引导却显示“已打开”。现在用 TCC 自己的预检(运行时加载,取不到就按原来的办法)判断:被拒时引导显示“去开启”和“重新打开”,状态栏提示去系统设置允许后重新打开知了。14 上这个开关在“屏幕与系统录音 › 仅系统录音”里;打开后要重开 app 才生效(系统自己也这么提示),从引导里重开不会跳过引导。+13. **首次打开(未公证)**:14 的拦截框是“来自身份不明的开发者”,只有“好”一个按钮;隐私与安全性里点“仍要打开”、输密码后还要再点一次“打开”。DMG 里第一步改成“点完成或好”,第三步改成“按提示输密码确认”。DMG 窗口、拖拽安装、正式版首次运行在 14.5 上都正常。+14. 在 14.5 上查过、没问题的:6 个系统设置跳转都到对的页面;纪要窗口默认不出现在截屏里,打开“共享屏幕时让对方看到”后出现;登录项能开。+9. 用到的 52 个 SF Symbols 在 14.5 上都存在(逐个在虚拟机里查过),不会显示成空白。++## 验证++- 单元测试 82 个通过(新增旧引擎拆句测试)。+- macOS 26 本机:26 引擎和 `recognizer:legacy` 都跑过;26 引擎回归正常。+- macOS 14.5 虚拟机(tart,`ghcr.io/cirruslabs/macos-sonoma-vanilla:14.4.1`,实际是 14.5):首次权限、引导、示例会议、实时字幕和翻译(Ling)、合并断句、实时纪要、会议记录、导入文件、按住说话(文件模拟)、中英文界面。截图在 `~/Downloads/cicada-macos14-test/`。+- 需要真人和真机:真 Mac 上 14.4 / 15 的权限对话框、外接带麦克风的耳机、中文听写模型的识别质量、长会议。++## 已知限制++- 旧系统只能识别加进“听写”的语言;自动识别要至少两种听写语言。+- 选了没加进听写的语言时会退回原来的语言,提示只闪一下(状态随后变回“正在听”)。+- 14 上纪要窗口里往上翻时,新句子仍会把视图拉到底部。+- 没有离线翻译(14 / 15);没有 Intel 版本。diff --git a/tools/README.md b/tools/README.mdindex 0542418..f2552bc 100644--- a/tools/README.md+++ b/tools/README.md@@ -15,6 +15,7 @@- 系统麦克风:`sysMic` 把状态、默认输入、要换回的麦克风和知了实际在录的麦克风写进日志,`sysMicSet:<设备名片段>` 假装别人改了系统麦克风,`sysMicRestore` 还原,`sysMicSwitch` 换成虚拟麦克风,`sysMicAuto:<on|off>`,`speakMic:<设备名片段>` 固定知了用的麦克风(留空 = 自动)。会改本机的系统麦克风:测完 `sysMicRestore` 或退出 App- 说话同传:`speakOn` / `speakOff` 开关,`speakAsk[:off]` 面板里第一次打开时的确认卡,`speakConfirmed:<on|off>` 是否已确认过,`speakFile:<音频>` 把文件按实时速度当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份,`speakOutput:<设备名片段>` 改输出设备(留空 = 虚拟麦克风)- 试一句:`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`- 导出:`export:<目录>`- 新手引导与窗口:`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`@@ -28,6 +29,8 @@- 更新与登录项:`updateFeed:<url>`、`updateCheck`、`updateInstall`、`updateState`、`loginItem[:on|off]`- 完整、最新的清单以 `AppModel.debugCommand` 里的 `switch` 为准。+- `macos-vm/vm.sh setup|start|deploy|listen|ssh|stop`:macOS 14 测试虚拟机(tart,镜像实际是 14.5),在旧识别引擎上跑开发版。第一次 `setup`(约 18 GB),之后 `start`、`deploy`(装 `build/Cicada.app`)、`listen en.aiff`(片段放在 `~/VMs/share`)。截图用 `screencapture -l <tart 窗口 ID>`,点按用虚拟机里的 `~/bin/mouse`。虚拟机的声卡带麦克风,开始听时会先弹“麦克风”权限。+## 测试技巧- 英文界面:`defaults write com.wquguru.cicada.dev AppleLanguages -array en` 后重启,测完 `defaults delete com.wquguru.cicada.dev AppleLanguages`;或启动时加 `--args -AppleLanguages "(en)"`。diff --git a/tools/macos-vm/vm.sh b/tools/macos-vm/vm.shnew file mode 100755index 0000000..339a344--- /dev/null+++ b/tools/macos-vm/vm.sh@@ -0,0 +1,64 @@+#!/bin/bash+# The macOS 14 test VM (tart, Apple silicon). Everything lives in ~/VMs: TART_HOME=~/VMs/tart, the+# SSH key ~/VMs/mac_key, the shared folder ~/VMs/share (/Volumes/My Shared Files/share in the VM).+# tools/macos-vm/vm.sh setup # once: pull the image (~18 GB), clone it, install the key and helpers+# tools/macos-vm/vm.sh start # boot it (window on screen), tunnel the host proxy into it+# tools/macos-vm/vm.sh deploy # install build/Cicada.app (a dev build) in the VM and launch it+# tools/macos-vm/vm.sh listen <clip in ~/VMs/share> [wait] # start listening, play the clip there, print the log+# tools/macos-vm/vm.sh ssh [command]+# tools/macos-vm/vm.sh stop+set -euo pipefail+here="$(cd "$(dirname "$0")" && pwd)"+repo="$(cd "$here/../.." && pwd)"+export TART_HOME="${TART_HOME:-$HOME/VMs/tart}"+TART="${TART:-$HOME/VMs/tools/tart/tart.app/Contents/MacOS/tart}"+NAME=cicada-macos14+IMAGE=ghcr.io/cirruslabs/macos-sonoma-vanilla:14.4.1 # ships macOS 14.5; user admin / admin+KEY="$HOME/VMs/mac_key"+SHARE="$HOME/VMs/share"+ip() { "$TART" ip "$NAME"; }+run() { ssh -i "$KEY" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR "admin@$(ip)" "$@"; }++case "${1:-}" in+setup)+ [ -x "$TART" ] || { echo "Get tart from https://github.com/openai/tart/releases (check the SHA-256 in its checksums file) into ~/VMs/tools/tart"; exit 1; }+ "$TART" pull "$IMAGE"+ "$TART" clone "$IMAGE" "$NAME"+ mkdir -p "$SHARE/tools"; [ -f "$KEY" ] || ssh-keygen -q -t ed25519 -N "" -f "$KEY"+ "$0" start+ expect -c "set timeout 30+ spawn ssh-copy-id -i $KEY.pub -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null admin@$(ip)+ expect { -re {[Pp]assword:} { send \"admin\r\"; exp_continue } eof }" >/dev/null+ # Helpers built for 14.4, and clicks from SSH allowed (SIP is off in this image).+ for t in lsctl mouse winall key; do swiftc -O -target arm64-apple-macos14.4 "$repo/tools/$t.swift" -o "$SHARE/tools/$t"; done+ run 'mkdir -p ~/bin && cp "/Volumes/My Shared Files/share/tools/"* ~/bin/+ for c in /usr/libexec/sshd-keygen-wrapper /Users/admin/bin/mouse; do for s in kTCCServiceAccessibility kTCCServicePostEvent; do+ sudo sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" "insert or replace into access (service,client,client_type,auth_value,auth_reason,auth_version,flags) values (\"$s\",\"$c\",1,2,4,1,0)"; done; done+ sudo killall tccd || true+ sudo networksetup -setwebproxy Ethernet 127.0.0.1 7890; sudo networksetup -setsecurewebproxy Ethernet 127.0.0.1 7890'+ ;;+start)+ pgrep -f "tart run $NAME" >/dev/null || { nohup "$TART" run "$NAME" --dir="share:$SHARE" >/dev/null 2>&1 & }+ until [ -n "$(ip 2>/dev/null)" ] && nc -z -w2 "$(ip)" 22 2>/dev/null; do sleep 2; done+ # The VM reaches Google and Ling through the host's proxy (127.0.0.1:7890 in the VM).+ pkill -f "ssh -N -i $KEY" || true+ nohup ssh -N -i "$KEY" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR \+ -o ServerAliveInterval=30 -R 7890:127.0.0.1:7890 "admin@$(ip)" >/dev/null 2>&1 &+ echo "VM at $(ip)"+ ;;+deploy)+ # A new file name each time: the shared folder keeps serving a replaced directory from its cache.+ n="cicada-$(date +%s).tgz"+ rm -f "$SHARE"/cicada-*.tgz+ tar -czf "$SHARE/$n" -C "$repo/build" Cicada.app+ run "pkill -x Cicada || true; sleep 1; rm -rf /Applications/Cicada.app; tar -xzf '/Volumes/My Shared Files/share/$n' -C /Applications+ : > /tmp/livesubs-dev-debug.log; open /Applications/Cicada.app; sleep 5; pgrep -lx Cicada"+ ;;+listen)+ run "~/bin/lsctl stop; sleep 1; : > /tmp/livesubs-dev-debug.log; ~/bin/lsctl start; sleep 3+ afplay '/Volumes/My Shared Files/share/$2'; sleep ${3:-8}; grep -v level /tmp/livesubs-dev-debug.log | cut -c1-200"+ ;;+ssh) shift; run "$@" ;;+stop) pkill -f "ssh -N -i $KEY" || true; "$TART" stop "$NAME" ;;+*) sed -n 2,10p "$0"; exit 1 ;;+esac