知了 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: add the Live Subs SwiftPM app with logo C and a dev build that runs beside the release
wquguru449c38353100
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..e986aff--- /dev/null+++ b/.gitignore@@ -0,0 +1,17 @@+# Build output+.build/+build/+.swiftpm/+.swift-module-cache/+*.xcodeproj/+*.app+*.icns+*.iconset/+*.dmg++# Local only: old backups, test screenshots, scratch+v1/+test-shots/++.DS_Store+!Resources/dmg/DS_Storediff --git a/Package.swift b/Package.swiftnew file mode 100644index 0000000..d09de8f--- /dev/null+++ b/Package.swift@@ -0,0 +1,12 @@+// swift-tools-version: 6.0+import PackageDescription++let package = Package(+ name: "LiveSubs",+ platforms: [.macOS("26.0")],+ targets: [+ .executableTarget(name: "LiveSubs", path: "Sources/LiveSubs"),+ .executableTarget(name: "LiveSubsIcon", path: "Sources/LiveSubsIcon"),+ ],+ swiftLanguageModes: [.v5]+)diff --git a/Resources/Info.plist b/Resources/Info.plistnew file mode 100644index 0000000..a96b46e--- /dev/null+++ b/Resources/Info.plist@@ -0,0 +1,42 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>zh_CN</string>+ <key>CFBundleDisplayName</key>+ <string>Live Subs</string>+ <key>CFBundleExecutable</key>+ <string>LiveSubs</string>+ <key>CFBundleIconFile</key>+ <string>AppIcon</string>+ <key>CFBundleIdentifier</key>+ <string>com.wquguru.cicada</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>Live Subs</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>2.0.0</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>LSApplicationCategoryType</key>+ <string>public.app-category.productivity</string>+ <key>LSMinimumSystemVersion</key>+ <string>26.0</string>+ <key>LSUIElement</key>+ <false/>+ <key>NSHighResolutionCapable</key>+ <true/>+ <key>NSHumanReadableCopyright</key>+ <string>Copyright © 2026 Live Subs</string>+ <key>NSAudioCaptureUsageDescription</key>+ <string>Live Subs 需要读取系统正在播放的声音,用于生成实时字幕。</string>+ <key>NSMicrophoneUsageDescription</key>+ <string>按住快捷键说话时,Live Subs 需要麦克风把你的话翻译成对方的语言。</string>+ <key>NSSpeechRecognitionUsageDescription</key>+ <string>Live Subs 需要语音识别权限,把音频转成文字。</string>+</dict>+</plist>diff --git a/Resources/sample/sample.m4a b/Resources/sample/sample.m4anew file mode 100644index 0000000..e0af067Binary files /dev/null and b/Resources/sample/sample.m4a differdiff --git a/Resources/sample/sample.mp4 b/Resources/sample/sample.mp4new file mode 100644index 0000000..182df05Binary files /dev/null and b/Resources/sample/sample.mp4 differdiff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftnew file mode 100644index 0000000..e39a09c--- /dev/null+++ b/Sources/LiveSubs/AppModel.swift@@ -0,0 +1,542 @@+import AppKit+import AVFoundation+import Carbon.HIToolbox+import Combine+import SwiftUI++/// Wires the engines, the meeting store, the subtitle bar and the UI together.+@MainActor+final class AppModel: ObservableObject {+ let settings = AppSettings()+ let store = SessionStore()+ let overlay = OverlayController()+ let hotkey = HotKey()+ let toggleKey = HotKey(id: 2, keyCode: kVK_ANSI_S, modifiers: controlKey | optionKey)+ lazy var listen = ListenEngine(settings: settings)+ lazy var speak = SpeakEngine(settings: settings)++ @Published var running = false+ @Published var status = "准备就绪"+ @Published var summary = ""+ @Published var installed: Set<String> = []+ @Published var candidates: [Lang] = []+ @Published var outputs: [OutputDevice] = []+ @Published var speakPhase: SpeakEngine.Phase = .idle+ @Published var showSettings = false+ @Published var systemAudioOK = false+ @Published var micStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .audio)+ @Published var liveSource = ""+ @Published var liveTranslation = ""+ @Published var onboardingStep = 1+ let installer = VirtualMicInstaller()+ let sample = SamplePlayer()+ var openOnboarding: (() -> Void)?++ var openMainWindow: (() -> Void)?+ var showPanel: (() -> Void)?++ private var lineForSegment: [Int: String] = [:]+ private var lineCounter = 0++ init() {+ listen.onSubtitle = { [weak self] src, dst in+ self?.liveSource = src+ self?.liveTranslation = dst+ self?.overlay.clearStatus()+ self?.overlay.setSubtitle(source: src, translation: dst)+ }+ listen.onStatus = { [weak self] text in+ self?.status = text+ self?.overlay.setStatus(text)+ }+ listen.onStateChange = { [weak self] in self?.refresh() }+ listen.onFinal = { [weak self] seg, duration in self?.recordHeard(seg, duration: duration) }+ listen.onTranslated = { [weak self] segID, text in+ guard let self, let line = self.lineForSegment[segID] else { return }+ self.store.setTranslation(lineID: line, text)+ }++ speak.translate = { [weak self] text, from, to in+ await self?.listen.translate(text, source: from, target: to)+ }+ speak.roomLanguage = { [weak self] in self?.listen.activeLang?.code }+ speak.onStatus = { [weak self] text in self?.status = text }+ speak.onLive = { [weak self] phase, src, dst in+ guard let self else { return }+ self.speakPhase = phase+ if !self.overlay.isShown { self.overlay.show() }+ if phase == .idle && src.isEmpty {+ self.overlay.setSpeaking(nil)+ } else {+ self.overlay.setSpeaking(.init(phase: phase, source: src, translation: dst))+ }+ }+ speak.onUtterance = { [weak self] src, dst, from, to, ago in+ self?.recordSaid(src, dst, from: from, to: to, secondsAgo: ago)+ }++ hotkey.onDown = { [weak self] in+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.speak.pressBegan() } }+ }+ hotkey.onUp = { [weak self] in+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.speak.pressEnded() } }+ }+ overlay.onCollapsed = { [weak self] in+ self?.listen.clearDisplay()+ self?.overlay.setSubtitle(source: "", translation: "")+ }+ overlay.mode = { [weak self] in+ (self?.settings.overlayAuto ?? true, self?.settings.overlayHideAfter ?? 4)+ }+ toggleKey.onDown = { [weak self] in+ DispatchQueue.main.async { MainActor.assumeIsolated { self?.overlay.toggleManual() } }+ }+ toggleKey.register()+ refreshOutputs()+ }++ func setOverlayAuto(_ on: Bool) {+ settings.overlayAuto = on+ overlay.modeChanged()+ objectWillChange.send()+ }++ func launch() async {+ await listen.refreshInstalledLocales()+ refresh()+ start()+ if settings.speakEnabled { enableSpeaking(true) }+ }++ func refresh() {+ running = listen.isRunning+ systemAudioOK = listen.isRunning+ summary = listen.languageSummary()+ candidates = listen.candidates+ installed = listen.installedLocales+ if running { status = listen.statusText }+ }++ func refreshOutputs() {+ outputs = AudioDevices.outputs()+ }++ var virtualMic: OutputDevice? { outputs.first(where: \.isVirtualMic) }++ // MARK: Permissions (all from the UI, no Terminal)++ func refreshPermissions() {+ let mic = AVCaptureDevice.authorizationStatus(for: .audio)+ if mic != micStatus { micStatus = mic }+ let devices = AudioDevices.outputs()+ if devices.map(\.uid) != outputs.map(\.uid) { outputs = devices }+ if systemAudioOK != listen.isRunning { systemAudioOK = listen.isRunning }+ }++ /// Starting the tap triggers the system prompt; if it still fails, open the pane.+ func requestSystemAudio() {+ if !listen.isRunning { start() }+ if !listen.isRunning {+ openSettingsPane("Privacy_ScreenCapture")+ }+ refreshPermissions()+ }++ func requestMicrophone() {+ AVCaptureDevice.requestAccess(for: .audio) { _ in+ DispatchQueue.main.async { MainActor.assumeIsolated { self.refreshPermissions() } }+ }+ }++ func openMicrophoneSettings() { openSettingsPane("Privacy_Microphone") }++ private func openSettingsPane(_ anchor: String) {+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?\(anchor)") {+ NSWorkspace.shared.open(url)+ }+ }++ func ensureListening() {+ if !listen.isRunning { start() }+ }++ func virtualMicInstalled() {+ refreshOutputs()+ // Core Audio restarts during the install; reattach the system-audio tap.+ listen.reconnectAudio()+ objectWillChange.send()+ }++ // MARK: Start / stop++ func start() {+ guard !listen.isRunning else { return }+ let session = store.begin()+ lineForSegment = [:]+ if settings.recordAudio {+ listen.router.setRecording(store.systemAudioURL(session.id))+ speak.setRecording(store.micAudioURL(session.id))+ }+ listen.start()+ if listen.isRunning {+ overlay.show()+ } else {+ store.end()+ }+ refresh()+ }++ func stop() {+ listen.stop()+ listen.router.setRecording(nil)+ speak.setRecording(nil)+ store.end()+ overlay.hide()+ refresh()+ }++ func setRunning(_ on: Bool) { on ? start() : stop() }++ // MARK: Settings actions++ var sourceSelection: String {+ get {+ if case .fixed(let l) = settings.sourceMode { return l.locale }+ return "auto"+ }+ set {+ settings.sourceMode = newValue == "auto" ? .auto+ : .fixed(sourceLanguages.first(where: { $0.locale == newValue }) ?? sourceLanguages[0])+ listen.sourceModeChanged()+ refresh()+ objectWillChange.send()+ }+ }++ var targetSelection: String {+ get { settings.target }+ set {+ settings.target = newValue+ listen.targetChanged()+ refresh()+ objectWillChange.send()+ }+ }++ func enableSpeaking(_ on: Bool) {+ settings.speakEnabled = on+ objectWillChange.send()+ if on {+ AVCaptureDevice.requestAccess(for: .audio) { granted in+ if !granted { debugLog("microphone permission denied") }+ }+ hotkey.register()+ refreshOutputs()+ Task { await speak.prepare() }+ } else {+ hotkey.unregister()+ Task { await speak.teardownAnalyzer() }+ }+ }++ func speakFromChanged() {+ objectWillChange.send()+ if settings.speakEnabled { Task { await speak.prepare() } }+ }++ // MARK: Meeting record++ private func recordHeard(_ seg: Segment, duration: Double) {+ guard let start = store.liveStart else { return }+ lineCounter += 1+ let id = "h\(lineCounter)-\(seg.id)"+ lineForSegment[seg.id] = id+ let t = max(0, Date().timeIntervalSince(start) - duration)+ store.append(TranscriptLine(id: id, t: t, speaker: "them", src: seg.text, dst: seg.translation,+ srcLang: seg.sourceCode, dstLang: listen.resolvedTarget))+ }++ private func recordSaid(_ src: String, _ dst: String, from: String, to: String, secondsAgo: Double) {+ guard let start = store.liveStart else { return }+ lineCounter += 1+ let t = max(0, Date().timeIntervalSince(start) - secondsAgo)+ store.append(TranscriptLine(id: "m\(lineCounter)", t: t, speaker: "me", src: src, dst: dst,+ srcLang: from, dstLang: to))+ }++ // MARK: Export++ func export(_ session: Session, kind: String) {+ if kind == "copy" {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(TranscriptExport.markdown(session), forType: .string)+ return+ }+ let panel = NSSavePanel()+ let ext = kind == "word" ? "docx" : kind == "srt" ? "srt" : "md"+ panel.nameFieldStringValue = "\(session.title).\(ext)"+ panel.canCreateDirectories = true+ guard panel.runModal() == .OK, let url = panel.url else { return }+ writeExport(session, kind: kind, to: url)+ }++ @discardableResult+ func writeExport(_ session: Session, kind: String, to url: URL) -> Bool {+ do {+ switch kind {+ case "word": try TranscriptExport.docx(session).write(to: url)+ case "srt": try TranscriptExport.srt(session).write(to: url, atomically: true, encoding: .utf8)+ default: try TranscriptExport.markdown(session).write(to: url, atomically: true, encoding: .utf8)+ }+ return true+ } catch {+ debugLog("export failed: \(error)")+ return false+ }+ }++ // MARK: Debug control (only with `defaults write com.wquguru.cicada debug -bool true`)++ func installDebugControl() {+ guard settings.debug || DevBuild.isDev else { return }+ DistributedNotificationCenter.default().addObserver(+ forName: Notification.Name("com.wquguru.cicada.debug"), object: nil, queue: .main+ ) { [weak self] note in+ let cmd = note.object as? String ?? ""+ MainActor.assumeIsolated { self?.debugCommand(cmd) }+ }+ debugLog("debug control ready")+ }++ private func debugCommand(_ cmd: String) {+ debugLog("debug command: \(cmd)")+ let parts = cmd.split(separator: ":", maxSplits: 1).map(String.init)+ let arg = parts.count > 1 ? parts[1] : ""+ switch parts.first ?? "" {+ case "start": start()+ case "stop": stop()+ case "open": openMainWindow?()+ case "panel": showPanel?()+ case "onboarding": onboardingStep = Int(arg) ?? 1; openOnboarding?()+ case "step": onboardingStep = Int(arg) ?? 1+ case "samplePlay": ensureListening(); sample.play()+ case "micVerify": installer.install(verifyOnly: true)+ case "settings": openMainWindow?(); showSettings = true+ case "speakOn": enableSpeaking(true)+ case "speakOff": enableSpeaking(false)+ case "speakOut": speak.debugOutputURL = arg.isEmpty ? nil : URL(fileURLWithPath: arg)+ case "speakFile": speak.speakFile(URL(fileURLWithPath: arg))+ case "place":+ let n = arg.split(separator: ",").compactMap { Double($0) }+ if n.count == 4 { overlay.place(x: n[0], y: n[1], width: n[2], fontSize: n[3]) }+ case "overlayState": debugLog("overlay \(overlay.stateDescription)")+ case "overlayToggle": overlay.toggleManual()+ case "overlayAuto": setOverlayAuto(arg != "off")+ case "hideAfter": settings.overlayHideAfter = Double(arg) ?? 4+ case "frame":+ debugLog("overlay frame=\(overlay.barFrame) font=\(overlay.currentFontSize)")+ case "export":+ guard let s = store.sessions.first(where: { $0.id != store.liveID }) ?? store.sessions.first else { return }+ let dir = URL(fileURLWithPath: arg)+ for (kind, ext) in [("md", "md"), ("srt", "srt"), ("word", "docx")] {+ let ok = writeExport(s, kind: kind, to: dir.appendingPathComponent("export.\(ext)"))+ debugLog("export \(ext) ok=\(ok)")+ }+ default: break+ }+ }+}++// MARK: - App delegate++@MainActor+final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {+ let model = AppModel()+ private var statusItem: NSStatusItem!+ private let popover = NSPopover()+ private var mainWindow: NSWindow?+ private var deviceListener: AudioObjectPropertyListenerBlock?+ private var deviceWork: DispatchWorkItem?+ private var onboardingWindow: NSWindow?+ private var pollTimer: Timer?+ private var runningObserver: Any?++ func applicationDidFinishLaunching(_ notification: Notification) {+ NSApp.setActivationPolicy(.accessory)+ setupStatusItem()+ model.openMainWindow = { [weak self] in self?.showMainWindow() }+ model.showPanel = { [weak self] in self?.togglePopover() }+ model.openOnboarding = { [weak self] in self?.showOnboarding() }+ runningObserver = model.$running.sink { [weak self] live in+ self?.statusItem.button?.image = BrandImage.menuBar(live: live)+ }+ let poll = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.model.refreshPermissions() }+ }+ pollTimer = poll+ RunLoop.main.add(poll, forMode: .common)+ if !UserDefaults.standard.bool(forKey: "onboarded") {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in+ MainActor.assumeIsolated { self?.showOnboarding() }+ }+ }+ model.installDebugControl()+ installDeviceListener()+ Task { await model.launch() }+ }++ func applicationWillTerminate(_ notification: Notification) {+ model.stop()+ }++ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {+ showMainWindow()+ return true+ }++ // MARK: Menu bar++ private func setupStatusItem() {+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)+ if let button = statusItem.button {+ button.image = BrandImage.menuBar(live: false)+ if DevBuild.isDev {+ button.imagePosition = .imageLeading+ button.attributedTitle = NSAttributedString(string: " DEV", attributes: [+ .font: NSFont.systemFont(ofSize: 9, weight: .heavy),+ .baselineOffset: 1,+ ])+ button.toolTip = "Live Subs Dev · \(DevBuild.label ?? "")"+ }+ button.action = #selector(togglePopover)+ button.target = self+ }+ popover.behavior = .transient+ popover.animates = false+ popover.contentViewController = NSHostingController(+ rootView: MenuPanelView(model: model, settings: model.settings)+ )+ }++ @objc private func togglePopover() {+ guard let button = statusItem.button else { return }+ if popover.isShown {+ popover.performClose(nil)+ } else {+ model.refreshOutputs()+ model.refresh()+ popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)+ popover.contentViewController?.view.window?.makeKey()+ }+ }++ // MARK: Main window++ func showMainWindow() {+ popover.performClose(nil)+ if mainWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1040, height: 700),+ styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],+ backing: .buffered, defer: false)+ w.title = DevBuild.isDev ? "Live Subs Dev" : "Live Subs"+ w.titlebarAppearsTransparent = true+ w.titleVisibility = .hidden+ w.isReleasedWhenClosed = false+ w.minSize = NSSize(width: 760, height: 480)+ w.delegate = self+ w.contentView = NSHostingView(rootView: MainWindowView(model: model, store: model.store, settings: model.settings))+ w.center()+ w.setFrameAutosaveName("LiveSubsMain")+ mainWindow = w+ }+ NSApp.setActivationPolicy(.regular)+ mainWindow?.makeKeyAndOrderFront(nil)+ NSApp.activate()+ }++ func showOnboarding() {+ popover.performClose(nil)+ if onboardingWindow == nil {+ let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 860, height: 640),+ styleMask: [.titled, .closable, .fullSizeContentView],+ backing: .buffered, defer: false)+ w.title = "欢迎使用 Live Subs"+ w.titlebarAppearsTransparent = true+ w.titleVisibility = .hidden+ w.isReleasedWhenClosed = false+ w.delegate = self+ w.contentView = NSHostingView(rootView: OnboardingView(+ model: model, settings: model.settings, installer: model.installer, sample: model.sample,+ onFinish: { [weak self] in+ UserDefaults.standard.set(true, forKey: "onboarded")+ self?.onboardingWindow?.close()+ }))+ w.center()+ onboardingWindow = w+ }+ NSApp.setActivationPolicy(.regular)+ onboardingWindow?.makeKeyAndOrderFront(nil)+ NSApp.activate()+ }++ func windowWillClose(_ notification: Notification) {+ let w = notification.object as? NSWindow+ if w == onboardingWindow {+ model.sample.stop()+ UserDefaults.standard.set(true, forKey: "onboarded")+ }+ let otherOpen = [mainWindow, onboardingWindow].contains { $0 != nil && $0 != w && $0!.isVisible }+ if !otherOpen { NSApp.setActivationPolicy(.accessory) }+ }++ // MARK: Output device changes++ private func installDeviceListener() {+ var addr = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDefaultOutputDevice,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let block: AudioObjectPropertyListenerBlock = { [weak self] _, _ in+ MainActor.assumeIsolated { self?.outputDeviceChanged() }+ }+ deviceListener = block+ AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &addr, DispatchQueue.main, block)+ }++ private func outputDeviceChanged() {+ deviceWork?.cancel()+ let work = DispatchWorkItem { [weak self] in+ MainActor.assumeIsolated {+ debugLog("default output device changed → reconnecting tap")+ self?.model.listen.reconnectAudio()+ self?.model.refreshOutputs()+ }+ }+ deviceWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6, execute: work)+ }+}++@main+struct LiveSubsMain {+ static func main() {+ let args = CommandLine.arguments+ if let i = args.firstIndex(of: "--render-dmg-background"), args.count > i + 1 {+ let scale = args.count > i + 2 ? Int(args[i + 2]) ?? 1 : 1+ do {+ try DMGBackground.render(to: URL(fileURLWithPath: args[i + 1]), scale: scale)+ exit(0)+ } catch {+ FileHandle.standardError.write("render failed: \(error)\n".data(using: .utf8)!)+ exit(1)+ }+ }+ MainActor.assumeIsolated {+ let app = NSApplication.shared+ let delegate = AppDelegate()+ app.delegate = delegate+ app.run()+ }+ }+}diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swiftnew file mode 100644index 0000000..14d28e2--- /dev/null+++ b/Sources/LiveSubs/AudioRouter.swift@@ -0,0 +1,200 @@+import AppKit+import AVFoundation+import AudioToolbox+import CoreAudio+import CoreMedia+import Speech++// MARK: - Audio routing++/// Stateful sample-rate / sample-format converter.+final class PCMConverter {+ private var converter: AVAudioConverter?++ func convert(_ input: AVAudioPCMBuffer, to format: AVAudioFormat) -> AVAudioPCMBuffer? {+ if input.format == format { return input }+ if converter == nil || converter!.inputFormat != input.format || converter!.outputFormat != format {+ converter = AVAudioConverter(from: input.format, to: format)+ }+ guard let converter else { return nil }+ let ratio = format.sampleRate / input.format.sampleRate+ let capacity = AVAudioFrameCount(Double(input.frameLength) * ratio) + 64+ guard let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else { return nil }+ var consumed = false+ var error: NSError?+ let status = converter.convert(to: out, error: &error) { _, outStatus in+ if consumed {+ outStatus.pointee = .noDataNow+ return nil+ }+ consumed = true+ outStatus.pointee = .haveData+ return input+ }+ if status == .error || out.frameLength == 0 { return nil }+ return out+ }+}++/// Moves audio off the real-time thread, converts it for the analyzer,+/// feeds the live transcriber, and keeps a short ring buffer for language detection.+final class AudioRouter: @unchecked Sendable {+ struct Stats {+ var voicedTotal: Double+ var silenceRun: Double+ /// Seconds of audio since the last pause of ≥ `gapSeconds`.+ var sinceGap: Double+ var recentVoiced: Double+ }++ static let gapSeconds = 1.5++ 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 ring: [(buffer: AVAudioPCMBuffer, seconds: Double, voiced: Bool)] = []+ private var ringSeconds = 0.0+ private let ringLimit = 10.0+ private var voicedTotal = 0.0+ private var silenceRun = 0.0+ private var sinceGap = 0.0++ private var recordURL: URL?+ private var recorder: AVAudioFile?++ /// Below this RMS the block counts as silence (≈ -40 dBFS).+ private let voiceThreshold: Float = 0.01++ func push(_ mono: AVAudioPCMBuffer) {+ queue.async { [self] in process(mono) }+ }++ private func process(_ mono: AVAudioPCMBuffer) {+ let n = Int(mono.frameLength)+ guard n > 0, let data = mono.floatChannelData else { return }+ var sum: Float = 0+ for i in 0..<n { sum += data[0][i] * data[0][i] }+ let rms = (sum / Float(n)).squareRoot()+ let seconds = Double(n) / mono.format.sampleRate+ let voiced = rms >= voiceThreshold+ if voiced {+ if silenceRun >= Self.gapSeconds { sinceGap = 0 }+ voicedTotal += seconds+ silenceRun = 0+ } else {+ silenceRun += seconds+ }+ sinceGap += seconds++ guard let format, let converted = converter.convert(mono, to: format) else { return }+ continuation?.yield(AnalyzerInput(buffer: converted))+ record(converted)+ ring.append((converted, seconds, voiced))+ ringSeconds += seconds+ while ringSeconds > ringLimit, !ring.isEmpty {+ ringSeconds -= ring.removeFirst().seconds+ }+ }++ /// `replaySeconds` re-feeds recent audio so a newly detected language+ /// doesn't lose the words spoken while detection was running.+ /// Starts writing everything the analyzer hears to an AAC file (nil stops).+ func setRecording(_ url: URL?) {+ queue.sync {+ recorder = nil // closes the previous file+ recordURL = url+ }+ }++ private func record(_ buffer: AVAudioPCMBuffer) {+ guard let url = recordURL else { return }+ if recorder == nil {+ recorder = AudioFileWriter.open(url, format: buffer.format)+ if recorder == nil { recordURL = nil; return }+ }+ try? recorder?.write(from: buffer)+ }++ func attach(format: AVAudioFormat, continuation: AsyncStream<AnalyzerInput>.Continuation, replaySeconds: Double = 0) {+ queue.sync {+ if self.format != format {+ ring.removeAll()+ ringSeconds = 0+ } else if replaySeconds > 0 {+ var acc = 0.0+ var replay: [AVAudioPCMBuffer] = []+ for item in ring.reversed() {+ if acc >= replaySeconds { break }+ acc += item.seconds+ replay.append(item.buffer)+ }+ for buffer in replay.reversed() { continuation.yield(AnalyzerInput(buffer: buffer)) }+ }+ self.format = format+ self.continuation?.finish()+ self.continuation = continuation+ }+ }++ func detach() {+ queue.sync {+ continuation?.finish()+ continuation = nil+ }+ }++ func reset() {+ queue.sync {+ continuation?.finish()+ continuation = nil+ ring.removeAll()+ ringSeconds = 0+ voicedTotal = 0+ silenceRun = 0+ sinceGap = 0+ }+ }++ func stats(window: Double = 6) -> Stats {+ queue.sync {+ var acc = 0.0, voiced = 0.0+ for item in ring.reversed() {+ if acc >= window { break }+ acc += item.seconds+ if item.voiced { voiced += item.seconds }+ }+ return Stats(voicedTotal: voicedTotal, silenceRun: silenceRun, sinceGap: sinceGap, recentVoiced: voiced)+ }+ }++ func snapshot(seconds: Double) -> [AVAudioPCMBuffer] {+ queue.sync {+ var acc = 0.0+ var out: [AVAudioPCMBuffer] = []+ for item in ring.reversed() {+ if acc >= seconds { break }+ acc += item.seconds+ out.append(item.buffer)+ }+ return out.reversed()+ }+ }+}+++enum AudioFileWriter {+ /// AAC .m4a, mono, at the buffer's sample rate. The processing format must+ /// match the buffers written to it exactly.+ static func open(_ url: URL, format: AVAudioFormat) -> AVAudioFile? {+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ let settings: [String: Any] = [+ AVFormatIDKey: kAudioFormatMPEG4AAC,+ AVSampleRateKey: format.sampleRate,+ AVNumberOfChannelsKey: Int(format.channelCount),+ AVEncoderBitRateKey: 32_000,+ ]+ return try? AVAudioFile(forWriting: url, settings: settings,+ commonFormat: format.commonFormat, interleaved: format.isInterleaved)+ }+}diff --git a/Sources/LiveSubs/DMGBackground.swift b/Sources/LiveSubs/DMGBackground.swiftnew file mode 100644index 0000000..eabf758--- /dev/null+++ b/Sources/LiveSubs/DMGBackground.swift@@ -0,0 +1,66 @@+import AppKit++/// `LiveSubs --render-dmg-background out.png <scale>` draws the installer window's background.+/// Finder places the icons on top of it at `appIcon` and `applicationsIcon`, so the art leaves+/// those spots empty. Keep in step with `scripts/dmg-template.sh`.+enum DMGBackground {+ static let size = CGSize(width: 640, height: 400)+ static let appIcon = CGPoint(x: 170, y: 205)+ static let applicationsIcon = CGPoint(x: 470, y: 205)++ private static let ink = NSColor(srgbRed: 0.082, green: 0.09, blue: 0.11, alpha: 1) // #15171C+ private static let secondary = NSColor(srgbRed: 0.353, green: 0.373, blue: 0.42, alpha: 1) // #5A5F6B+ private static let orange = NSColor(srgbRed: 0.91, green: 0.33, blue: 0.17, alpha: 1) // #E8552B++ static func render(to url: URL, scale: Int) throws {+ let rep = NSBitmapImageRep(+ bitmapDataPlanes: nil, pixelsWide: Int(size.width) * scale, pixelsHigh: Int(size.height) * scale,+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!+ rep.size = size+ guard let cg = NSGraphicsContext(bitmapImageRep: rep)?.cgContext else { throw CocoaError(.fileWriteUnknown) }+ // Flip to a y-down point space so coordinates match Finder's icon positions.+ cg.translateBy(x: 0, y: size.height)+ cg.scaleBy(x: 1, y: -1)+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(cgContext: cg, flipped: true)+ draw(cg)+ NSGraphicsContext.restoreGraphicsState()+ guard let png = rep.representation(using: .png, properties: [:]) else { throw CocoaError(.fileWriteUnknown) }+ try png.write(to: url)+ }++ private static func draw(_ ctx: CGContext) {+ ctx.setFillColor(CGColor(srgbRed: 0.965, green: 0.969, blue: 0.976, alpha: 1)) // #F6F7F9+ ctx.fill(CGRect(origin: .zero, size: size))++ text("把 Live Subs 拖进「应用程序」", size: 22, weight: .semibold, color: ink, centerX: size.width / 2, top: 40)+ text("然后在「应用程序」或启动台里打开它", size: 13, weight: .regular, color: secondary, centerX: size.width / 2, top: 76)++ // Dotted arrow from the app to Applications.+ ctx.setStrokeColor(orange.cgColor)+ ctx.setLineWidth(3)+ ctx.setLineCap(.round)+ ctx.setLineDash(phase: 0, lengths: [0.1, 9])+ let y = appIcon.y+ ctx.move(to: CGPoint(x: appIcon.x + 84, y: y))+ ctx.addLine(to: CGPoint(x: applicationsIcon.x - 92, y: y))+ ctx.strokePath()+ ctx.setLineDash(phase: 0, lengths: [])+ ctx.setLineJoin(.round)+ let tip = CGPoint(x: applicationsIcon.x - 80, y: y)+ ctx.move(to: CGPoint(x: tip.x - 11, y: y - 9))+ ctx.addLine(to: tip)+ ctx.addLine(to: CGPoint(x: tip.x - 11, y: y + 9))+ ctx.strokePath()++ text("第一次打开被拦住:系统设置 › 隐私与安全性 › 仍要打开", size: 12, weight: .regular,+ color: secondary, centerX: size.width / 2, top: 338)+ }++ private static func text(_ s: String, size: CGFloat, weight: NSFont.Weight, color: NSColor, centerX: CGFloat, top: CGFloat) {+ let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: size, weight: weight), .foregroundColor: color]+ let w = (s as NSString).size(withAttributes: attrs).width+ (s as NSString).draw(at: CGPoint(x: centerX - w / 2, y: top), withAttributes: attrs)+ }+}diff --git a/Sources/LiveSubs/DevBuild.swift b/Sources/LiveSubs/DevBuild.swiftnew file mode 100644index 0000000..a97fe58--- /dev/null+++ b/Sources/LiveSubs/DevBuild.swift@@ -0,0 +1,20 @@+import Foundation++/// A build run from a checkout rather than installed from a release, so the two can run side by+/// side and be told apart. `scripts/build.sh` without `RELEASE=1` stamps `LiveSubsDev` (branch and+/// commit) into Info.plist and gives the app its own bundle id (`com.wquguru.cicada.dev`): its own+/// settings, permissions, meeting records and log. `swift run` has no bundle at all.+enum DevBuild {+ /// Where it came from ("main @ 1b3d7f7"), "swift run", or nil for a release build.+ static let label: String? = {+ if let stamp = Bundle.main.object(forInfoDictionaryKey: "LiveSubsDev") as? String { return stamp }+ return Bundle.main.bundleIdentifier == nil ? "swift run" : nil+ }()++ static var isDev: Bool { label != nil }++ /// Folder name under ~/Library/Application Support.+ static var supportFolder: String { isDev ? "LiveSubs Dev" : "LiveSubs" }++ static var logPath: String { isDev ? "/tmp/livesubs-dev-debug.log" : "/tmp/livesubs-debug.log" }+}diff --git a/Sources/LiveSubs/LanguageDetector.swift b/Sources/LiveSubs/LanguageDetector.swiftnew file mode 100644index 0000000..e670beb--- /dev/null+++ b/Sources/LiveSubs/LanguageDetector.swift@@ -0,0 +1,88 @@+import AppKit+import AVFoundation+import AudioToolbox+import CoreAudio+import CoreMedia+import Speech++// MARK: - Spoken language detection++/// Detects the spoken language by transcribing the same short clip with+/// every installed on-device model and comparing how confident each one is.+/// The right model is typically ≥0.85 confident; wrong ones produce little+/// text or score well below that.+enum LanguageDetector {+ struct Candidate {+ let lang: Lang+ let confidence: Double+ let chars: Int+ let text: String+ let score: Double+ }++ static func rank(_ clip: [AVAudioPCMBuffer], candidates: [Lang]) async -> [Candidate] {+ await withTaskGroup(of: Candidate?.self) { group in+ for lang in candidates {+ group.addTask { await evaluate(clip, lang: lang) }+ }+ var out: [Candidate] = []+ for await c in group { if let c { out.append(c) } }+ return out.sorted { $0.score > $1.score }+ }+ }++ 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+ }+ }++ private static func score(conf: Double, chars: Int, text: String, lang: Lang) -> Double {+ guard chars > 0 else { return 0 }+ // Very short output means the model mostly heard noise.+ let lengthFactor = min(1.0, Double(chars) / 6.0)+ // A CJK model that mostly writes Latin letters is transcribing a foreign language.+ var scriptFactor = 1.0+ if ["ja", "zh-CN", "ko"].contains(lang.code) {+ let letters = text.unicodeScalars.filter { CharacterSet.letters.contains($0) }+ let latin = letters.filter { $0.isASCII }.count+ if !letters.isEmpty, Double(latin) / Double(letters.count) > 0.5 { scriptFactor = 0.75 }+ }+ return conf * lengthFactor * scriptFactor+ }+}+diff --git a/Sources/LiveSubs/Languages.swift b/Sources/LiveSubs/Languages.swiftnew file mode 100644index 0000000..6b78085--- /dev/null+++ b/Sources/LiveSubs/Languages.swift@@ -0,0 +1,62 @@+import AppKit+import AVFoundation+import AudioToolbox+import CoreAudio+import CoreMedia+import Speech++// MARK: - Languages++struct Lang: Equatable {+ let name: String+ /// Locale used by SpeechTranscriber.+ let locale: String+ /// Language code used by the translation endpoint.+ let code: String+}++let sourceLanguages: [Lang] = [+ .init(name: "English", locale: "en-US", code: "en"),+ .init(name: "日本語", locale: "ja-JP", code: "ja"),+ .init(name: "中文", locale: "zh-CN", code: "zh-CN"),+ .init(name: "한국어", locale: "ko-KR", code: "ko"),+ .init(name: "Español", locale: "es-ES", code: "es"),+ .init(name: "Français", locale: "fr-FR", code: "fr"),+ .init(name: "Deutsch", locale: "de-DE", code: "de"),+ .init(name: "Português", locale: "pt-BR", code: "pt"),+]++let targetLanguages: [Lang] = [+ .init(name: "简体中文", locale: "zh-Hans", code: "zh-CN"),+ .init(name: "繁體中文", locale: "zh-Hant", code: "zh-TW"),+ .init(name: "English", locale: "en", code: "en"),+ .init(name: "日本語", locale: "ja", code: "ja"),+ .init(name: "한국어", locale: "ko", code: "ko"),+ .init(name: "Español", locale: "es", code: "es"),+ .init(name: "Français", locale: "fr", code: "fr"),+ .init(name: "Deutsch", locale: "de", code: "de"),+ .init(name: "Português", locale: "pt", code: "pt"),+]++/// Maps a system language identifier ("zh-Hans-CA", "en-CA", "zh-TW") to a translation code.+func translationCode(forSystemLanguage id: String) -> String {+ let locale = Locale(identifier: id)+ let lang = locale.language.languageCode?.identifier ?? "en"+ guard lang == "zh" else { return lang }+ let script = locale.language.script?.identifier+ let region = locale.region?.identifier+ if script == "Hant" { return "zh-TW" }+ if script == nil, let region, ["TW", "HK", "MO"].contains(region) { return "zh-TW" }+ return "zh-CN"+}++func targetName(_ code: String) -> String {+ targetLanguages.first(where: { $0.code == code })?.name+ ?? Locale.current.localizedString(forIdentifier: code) ?? code+}++/// CJK text is joined without spaces.+func joiner(for code: String) -> String {+ (code.hasPrefix("zh") || code == "ja") ? "" : " "+}+diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftnew file mode 100644index 0000000..31ef701--- /dev/null+++ b/Sources/LiveSubs/ListenEngine.swift@@ -0,0 +1,490 @@+import AppKit+import AVFoundation+import CoreMedia+import Speech++struct Segment {+ let id: Int+ let text: String+ let sourceCode: String+ var translation: String?+}++/// System audio → language detection → on-device transcription → translation.+/// UI-free: it reports through the callbacks below.+@MainActor+final class ListenEngine {+ // Outputs+ var onSubtitle: ((_ source: String, _ translation: String) -> Void)?+ var onStatus: ((String) -> Void)?+ var onStateChange: (() -> Void)?+ /// A finished sentence; `secondsAgo` ≈ how long ago it started.+ var onFinal: ((Segment, _ secondsAgo: Double) -> Void)?+ var onTranslated: ((_ segmentID: Int, _ translation: String) -> Void)?++ let settings: AppSettings+ let router = AudioRouter()++ private(set) var isRunning = false+ private(set) var statusText = "准备就绪"+ private(set) var activeLang: Lang?+ private(set) var languageConfirmed = false+ private(set) var detecting = false+ private(set) var candidates: [Lang] = []+ private(set) var installedLocales: Set<String> = []++ private var audioTap: SystemAudioTap?+ private var analyzer: SpeechAnalyzer?+ private var resultsTask: Task<Void, Never>?+ private var generation = 0+ private var pendingSwitch: Lang?+ private var needsDetection = true+ private var nextPeriodicDetection = 30.0+ private var lastDetectionAt = Date.distantPast+ private var ambiguousDetections = 0+ private var failureStreak = 0++ private var segments: [Segment] = []+ private var nextSegmentID = 0+ private var volatileText = ""+ private var volatileTranslation = ""+ private var lastVolatileSent = ""+ private var volatileInFlight = false+ private var volatileEpoch = 0+ private var translateBackoffUntil = Date.distantPast+ private var tickTimer: Timer?++ init(settings: AppSettings) {+ self.settings = settings+ }++ var resolvedTarget: String { settings.resolvedTarget(source: activeLang?.code) }++ func languageSummary() -> String {+ let target = targetName(resolvedTarget)+ switch settings.sourceMode {+ case .fixed(let lang):+ return "\(lang.name) → \(target)"+ case .auto:+ guard let lang = activeLang else { return "自动识别 → \(target)" }+ if detecting || !languageConfirmed { return "\(lang.name)(识别中…)→ \(target)" }+ return "\(lang.name) → \(target)"+ }+ }++ private func setStatus(_ text: String) {+ statusText = text+ onStatus?(text)+ onStateChange?()+ }++ // MARK: Models++ func refreshInstalledLocales() async {+ let installed = await SpeechTranscriber.installedLocales+ installedLocales = Set(installed.map { $0.identifier(.bcp47) })+ candidates = sourceLanguages.filter { installedLocales.contains($0.locale) }+ debugLog("installed speech models: \(installedLocales.sorted()) candidates=\(candidates.map(\.locale))")+ onStateChange?()+ }++ // MARK: Start / stop++ func start() {+ guard !isRunning else { return }+ guard SpeechTranscriber.isAvailable else {+ setStatus("此 Mac 不支持本机语音识别")+ return+ }+ languageConfirmed = false+ pendingSwitch = nil+ needsDetection = true+ nextPeriodicDetection = 30+ ambiguousDetections = 0+ lastDetectionAt = .distantPast+ debugLog("listen start mode=\(settings.sourceMode) target=\(resolvedTarget)")++ guard startTap() else { return }+ isRunning = true+ startTickTimer()++ let initial: Lang+ switch settings.sourceMode {+ case .fixed(let lang):+ initial = lang+ case .auto:+ let last = UserDefaults.standard.string(forKey: "lastDetected")+ initial = candidates.first(where: { $0.locale == last }) ?? candidates.first ?? sourceLanguages[0]+ }+ setStatus("正在听")+ Task { await switchTranscriber(to: initial) }+ }++ func stop() {+ isRunning = false+ generation += 1+ tickTimer?.invalidate()+ tickTimer = nil+ audioTap?.stop()+ audioTap = nil+ router.reset()+ resultsTask?.cancel()+ resultsTask = nil+ if let analyzer {+ Task { await analyzer.cancelAndFinishNow() }+ }+ analyzer = nil+ segments.removeAll()+ volatileText = ""+ volatileTranslation = ""+ lastVolatileSent = ""+ volatileInFlight = false+ detecting = false+ setStatus("已暂停")+ }++ func reconnectAudio() {+ guard isRunning else { return }+ audioTap?.stop()+ audioTap = nil+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in+ MainActor.assumeIsolated {+ guard let self, self.isRunning else { return }+ if self.startTap() { self.setStatus("正在听") }+ }+ }+ }++ @discardableResult+ private func startTap() -> Bool {+ let tap = SystemAudioTap()+ let router = self.router+ tap.onAudio = { pcm in router.push(pcm) }+ do {+ try tap.start()+ audioTap = tap+ debugLog("audio tap started")+ return true+ } catch {+ debugLog("audio tap start failed: \(error)")+ isRunning = false+ setStatus("无法读取系统音频,请在系统设置里允许“系统音频录制”")+ return false+ }+ }++ // MARK: Settings changes++ func sourceModeChanged() {+ languageConfirmed = false+ pendingSwitch = nil+ needsDetection = true+ if isRunning, case .fixed(let lang) = settings.sourceMode {+ Task { await switchTranscriber(to: lang) }+ }+ onStateChange?()+ }++ func targetChanged() {+ retranslateVisible()+ onStateChange?()+ }++ func redetect() {+ guard isRunning, settings.sourceMode == .auto else { return }+ languageConfirmed = false+ pendingSwitch = nil+ needsDetection = true+ ambiguousDetections = 0+ lastDetectionAt = .distantPast+ onStateChange?()+ }++ // MARK: Transcriber++ private func ensureModel(for transcriber: SpeechTranscriber, lang: Lang) async throws {+ let status = await AssetInventory.status(forModules: [transcriber])+ if status == .installed { return }+ debugLog("model status for \(lang.locale): \(status)")+ guard status != .unsupported else {+ throw NSError(domain: "LiveSubsSpeech", code: 1,+ userInfo: [NSLocalizedDescriptionKey: "本机不支持\(lang.name)识别"])+ }+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {+ setStatus("正在下载 \(lang.name) 语音模型…")+ try await request.downloadAndInstall()+ await refreshInstalledLocales()+ }+ }++ private func switchTranscriber(to lang: Lang, replaySeconds: Double = 0) async {+ generation += 1+ let gen = generation+ router.detach()+ resultsTask?.cancel()+ resultsTask = nil+ if let old = analyzer {+ analyzer = nil+ await old.cancelAndFinishNow()+ }+ guard isRunning, gen == generation else { return }++ if activeLang != lang {+ segments.removeAll()+ }+ activeLang = lang+ volatileText = ""+ volatileTranslation = ""+ lastVolatileSent = ""+ volatileEpoch += 1+ onStateChange?()++ 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)+ guard isRunning, gen == generation else {+ await analyzer.cancelAndFinishNow()+ return+ }+ let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self, bufferingPolicy: .bufferingNewest(400))+ router.attach(format: format, continuation: continuation, replaySeconds: replaySeconds)+ self.analyzer = analyzer+ resultsTask = Task { [weak self] in+ do {+ for try await result in transcriber.results {+ self?.handle(result, generation: gen)+ }+ } catch {+ self?.recognitionFailed(error, generation: gen)+ }+ }+ try await analyzer.start(inputSequence: stream)+ debugLog("transcriber started locale=\(lang.locale) format=\(format)")+ setStatus("正在听")+ } catch {+ debugLog("transcriber start failed locale=\(lang.locale): \(error)")+ recognitionFailed(error, generation: gen)+ }+ }++ private func recognitionFailed(_ error: Error, generation gen: Int) {+ guard gen == generation, isRunning else { return }+ debugLog("recognition error: \(error)")+ failureStreak += 1+ let delay = min(30.0, 2.0 * pow(2.0, Double(failureStreak - 1)))+ setStatus("识别出错,\(Int(delay)) 秒后重试")+ guard let lang = activeLang else { return }+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in+ MainActor.assumeIsolated {+ guard let self, self.isRunning, gen == self.generation else { return }+ Task { await self.switchTranscriber(to: lang) }+ }+ }+ }++ private func handle(_ result: SpeechTranscriber.Result, generation gen: Int) {+ guard gen == generation, isRunning else { return }+ failureStreak = 0+ let text = String(result.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)+ if result.isFinal {+ volatileText = ""+ volatileEpoch += 1+ guard !text.isEmpty 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 provisional = volatileTranslation.isEmpty ? nil : volatileTranslation+ let seg = Segment(id: nextSegmentID, text: text, sourceCode: activeLang?.code ?? "auto", translation: provisional)+ nextSegmentID += 1+ segments.append(seg)+ if segments.count > 8 { segments.removeFirst(segments.count - 8) }+ volatileTranslation = ""+ lastVolatileSent = ""+ contentLog(String(format: "FINAL conf=%.2f [%@] %@", conf, activeLang?.locale ?? "?", text))+ let duration = max(0, CMTimeGetSeconds(result.range.duration))+ // Only confirmed-language sentences go into the meeting record.+ if settings.sourceMode != .auto || languageConfirmed {+ onFinal?(seg, duration.isFinite ? duration : 0)+ }+ translateSegment(id: seg.id)+ if settings.sourceMode == .auto, conf < 0.6, text.count >= 4 {+ needsDetection = true+ }+ } else {+ volatileText = text+ }+ renderSubtitles()+ }++ private func renderSubtitles() {+ guard !(segments.isEmpty && volatileText.isEmpty) else { return }+ let srcJoin = joiner(for: activeLang?.code ?? "en")+ let source = [segments.last?.text ?? "", volatileText].filter { !$0.isEmpty }+ .joined(separator: srcJoin.isEmpty ? " " : srcJoin)+ if settings.sourceMode == .auto, !languageConfirmed, ambiguousDetections < 2 {+ onSubtitle?(source, "正在识别语言…")+ return+ }+ let tgtJoin = joiner(for: resolvedTarget)+ var parts = segments.suffix(3).compactMap(\.translation)+ if !volatileTranslation.isEmpty { parts.append(volatileTranslation) }+ onSubtitle?(source, parts.joined(separator: tgtJoin.isEmpty ? "" : " "))+ }++ // MARK: Language detection++ private func maybeDetectLanguage() {+ guard isRunning, settings.sourceMode == .auto, !detecting, candidates.count >= 2 else { return }+ var stats = router.stats(window: 6)+ if stats.silenceRun >= AudioRouter.gapSeconds { needsDetection = true }+ if stats.voicedTotal >= nextPeriodicDetection { needsDetection = true }+ guard needsDetection, Date().timeIntervalSince(lastDetectionAt) >= 3 else { return }+ let clipSeconds = min(6, stats.sinceGap)+ guard clipSeconds >= 3 else { return }+ stats = router.stats(window: clipSeconds)+ guard stats.recentVoiced >= 2.5 else { return }++ needsDetection = false+ lastDetectionAt = Date()+ detecting = true+ nextPeriodicDetection = stats.voicedTotal + 20+ onStateChange?()+ let clip = router.snapshot(seconds: clipSeconds)+ let candidates = self.candidates+ Task { [weak self] in+ let started = Date()+ let ranked = await LanguageDetector.rank(clip, candidates: candidates)+ guard let self else { return }+ self.detecting = false+ guard self.isRunning, self.settings.sourceMode == .auto else { return }+ let summary = ranked.map { String(format: "%@ s=%.2f c=%.2f n=%d", $0.lang.locale, $0.score, $0.confidence, $0.chars) }+ debugLog("detect (\(String(format: "%.2f", Date().timeIntervalSince(started)))s): \(summary.joined(separator: " | "))")+ self.applyDetection(ranked)+ self.onStateChange?()+ }+ }++ private func applyDetection(_ ranked: [LanguageDetector.Candidate]) {+ guard let best = ranked.first else { return }+ let runnerUp = ranked.dropFirst().first?.score ?? 0+ guard best.confidence >= 0.6, best.score - runnerUp >= 0.08 else {+ debugLog("detect: ambiguous, keeping \(activeLang?.locale ?? "-")")+ ambiguousDetections += 1+ if !languageConfirmed { needsDetection = true }+ renderSubtitles()+ return+ }+ if best.lang == activeLang {+ languageConfirmed = true+ pendingSwitch = nil+ UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")+ renderSubtitles()+ return+ }+ let currentScore = ranked.first(where: { $0.lang == activeLang })?.score ?? 0+ let overwhelming = best.score - currentScore >= 0.35+ if !languageConfirmed || overwhelming || pendingSwitch == best.lang {+ debugLog("detect: switching \(activeLang?.locale ?? "-") → \(best.lang.locale)")+ languageConfirmed = true+ pendingSwitch = nil+ UserDefaults.standard.set(best.lang.locale, forKey: "lastDetected")+ Task { await switchTranscriber(to: best.lang, replaySeconds: 8) }+ } else {+ pendingSwitch = best.lang+ needsDetection = true+ }+ }++ // MARK: Translation++ private func startTickTimer() {+ tickTimer?.invalidate()+ let timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated {+ self?.translateVolatile()+ self?.maybeDetectLanguage()+ }+ }+ tickTimer = timer+ RunLoop.main.add(timer, forMode: .common)+ }++ func translate(_ text: String, source: String, target: String? = nil) async -> String? {+ let target = target ?? resolvedTarget+ if source == target { return text }+ guard Date() >= translateBackoffUntil else { return nil }+ do {+ return try await GoogleTranslator.translate(text, source: source, target: target)+ } catch {+ debugLog("translate failed: \(error)")+ if case TranslateFailure.badResponse(429) = error {+ translateBackoffUntil = Date().addingTimeInterval(10)+ }+ if segments.allSatisfy({ $0.translation == nil }) && volatileTranslation.isEmpty {+ onSubtitle?(volatileText.isEmpty ? (segments.last?.text ?? "") : volatileText, "翻译暂不可用")+ }+ return nil+ }+ }++ private func translateSegment(id: Int) {+ guard let seg = segments.first(where: { $0.id == id }) else { return }+ Task { [weak self] in+ guard let self, let out = await self.translate(seg.text, source: seg.sourceCode) else { return }+ guard self.isRunning else { return }+ if let idx = self.segments.firstIndex(where: { $0.id == id }) {+ self.segments[idx].translation = out+ }+ contentLog("TRANSLATE [\(seg.sourceCode)→\(self.resolvedTarget)] \(seg.text) => \(out)")+ self.onTranslated?(id, out)+ self.renderSubtitles()+ }+ }++ private func translateVolatile() {+ guard isRunning, !volatileInFlight, volatileText.count >= 2, volatileText != lastVolatileSent else { return }+ let text = volatileText+ let epoch = volatileEpoch+ let source = activeLang?.code ?? "auto"+ lastVolatileSent = text+ volatileInFlight = true+ Task { [weak self] in+ guard let self else { return }+ let out = await self.translate(text, source: source)+ self.volatileInFlight = false+ guard let out, self.isRunning, epoch == self.volatileEpoch else { return }+ self.volatileTranslation = out+ self.renderSubtitles()+ }+ }++ /// After a quiet spell the next sentence starts on a clean bar.+ func clearDisplay() {+ segments.removeAll()+ volatileTranslation = ""+ lastVolatileSent = ""+ }++ private func retranslateVisible() {+ volatileTranslation = ""+ lastVolatileSent = ""+ for seg in segments.suffix(3) {+ if let idx = segments.firstIndex(where: { $0.id == seg.id }) { segments[idx].translation = nil }+ translateSegment(id: seg.id)+ }+ renderSubtitles()+ }+}diff --git a/Sources/LiveSubs/Onboarding.swift b/Sources/LiveSubs/Onboarding.swiftnew file mode 100644index 0000000..4d142c3--- /dev/null+++ b/Sources/LiveSubs/Onboarding.swift@@ -0,0 +1,447 @@+import AppKit+import AVFoundation+import AVKit+import SwiftUI++// MARK: - Brand mark (logo C: sound bars turning into lines of text)++private func logoBars(_ r: (CGFloat, CGFloat, CGFloat, CGFloat) -> CGRect) -> [(CGRect, Double)] {+ [(r(20, 42, 7, 16), 1), (r(31, 34, 7, 32), 1), (r(42, 40, 7, 20), 1), (r(57, 40, 24, 7), 1), (r(57, 53, 16, 7), 0.7)]+}++struct BrandMark: View {+ var size: CGFloat = 36+ var body: some View {+ Canvas { ctx, sz in+ let u = sz.width / 100+ func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> CGRect {+ CGRect(x: x * u, y: y * u, width: w * u, height: h * u)+ }+ ctx.fill(Path(roundedRect: r(4, 4, 92, 92), cornerRadius: 22 * u), with: .color(Palette.accent))+ for (rect, alpha) in logoBars(r) {+ ctx.fill(Path(roundedRect: rect, cornerRadius: min(rect.width, rect.height) / 2),+ with: .color(.white.opacity(alpha)))+ }+ }+ .frame(width: size, height: size)+ .accessibilityHidden(true)+ }+}++enum BrandImage {+ /// Menu bar template glyph: sound bars and text lines. Paused draws it at 40%.+ static func menuBar(live: Bool) -> NSImage {+ let img = NSImage(size: NSSize(width: 20, height: 16), flipped: true) { _ in+ NSColor.black.withAlphaComponent(live ? 1 : 0.4).setFill()+ // 100-unit logo design space scaled into 20 × 16 (bars are a little bolder at this size).+ let u: CGFloat = 0.22+ func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> NSRect {+ NSRect(x: (x - 14) * u, y: (y - 26) * u - 0.4, width: w * u + 0.6, height: h * u + 0.6)+ }+ for (rect, _) in logoBars(r) {+ NSBezierPath(roundedRect: rect, xRadius: min(rect.width, rect.height) / 2,+ yRadius: min(rect.width, rect.height) / 2).fill()+ }+ return true+ }+ img.isTemplate = true+ img.accessibilityDescription = "Live Subs"+ return img+ }+}++// MARK: - Sample clip++/// Plays the bundled 7-second sample. The picture shows in the onboarding card;+/// the sound is played by a separate `afplay` process, because the app leaves+/// its own audio out of what it listens to.+@MainActor+final class SamplePlayer: ObservableObject {+ @Published private(set) var playing = false+ @Published private(set) var progress = 0.0+ let player: AVPlayer?+ private var audio: Process?+ private var timer: Timer?+ private var started = Date()+ private let duration = 7.4++ init() {+ if let url = Bundle.main.url(forResource: "sample", withExtension: "mp4") {+ player = AVPlayer(url: url)+ player?.isMuted = true+ } else {+ player = nil+ }+ }++ func play() {+ guard !playing, let audioURL = Bundle.main.url(forResource: "sample", withExtension: "m4a") else { return }+ player?.seek(to: .zero)+ player?.play()+ let p = Process()+ p.executableURL = URL(fileURLWithPath: "/usr/bin/afplay")+ p.arguments = [audioURL.path]+ try? p.run()+ audio = p+ playing = true+ started = Date()+ progress = 0+ timer?.invalidate()+ let t = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.tick() }+ }+ timer = t+ RunLoop.main.add(t, forMode: .common)+ }++ private func tick() {+ progress = min(1, Date().timeIntervalSince(started) / duration)+ if progress >= 1 { stop() }+ }++ func stop() {+ timer?.invalidate()+ timer = nil+ if audio?.isRunning == true { audio?.terminate() }+ audio = nil+ player?.pause()+ playing = false+ }+}++struct PlayerSurface: NSViewRepresentable {+ let player: AVPlayer?+ func makeNSView(context: Context) -> AVPlayerView {+ let v = AVPlayerView()+ v.controlsStyle = .none+ v.videoGravity = .resizeAspectFill+ v.player = player+ return v+ }+ func updateNSView(_ nsView: AVPlayerView, context: Context) {}+}++// MARK: - Onboarding++struct OnboardingView: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings+ @ObservedObject var installer: VirtualMicInstaller+ @ObservedObject var sample: SamplePlayer+ private var step: Int {+ get { model.onboardingStep }+ nonmutating set { model.onboardingStep = newValue }+ }+ var onFinish: () -> Void++ var body: some View {+ VStack(alignment: .leading, spacing: 0) {+ header+ .padding(.top, 34)+ Group {+ switch step {+ case 1: permissions+ case 2: tryIt+ default: speaking+ }+ }+ .padding(.top, 28)+ Spacer(minLength: 0)+ footer+ }+ .padding(.horizontal, 64)+ .padding(.bottom, 36)+ .frame(width: 860, height: 640)+ .background(Color(red: 0.965, green: 0.969, blue: 0.976))+ .onChange(of: step) { _, _ in sample.stop() }+ }++ // MARK: Header / footer++ private var header: some View {+ HStack(spacing: 14) {+ BrandMark(size: 34)+ HStack(spacing: 6) {+ ForEach(1...3, id: \.self) { i in+ Capsule().fill(i <= step ? Palette.ink : Color(white: 0.87)).frame(height: 4)+ }+ }+ Text("\(step) / 3").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }++ private var footer: some View {+ HStack {+ if step == 1 {+ Button("以后再说") { step = 2 }.buttonStyle(.plain).foregroundStyle(Palette.secondary)+ } else {+ Button("上一步") { step -= 1 }.buttonStyle(.plain).foregroundStyle(Palette.secondary)+ }+ Spacer()+ if step == 1 && !model.systemAudioOK {+ Text("先打开“听电脑里的声音”")+ .font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.secondary)+ .padding(.horizontal, 24).frame(height: 44)+ .background(RoundedRectangle(cornerRadius: 12).fill(Color(white: 0.87)))+ } else {+ Button {+ if step < 3 { step += 1 } else { onFinish() }+ } label: {+ HStack(spacing: 8) {+ Text(step < 3 ? "继续" : "开始使用")+ if step < 3 { Image(systemName: "arrow.right") }+ }+ .font(.system(size: 14, weight: .semibold)).foregroundStyle(.white)+ .padding(.horizontal, 28).frame(height: 44)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.ink))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .keyboardShortcut(.defaultAction)+ }+ }+ .font(.system(size: 13))+ }++ private func title(_ text: String, _ sub: String) -> some View {+ VStack(alignment: .leading, spacing: 8) {+ Text(text).font(.system(size: 26, weight: .bold)).foregroundStyle(Palette.ink)+ Text(sub).font(.system(size: 14)).foregroundStyle(Palette.secondary)+ }+ }++ private func row<Trailing: View>(icon: String, tint: Color = Palette.ground, iconColor: Color = Palette.ink,+ title: String, tag: String? = nil, tagAccent: Bool = false, detail: String,+ @ViewBuilder trailing: () -> Trailing) -> some View {+ HStack(spacing: 16) {+ RoundedRectangle(cornerRadius: 12).fill(tint).frame(width: 44, height: 44)+ .overlay(Image(systemName: icon).font(.system(size: 18)).foregroundStyle(iconColor))+ VStack(alignment: .leading, spacing: 4) {+ HStack(spacing: 8) {+ Text(title).font(.system(size: 15, weight: .semibold)).foregroundStyle(Palette.ink)+ if let tag {+ Text(tag).font(.system(size: 11, weight: .semibold))+ .foregroundStyle(tagAccent ? Palette.accentInk : Palette.secondary)+ .padding(.horizontal, 7).padding(.vertical, 2)+ .background(Capsule().fill(tagAccent ? Palette.accentPale : Color(white: 0.94)))+ }+ }+ Text(detail).font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ Spacer()+ trailing()+ }+ .padding(.horizontal, 22).padding(.vertical, 20)+ }++ private func done(_ text: String) -> some View {+ Label(text, systemImage: "checkmark").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ }++ private func primary(_ text: String, _ action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Text(text).font(.system(size: 13, weight: .semibold)).foregroundStyle(.white)+ .padding(.horizontal, 16).frame(height: 36)+ .background(RoundedRectangle(cornerRadius: 10).fill(Palette.ink))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }++ private func secondary(_ text: String, _ action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Text(text).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink)+ .padding(.horizontal, 16).frame(height: 36)+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color(white: 0.84), lineWidth: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ }++ private var card: some ShapeStyle { Color.white }++ // MARK: Step 1++ private var permissions: some View {+ VStack(alignment: .leading, spacing: 24) {+ title("先打开两个开关", "去系统设置打开,回来会自动识别。")+ VStack(spacing: 0) {+ row(icon: "speaker.wave.2", title: "听电脑里的声音", tag: "必需", tagAccent: true, detail: "生成字幕用,不录屏幕") {+ if model.systemAudioOK { done("已打开") } else { primary("去打开") { model.requestSystemAudio() } }+ }+ Divider().padding(.horizontal, 22)+ row(icon: "mic", title: "麦克风", tag: "可选", detail: "说话翻译时才用") {+ switch model.micStatus {+ case .authorized: done("已允许")+ case .notDetermined: secondary("允许") { model.requestMicrophone() }+ default: secondary("去打开") { model.openMicrophoneSettings() }+ }+ }+ }+ .background(RoundedRectangle(cornerRadius: 18).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 18).stroke(Palette.line, lineWidth: 1))+ Label("声音只在本机识别", systemImage: "lock")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }++ // MARK: Step 2++ private var tryIt: some View {+ VStack(alignment: .leading, spacing: 22) {+ title("放一段视频试试", "点播放,看字幕出来。")+ ZStack {+ PlayerSurface(player: sample.player)+ if !sample.playing {+ Color.black.opacity(0.35)+ Button { model.ensureListening(); sample.play() } label: {+ Circle().fill(Color.white).frame(width: 64, height: 64)+ .overlay(Image(systemName: "play.fill").font(.system(size: 22)).foregroundStyle(Palette.ink).offset(x: 2))+ }+ .buttonStyle(.plain)+ .accessibilityLabel("播放示例视频")+ VStack {+ Spacer()+ HStack {+ Spacer()+ Text("示例 · 0:07").font(.system(size: 12)).foregroundStyle(.white.opacity(0.85))+ .padding(.horizontal, 8).padding(.vertical, 3)+ .background(RoundedRectangle(cornerRadius: 6).fill(.black.opacity(0.5)))+ }+ }+ .padding(12)+ }+ if sample.playing || !model.liveTranslation.isEmpty {+ VStack {+ GeometryReader { g in+ Rectangle().fill(Palette.accent).frame(width: g.size.width * sample.progress, height: 3)+ }+ .frame(height: 3)+ Spacer()+ VStack(spacing: 4) {+ Text(model.liveSource.isEmpty ? "正在听…" : model.liveSource)+ .font(.system(size: 13)).foregroundStyle(.white.opacity(0.65)).lineLimit(1).truncationMode(.head)+ Text(model.liveTranslation)+ .font(.system(size: 19, weight: .semibold)).foregroundStyle(.white).lineLimit(2).truncationMode(.head)+ }+ .multilineTextAlignment(.center)+ .padding(.horizontal, 20).padding(.vertical, 12)+ .frame(maxWidth: .infinity)+ .background(RoundedRectangle(cornerRadius: 14).fill(Color(white: 0.05, opacity: 0.9)))+ .padding(.horizontal, 40).padding(.bottom, 18)+ }+ }+ }+ .frame(height: 230)+ .clipShape(RoundedRectangle(cornerRadius: 18))+ .background(RoundedRectangle(cornerRadius: 18).fill(Color(red: 0.1, green: 0.11, blue: 0.13)))++ HStack(spacing: 12) {+ ChoiceRow(label: "听到", value: heardName, badge: nil, options: sourceOptions) { model.sourceSelection = $0 }+ ChoiceRow(label: "翻译成", value: targetName(model.listen.resolvedTarget),+ badge: settings.target == "system" ? "跟随系统" : nil, options: targetOptions) { model.targetSelection = $0 }+ }+ Text("字幕条可以拖动,拖右下角改大小。").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }++ private var heardName: String {+ if case .fixed(let l) = settings.sourceMode { return l.name }+ return model.listen.activeLang.map { "自动 · \($0.name)" } ?? "自动识别"+ }+ private var sourceOptions: [(id: String, title: String)] {+ [("auto", "自动识别")] + sourceLanguages.map { ($0.locale, $0.name) }+ }+ private var targetOptions: [(id: String, title: String)] {+ [("system", "跟随系统")] + targetLanguages.map { ($0.code, $0.name) }+ }++ // MARK: Step 3++ private var speaking: some View {+ VStack(alignment: .leading, spacing: 22) {+ HStack(alignment: .top, spacing: 24) {+ title("想让对方听懂你?", "按住说\(settings.speakFromLang.name),对方听到翻译后的语音。")+ Spacer()+ HStack(alignment: .bottom, spacing: 6) {+ key("⌥", "option", width: 58)+ key("", "space", width: 120)+ }+ }+ VStack(spacing: 0) {+ row(icon: "mic.badge.plus", tint: Palette.accentPale, iconColor: Palette.accentInk,+ title: "虚拟麦克风", detail: micDetail) {+ if model.virtualMic != nil {+ done("已安装")+ } else {+ switch installer.state {+ case .downloading: progressLabel("下载中…")+ case .installing: progressLabel("安装中…")+ default: primary("一键安装") { installer.install { model.virtualMicInstalled() } }+ }+ }+ }+ Divider().padding(.horizontal, 22)+ HStack(spacing: 16) {+ Text("按住说话").font(.system(size: 15, weight: .semibold))+ Spacer()+ Toggle("按住说话", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))+ .toggleStyle(.switch).labelsHidden().tint(Palette.ink)+ }+ .padding(.horizontal, 22).padding(.vertical, 16)+ Divider().padding(.horizontal, 22)+ HStack(spacing: 16) {+ Text("对方听到").font(.system(size: 15, weight: .semibold))+ Spacer()+ Picker("对方听到", selection: $settings.speakTo) {+ Text("跟着对方说的语言").tag("room")+ ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }+ }+ .labelsHidden().frame(width: 200)+ }+ .padding(.horizontal, 22).padding(.vertical, 14)+ }+ .background(RoundedRectangle(cornerRadius: 18).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 18).stroke(Palette.line, lineWidth: 1))++ if model.virtualMic != nil {+ (Text("在会议软件里,把麦克风选成 ") + Text(model.virtualMic?.name ?? "BlackHole 2ch").bold())+ .font(.system(size: 13)).foregroundStyle(Palette.ink)+ .padding(.horizontal, 16).padding(.vertical, 12)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.accentPale))+ } else if case .failed(let msg) = installer.state {+ Text(msg).font(.system(size: 13)).foregroundStyle(Palette.accentInk)+ }+ }+ }++ private var micDetail: String {+ if model.virtualMic != nil { return "已装好" }+ return "需要输一次电脑密码"+ }++ private func progressLabel(_ text: String) -> some View {+ HStack(spacing: 8) {+ ProgressView().controlSize(.small)+ Text(text).font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }++ private func key(_ top: String, _ bottom: String, width: CGFloat) -> some View {+ VStack(alignment: .leading) {+ Text(top).frame(maxWidth: .infinity, alignment: .trailing)+ Spacer(minLength: 0)+ Text(bottom)+ }+ .font(.system(size: 11)).foregroundStyle(Palette.secondary)+ .padding(.horizontal, 8).padding(.vertical, 6)+ .frame(width: width, height: 52)+ .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color(white: 0.84), lineWidth: 1))+ .overlay(alignment: .bottom) {+ RoundedRectangle(cornerRadius: 10).fill(Color(white: 0.84)).frame(height: 3).padding(.horizontal, 1)+ }+ }+}diff --git a/Sources/LiveSubs/Overlay.swift b/Sources/LiveSubs/Overlay.swiftnew file mode 100644index 0000000..f9dac93--- /dev/null+++ b/Sources/LiveSubs/Overlay.swift@@ -0,0 +1,590 @@+import AppKit++/// The floating subtitle bar.+/// - Auto mode: appears when someone speaks; after a few quiet seconds it+/// tucks away into a small dot (hover the dot to peek at the last line).+/// - Always click-through. When the pointer passes over it, it fades to 15%+/// so whatever is underneath stays visible and clickable.+/// - Rest the pointer on it for 0.6 s to edit: outline + corner grip.+/// - Drag anywhere to move (snaps to the screen's centre line).+/// - Drag the bottom-right grip to scale; the font scales with the width.+/// - Double-click to return to the default spot.+/// - Position, width and size are remembered per display.+@MainActor+final class OverlayController {+ struct Speaking {+ var phase: SpeakEngine.Phase+ var source: String+ var translation: String+ }++ private let panel: OverlayPanel+ private let view: OverlayView+ private var hoverTimer: Timer?+ private var speakClearWork: DispatchWorkItem?++ /// "auto" or "always", and seconds of quiet before tucking away.+ var mode: () -> (auto: Bool, hideAfter: Double) = { (true, 4) }+ /// Called when the bar tucks away after a quiet spell.+ var onCollapsed: (() -> Void)?+ private(set) var expanded = true+ private(set) var manualHidden = false+ private(set) var dimmed = false+ private var peeking = false+ private var lastContentAt = Date()+ private var lastMouse = NSPoint.zero+ private var stillFor = 0.0+ private static let pollInterval = 0.05++ private(set) var isShown = false+ private var width: CGFloat = 900+ private var fontSize: CGFloat = 28+ private var origin = NSPoint.zero+ private var screenKey = ""++ static let margin: CGFloat = 10++ init() {+ view = OverlayView(frame: NSRect(x: 0, y: 0, width: 900, height: 160))+ panel = OverlayPanel(contentRect: view.frame, styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered, defer: false)+ panel.level = .screenSaver+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary]+ panel.isOpaque = false+ panel.backgroundColor = .clear+ panel.hasShadow = false+ panel.ignoresMouseEvents = true+ panel.hidesOnDeactivate = false+ panel.isReleasedWhenClosed = false+ panel.animationBehavior = .none+ panel.contentView = view+ view.controller = self+ }++ // MARK: Content++ func setSubtitle(source: String, translation: String) {+ let changed = source != view.source || translation != view.translation+ view.source = source+ view.translation = translation+ view.needsDisplay = true+ if changed && !(source.isEmpty && translation.isEmpty) {+ lastContentAt = Date()+ expand()+ }+ }++ func setStatus(_ text: String) {+ guard view.source.isEmpty && view.translation.isEmpty || view.isStatus else { return }+ view.source = ""+ view.translation = text+ view.isStatus = true+ view.needsDisplay = true+ }++ func clearStatus() {+ if view.isStatus {+ view.translation = ""+ view.isStatus = false+ }+ }++ func setSpeaking(_ s: Speaking?) {+ speakClearWork?.cancel()+ if s != nil {+ lastContentAt = Date()+ expand()+ }+ if let s, s.phase == .idle {+ // Leave the last thing you said up for a few seconds.+ view.speaking = s+ let work = DispatchWorkItem { [weak self] in+ MainActor.assumeIsolated {+ self?.view.speaking = nil+ self?.layout()+ }+ }+ speakClearWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: work)+ } else {+ view.speaking = s+ }+ layout()+ }++ // MARK: Show / hide++ func show() {+ restore()+ isShown = true+ manualHidden = false+ // Auto mode starts tucked away until someone speaks.+ setExpanded(!mode().auto, animated: false)+ layout()+ panel.alphaValue = 1+ panel.orderFrontRegardless()+ hoverTimer?.invalidate()+ let t = Timer(timeInterval: Self.pollInterval, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated { self?.pollHover() }+ }+ hoverTimer = t+ RunLoop.main.add(t, forMode: .common)+ }++ func hide() {+ isShown = false+ hoverTimer?.invalidate()+ hoverTimer = nil+ setHover(false)+ panel.orderOut(nil)+ }++ // MARK: Expand / collapse++ private func expand() {+ guard isShown, !manualHidden, !expanded else { return }+ setExpanded(true, animated: true)+ }++ private func setExpanded(_ on: Bool, animated: Bool) {+ expanded = on+ if !on {+ onCollapsed?()+ dimmed = false+ stillFor = 0+ setHover(false)+ }+ guard animated else {+ view.collapsed = !on+ view.needsDisplay = true+ panel.alphaValue = manualHidden ? 0 : 1+ return+ }+ if on {+ view.collapsed = false+ view.needsDisplay = true+ panel.alphaValue = 0+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.2+ panel.animator().alphaValue = 1+ }+ } else {+ NSAnimationContext.runAnimationGroup({ ctx in+ ctx.duration = 0.35+ panel.animator().alphaValue = 0+ }, completionHandler: { [weak self] in+ MainActor.assumeIsolated {+ guard let self, !self.expanded else { return }+ self.view.collapsed = true+ self.view.needsDisplay = true+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.2+ self.panel.animator().alphaValue = 1+ }+ }+ })+ }+ }++ /// ⌃⌥S: hide everything now, or bring the bar back.+ func toggleManual() {+ guard isShown else { return }+ if manualHidden || !expanded {+ manualHidden = false+ lastContentAt = Date()+ setExpanded(true, animated: true)+ } else {+ manualHidden = true+ setHover(false)+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = 0.2+ panel.animator().alphaValue = 0+ }+ }+ }++ func modeChanged() {+ if !mode().auto { lastContentAt = Date(); expand() }+ }++ var stateDescription: String {+ "shown=\(isShown) expanded=\(expanded) manualHidden=\(manualHidden) dimmed=\(dimmed) editing=\(view.hover) " ++ "peek=\(peeking) alpha=\(String(format: "%.2f", panel.alphaValue)) clickThrough=\(panel.ignoresMouseEvents) " ++ "mouse=\(Int(NSEvent.mouseLocation.x)),\(Int(NSEvent.mouseLocation.y)) bar=\(barFrame.integral)"+ }++ // MARK: Geometry++ private var barHeight: CGFloat { view.barHeight(fontSize: fontSize) }++ private func layout() {+ view.fontSize = fontSize+ let m = Self.margin+ let frame = NSRect(x: origin.x - m, y: origin.y - m, width: width + 2 * m, height: barHeight + 2 * m)+ panel.setFrame(frame, display: true)+ view.needsDisplay = true+ }++ private func currentScreen() -> NSScreen {+ let mid = NSPoint(x: origin.x + width / 2, y: origin.y + 10)+ return NSScreen.screens.first(where: { $0.frame.contains(mid) }) ?? NSScreen.main ?? NSScreen.screens[0]+ }++ private static func key(for screen: NSScreen) -> String {+ let n = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.intValue ?? 0+ return "overlay.\(n)"+ }++ private func defaults(on screen: NSScreen) {+ let v = screen.visibleFrame+ width = min(1000, v.width - 160)+ fontSize = 28+ origin = NSPoint(x: v.midX - width / 2, y: v.minY + 56)+ }++ private func restore() {+ let d = UserDefaults.standard+ let last = d.string(forKey: "overlay.lastScreen")+ let screen = NSScreen.screens.first(where: { Self.key(for: $0) == last })+ ?? NSScreen.screens.first(where: { $0.frame.contains(NSEvent.mouseLocation) })+ ?? NSScreen.main ?? NSScreen.screens[0]+ screenKey = Self.key(for: screen)+ if let a = d.array(forKey: screenKey) as? [Double], a.count == 4 {+ let rect = NSRect(x: a[0], y: a[1], width: a[2], height: 40)+ if screen.frame.intersects(rect) {+ origin = NSPoint(x: a[0], y: a[1])+ width = a[2]+ fontSize = a[3]+ return+ }+ }+ defaults(on: screen)+ }++ private func save() {+ let screen = currentScreen()+ screenKey = Self.key(for: screen)+ UserDefaults.standard.set([Double(origin.x), Double(origin.y), Double(width), Double(fontSize)], forKey: screenKey)+ UserDefaults.standard.set(screenKey, forKey: "overlay.lastScreen")+ }++ func resetPosition() {+ defaults(on: currentScreen())+ layout()+ save()+ }++ /// Debug / tests: place the bar exactly.+ func place(x: CGFloat, y: CGFloat, width w: CGFloat, fontSize fs: CGFloat) {+ origin = NSPoint(x: x, y: y)+ width = w+ fontSize = fs+ layout()+ save()+ }++ var barFrame: NSRect { NSRect(x: origin.x, y: origin.y, width: width, height: barHeight) }+ var currentFontSize: CGFloat { fontSize }++ // MARK: Hover++ private var pillFrame: NSRect {+ NSRect(x: origin.x + width / 2 - 34, y: origin.y - 4, width: 68, height: 30)+ }++ private func setDimmed(_ on: Bool) {+ guard dimmed != on else { return }+ dimmed = on+ NSAnimationContext.runAnimationGroup { ctx in+ ctx.duration = on ? 0.12 : 0.25+ panel.animator().alphaValue = on ? 0.15 : 1+ }+ }++ private func pollHover() {+ guard isShown, !manualHidden else { return }+ if view.dragMode != nil { return }+ let mouse = NSEvent.mouseLocation+ let moved = hypot(mouse.x - lastMouse.x, mouse.y - lastMouse.y) > 2+ lastMouse = mouse+ let dt = Self.pollInterval++ // Tucked away: hovering the dot peeks at the last line.+ if !expanded {+ if pillFrame.contains(mouse) {+ peeking = true+ setExpanded(true, animated: true)+ }+ return+ }++ let overBar = barFrame.insetBy(dx: -4, dy: -4).contains(mouse)+ if view.hover {+ // Editing: stay until the pointer leaves.+ if !overBar { setHover(false); stillFor = 0 }+ } else if overBar && !peeking {+ // Passing over: fade so the app underneath stays usable.+ setDimmed(true)+ stillFor = moved ? 0 : stillFor + dt+ if stillFor >= 0.6 {+ setDimmed(false)+ setHover(true)+ }+ } else {+ stillFor = 0+ setDimmed(false)+ }++ if peeking {+ if !overBar && !pillFrame.contains(mouse) {+ peeking = false+ if mode().auto { setExpanded(false, animated: true) }+ }+ return+ }++ // Quiet long enough: tuck away.+ let m = mode()+ if m.auto, !view.hover, !dimmed, view.speaking == nil,+ Date().timeIntervalSince(lastContentAt) > m.hideAfter {+ setExpanded(false, animated: true)+ }+ }++ private func setHover(_ on: Bool) {+ view.hover = on+ panel.ignoresMouseEvents = !on+ view.needsDisplay = true+ }++ // MARK: Dragging (called by the view)++ private var dragStartMouse = NSPoint.zero+ private var dragStartOrigin = NSPoint.zero+ private var dragStartWidth: CGFloat = 0+ private var dragStartFont: CGFloat = 0+ private var snapped = false++ func beginDrag() {+ dragStartMouse = NSEvent.mouseLocation+ dragStartOrigin = origin+ dragStartWidth = width+ dragStartFont = fontSize+ snapped = false+ }++ func drag(scale: Bool) {+ let p = NSEvent.mouseLocation+ let dx = p.x - dragStartMouse.x+ let dy = p.y - dragStartMouse.y+ let screen = currentScreen()+ let sf = screen.frame+ if scale {+ let maxW = min(1800, sf.width - 16)+ width = max(420, min(maxW, dragStartWidth + dx))+ fontSize = max(18, min(48, (dragStartFont * width / dragStartWidth).rounded()))+ // Grow downwards from the top edge, like a window corner.+ let top = dragStartOrigin.y + view.barHeight(fontSize: dragStartFont)+ origin = NSPoint(x: dragStartOrigin.x, y: top - view.barHeight(fontSize: fontSize))+ } else {+ var x = dragStartOrigin.x + dx+ let y = dragStartOrigin.y + dy+ let centre = screen.visibleFrame.midX+ if abs(x + width / 2 - centre) < 18 {+ x = centre - width / 2+ if !snapped { NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now) }+ snapped = true+ } else {+ snapped = false+ }+ origin = NSPoint(x: x, y: y)+ }+ // Keep the bar on screen.+ let all = NSScreen.screens.reduce(NSRect.null) { $0.union($1.frame) }+ origin.x = max(all.minX + 4 - width + 120, min(all.maxX - 120, origin.x))+ origin.y = max(all.minY + 4, min(all.maxY - barHeight - 4, origin.y))+ view.snapped = snapped && !scale+ layout()+ }++ func endDrag() {+ view.snapped = false+ save()+ view.needsDisplay = true+ }+}++final class OverlayPanel: NSPanel {+ override var canBecomeKey: Bool { false }+ override var canBecomeMain: Bool { false }+}++final class OverlayView: NSView {+ weak var controller: OverlayController?+ var source = ""+ var translation = ""+ var isStatus = false+ var speaking: OverlayController.Speaking?+ var fontSize: CGFloat = 28+ var hover = false+ var snapped = false+ var collapsed = false+ var dragMode: Bool?++ private let orange = NSColor(srgbRed: 1.0, green: 0.71, blue: 0.62, alpha: 1)+ private let accent = NSColor(srgbRed: 0.91, green: 0.33, blue: 0.17, alpha: 1)++ override var isFlipped: Bool { false }+ override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }++ // MARK: Metrics++ private func k(_ fs: CGFloat) -> CGFloat { fs / 28 }+ private func srcFont(_ fs: CGFloat) -> NSFont { .systemFont(ofSize: max(12, fs * 0.58), weight: .medium) }+ private func transFont(_ fs: CGFloat) -> NSFont { .systemFont(ofSize: fs, weight: .semibold) }+ private func speakFont(_ fs: CGFloat) -> NSFont { .systemFont(ofSize: max(14, fs * 0.78), weight: .semibold) }+ private func line(_ f: NSFont) -> CGFloat { ceil(f.ascender - f.descender + f.leading) * 1.18 }++ func barHeight(fontSize fs: CGFloat) -> CGFloat {+ let pad = 14 * k(fs)+ var h = pad * 2 + line(srcFont(fs)) + 6 * k(fs) + line(transFont(fs)) * 2+ if speaking != nil {+ h += 12 * k(fs) + line(srcFont(fs)) + line(speakFont(fs)) * 2+ }+ return ceil(h)+ }++ private var barRect: NSRect { bounds.insetBy(dx: OverlayController.margin, dy: OverlayController.margin) }+ private var gripRect: NSRect {+ let s: CGFloat = 26+ return NSRect(x: barRect.maxX - s + 6, y: barRect.minY - 6, width: s, height: s)+ }++ // MARK: Drawing++ override func draw(_ dirtyRect: NSRect) {+ if collapsed {+ // Tucked away: a small pill at the bottom centre — still listening.+ let pill = NSRect(x: barRect.midX - 23, y: barRect.minY, width: 46, height: 18)+ NSColor(calibratedWhite: 0.05, alpha: 0.75).setFill()+ NSBezierPath(roundedRect: pill, xRadius: 9, yRadius: 9).fill()+ accent.setFill()+ NSBezierPath(ovalIn: NSRect(x: pill.minX + 12, y: pill.midY - 2.5, width: 5, height: 5)).fill()+ NSColor.white.withAlphaComponent(0.5).setFill()+ NSBezierPath(ovalIn: NSRect(x: pill.minX + 21, y: pill.midY - 1.5, width: 3, height: 3)).fill()+ NSBezierPath(ovalIn: NSRect(x: pill.minX + 28, y: pill.midY - 1.5, width: 3, height: 3)).fill()+ return+ }+ let bar = barRect+ let radius = 16 * k(fontSize)+ NSColor(calibratedWhite: 0.05, alpha: 0.92).setFill()+ NSBezierPath(roundedRect: bar, xRadius: radius, yRadius: radius).fill()++ if hover {+ let outline = NSBezierPath(roundedRect: bar.insetBy(dx: -3, dy: -3), xRadius: radius + 3, yRadius: radius + 3)+ outline.lineWidth = 1.5+ (snapped ? accent : NSColor.white.withAlphaComponent(0.5)).setStroke()+ outline.stroke()+ }++ let fs = fontSize+ let pad = 14 * k(fs)+ let inner = bar.insetBy(dx: 26 * k(fs), dy: pad)+ var y = inner.maxY++ let center = NSMutableParagraphStyle()+ center.alignment = .center+ center.lineBreakMode = .byWordWrapping++ func draw(_ text: String, font: NSFont, color: NSColor, maxLines: Int) {+ let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: color, .paragraphStyle: center]+ let maxH = line(font) * CGFloat(maxLines)+ let fitted = fitTail(text, attrs: attrs, width: inner.width, maxHeight: maxH + 1)+ let h = min(maxH, height(of: fitted, attrs: attrs, width: inner.width))+ // Bottom-align within the slot so the newest line sits lowest.+ let rect = NSRect(x: inner.minX, y: y - maxH, width: inner.width, height: h)+ (fitted as NSString).draw(with: rect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attrs)+ y -= maxH+ }++ let srcText = isStatus ? "" : source+ draw(srcText, font: srcFont(fs), color: NSColor.white.withAlphaComponent(0.62), maxLines: 1)+ y -= 6 * k(fs)+ draw(translation, font: transFont(fs),+ color: isStatus ? NSColor.white.withAlphaComponent(0.7) : .white, maxLines: 2)++ if let s = speaking {+ y -= 12 * k(fs)+ let label: String+ switch s.phase {+ case .listening: label = "你在说… " + s.source+ case .translating: label = "翻译中… " + s.source+ case .speaking, .idle: label = "你:" + s.source+ }+ draw(label, font: srcFont(fs), color: orange.withAlphaComponent(0.8), maxLines: 1)+ draw(s.translation, font: speakFont(fs), color: orange, maxLines: 2)+ }++ if hover {+ let g = gripRect+ NSColor(calibratedWhite: 0.94, alpha: 1).setFill()+ NSBezierPath(roundedRect: g, xRadius: 8, yRadius: 8).fill()+ let p = NSBezierPath()+ p.lineWidth = 2+ p.lineCapStyle = .round+ p.move(to: NSPoint(x: g.minX + 8, y: g.minY + 7)); p.line(to: NSPoint(x: g.maxX - 7, y: g.maxY - 8))+ p.move(to: NSPoint(x: g.midX + 1, y: g.minY + 7)); p.line(to: NSPoint(x: g.maxX - 7, y: g.midY - 1))+ NSColor(calibratedWhite: 0.08, alpha: 1).setStroke()+ p.stroke()+ }+ }++ private func height(of s: String, attrs: [NSAttributedString.Key: Any], width: CGFloat) -> CGFloat {+ ceil((s as NSString).boundingRect(with: NSSize(width: width, height: .greatestFiniteMagnitude),+ options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attrs).height)+ }++ /// Keeps the end of the text (newest words) and drops the beginning until it fits.+ private func fitTail(_ text: String, attrs: [NSAttributedString.Key: Any], width: CGFloat, maxHeight: CGFloat) -> String {+ if text.isEmpty || height(of: text, attrs: attrs, width: width) <= maxHeight { return text }+ let chars = Array(text)+ var lo = 0, hi = chars.count+ while lo < hi {+ let mid = (lo + hi) / 2+ if height(of: "…" + String(chars[mid...]), attrs: attrs, width: width) <= maxHeight { hi = mid } else { lo = mid + 1 }+ }+ return "…" + String(chars[min(lo, chars.count)...])+ }++ // MARK: Mouse++ override func mouseDown(with event: NSEvent) {+ if event.clickCount == 2 {+ controller?.resetPosition()+ return+ }+ let p = convert(event.locationInWindow, from: nil)+ dragMode = gripRect.insetBy(dx: -6, dy: -6).contains(p)+ controller?.beginDrag()+ (dragMode == true ? NSCursor.crosshair : NSCursor.closedHand).push()+ }++ override func mouseDragged(with event: NSEvent) {+ guard let mode = dragMode else { return }+ controller?.drag(scale: mode)+ }++ override func mouseUp(with event: NSEvent) {+ guard dragMode != nil else { return }+ dragMode = nil+ NSCursor.pop()+ controller?.endDrag()+ }++ override func resetCursorRects() {+ if hover {+ addCursorRect(barRect, cursor: .openHand)+ addCursorRect(gripRect, cursor: .crosshair)+ }+ }+}diff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swiftnew file mode 100644index 0000000..13822c4--- /dev/null+++ b/Sources/LiveSubs/SessionStore.swift@@ -0,0 +1,217 @@+import AppKit+import Foundation++struct TranscriptLine: Codable, Identifiable, Equatable {+ var id: String+ /// Seconds from the start of the session.+ var t: Double+ /// "them" (system audio) or "me" (microphone).+ var speaker: String+ var src: String+ var dst: String?+ var srcLang: String+ var dstLang: String+}++struct Session: Codable, Identifiable, Equatable {+ var id: String+ var title: String+ var startedAt: Date+ var endedAt: Date?+ var lines: [TranscriptLine]+ var hasAudio: Bool++ var duration: TimeInterval { (endedAt ?? Date()).timeIntervalSince(startedAt) }+}++/// One folder per meeting under ~/Library/Application Support/LiveSubs/Sessions/<id>/:+/// session.json, system.m4a (what you heard) and mic.m4a (what you said).+@MainActor+final class SessionStore: ObservableObject {+ @Published private(set) var sessions: [Session] = []+ @Published private(set) var liveID: String?++ let root: URL+ private var saveWork: DispatchWorkItem?++ init() {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ root = base.appendingPathComponent("\(DevBuild.supportFolder)/Sessions", isDirectory: true)+ try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+ load()+ }++ func folder(_ id: String) -> URL { root.appendingPathComponent(id, isDirectory: true) }+ func systemAudioURL(_ id: String) -> URL { folder(id).appendingPathComponent("system.m4a") }+ func micAudioURL(_ id: String) -> URL { folder(id).appendingPathComponent("mic.m4a") }++ private func load() {+ let dirs = (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []+ let decoder = JSONDecoder()+ decoder.dateDecodingStrategy = .iso8601+ var out: [Session] = []+ for dir in dirs {+ if let data = try? Data(contentsOf: dir.appendingPathComponent("session.json")),+ var s = try? decoder.decode(Session.self, from: data) {+ if s.endedAt == nil { s.endedAt = s.lines.last.map { s.startedAt.addingTimeInterval($0.t + 5) } ?? s.startedAt }+ out.append(s)+ }+ }+ sessions = out.sorted { $0.startedAt > $1.startedAt }+ }++ // MARK: Live session++ @discardableResult+ func begin() -> Session {+ let now = Date()+ let f = DateFormatter()+ f.locale = Locale(identifier: "zh_CN")+ f.dateFormat = "M月d日 HH:mm"+ let fid = DateFormatter()+ fid.dateFormat = "yyyyMMdd-HHmmss"+ let s = Session(id: fid.string(from: now), title: "会议 \(f.string(from: now))",+ startedAt: now, endedAt: nil, lines: [], hasAudio: false)+ sessions.insert(s, at: 0)+ liveID = s.id+ try? FileManager.default.createDirectory(at: folder(s.id), withIntermediateDirectories: true)+ return s+ }++ func end() {+ guard let id = liveID, let i = index(id) else { liveID = nil; return }+ sessions[i].endedAt = Date()+ liveID = nil+ if sessions[i].lines.isEmpty {+ // Nothing was said: don't keep an empty meeting around.+ try? FileManager.default.removeItem(at: folder(id))+ sessions.remove(at: i)+ return+ }+ sessions[i].hasAudio = FileManager.default.fileExists(atPath: systemAudioURL(id).path)+ || FileManager.default.fileExists(atPath: micAudioURL(id).path)+ saveNow(id)+ }++ var liveStart: Date? { liveID.flatMap { index($0) }.map { sessions[$0].startedAt } }++ func append(_ line: TranscriptLine) {+ guard let id = liveID, let i = index(id) else { return }+ sessions[i].lines.append(line)+ scheduleSave(id)+ }++ func setTranslation(lineID: String, _ text: String) {+ guard let id = liveID, let i = index(id),+ let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }+ sessions[i].lines[j].dst = text+ scheduleSave(id)+ }++ // MARK: Editing++ func rename(_ id: String, to title: String) {+ guard let i = index(id) else { return }+ let t = title.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !t.isEmpty else { return }+ sessions[i].title = t+ saveNow(id)+ }++ func delete(_ id: String) {+ guard id != liveID, let i = index(id) else { return }+ try? FileManager.default.removeItem(at: folder(id))+ sessions.remove(at: i)+ }++ func session(_ id: String?) -> Session? { id.flatMap { index($0) }.map { sessions[$0] } }++ private func index(_ id: String) -> Int? { sessions.firstIndex(where: { $0.id == id }) }++ private func scheduleSave(_ id: String) {+ saveWork?.cancel()+ let work = DispatchWorkItem { [weak self] in+ MainActor.assumeIsolated { self?.saveNow(id) }+ }+ saveWork = work+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: work)+ }++ func saveNow(_ id: String) {+ guard let s = session(id) else { return }+ let encoder = JSONEncoder()+ encoder.dateEncodingStrategy = .iso8601+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ guard let data = try? encoder.encode(s) else { return }+ try? FileManager.default.createDirectory(at: folder(id), withIntermediateDirectories: true)+ try? data.write(to: folder(id).appendingPathComponent("session.json"), options: .atomic)+ }+}++// MARK: - Export++enum TranscriptExport {+ static func clock(_ t: Double) -> String {+ let s = Int(max(0, t))+ return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, (s / 60) % 60, s % 60)+ : String(format: "%02d:%02d", s / 60, s % 60)+ }++ static func speakerName(_ line: TranscriptLine) -> String { line.speaker == "me" ? "你" : "对方" }++ static func header(_ s: Session) -> String {+ let f = DateFormatter()+ f.locale = Locale(identifier: "zh_CN")+ f.dateFormat = "yyyy年M月d日 HH:mm"+ let mins = Int(s.duration / 60)+ return "\(f.string(from: s.startedAt)) · " + (mins < 1 ? "不到 1 分钟" : "\(mins) 分钟")+ }++ static func markdown(_ s: Session) -> String {+ var out = "# \(s.title)\n\n\(header(s))\n\n"+ for l in s.lines {+ out += "**[\(clock(l.t))] \(speakerName(l))** \n\(l.src)\n"+ if let d = l.dst, d != l.src { out += "> \(d)\n" }+ out += "\n"+ }+ return out+ }++ static func srt(_ s: Session) -> String {+ func ts(_ t: Double) -> String {+ let ms = Int((max(0, t) * 1000).rounded())+ return String(format: "%02d:%02d:%02d,%03d", ms / 3_600_000, (ms / 60_000) % 60, (ms / 1000) % 60, ms % 1000)+ }+ var out = ""+ for (i, l) in s.lines.enumerated() {+ let next = i + 1 < s.lines.count ? s.lines[i + 1].t : l.t + 4+ let end = max(l.t + 1, min(next, l.t + 8))+ out += "\(i + 1)\n\(ts(l.t)) --> \(ts(end))\n\(l.src)\n"+ if let d = l.dst, d != l.src { out += "\(d)\n" }+ out += "\n"+ }+ return out+ }++ static func docx(_ s: Session) throws -> Data {+ let doc = NSMutableAttributedString()+ func add(_ text: String, size: CGFloat, weight: NSFont.Weight = .regular, color: NSColor = .black, after: CGFloat = 4) {+ let p = NSMutableParagraphStyle()+ p.paragraphSpacing = after+ doc.append(NSAttributedString(string: text + "\n", attributes: [+ .font: NSFont.systemFont(ofSize: size, weight: weight),+ .foregroundColor: color,+ .paragraphStyle: p,+ ]))+ }+ add(s.title, size: 20, weight: .bold, after: 6)+ add(header(s), size: 10, color: .darkGray, after: 14)+ for l in s.lines {+ add("[\(clock(l.t))] \(speakerName(l))", size: 9, weight: .semibold, color: .darkGray, after: 2)+ add(l.src, size: 11, after: 2)+ if let d = l.dst, d != l.src { add(d, size: 11, color: NSColor(calibratedWhite: 0.3, alpha: 1), after: 10) }+ }+ return try doc.data(from: NSRange(location: 0, length: doc.length),+ documentAttributes: [.documentType: NSAttributedString.DocumentType.officeOpenXML])+ }+}diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftnew file mode 100644index 0000000..77bd0bf--- /dev/null+++ b/Sources/LiveSubs/Settings.swift@@ -0,0 +1,118 @@+import AppKit+import Foundation++enum SourceMode: Equatable {+ case auto+ case fixed(Lang)+}++/// Persisted user choices. Everything the menu panel and settings sheet edit lives here.+@MainActor+final class AppSettings: ObservableObject {+ private let defaults = UserDefaults.standard++ @Published var sourceMode: SourceMode {+ didSet { save() }+ }+ /// "system" or a translation code.+ @Published var target: String {+ didSet { save() }+ }+ @Published var speakEnabled: Bool {+ didSet { save() }+ }+ /// Locale of the language I speak.+ @Published var speakFrom: String {+ didSet { save() }+ }+ /// "room" (follow the detected room language) or a translation code.+ @Published var speakTo: String {+ didSet { save() }+ }+ /// Output device UID for spoken translations, "" = automatic.+ @Published var speakOutput: String {+ didSet { save() }+ }+ @Published var recordAudio: Bool {+ didSet { save() }+ }+ /// Subtitle bar: show only while someone talks ("auto") or always.+ @Published var overlayAuto: Bool {+ didSet { save() }+ }+ @Published var overlayHideAfter: Double {+ didSet { save() }+ }++ var debug: Bool { defaults.bool(forKey: "debug") }++ init() {+ if let s = defaults.string(forKey: "sourceMode"), s != "auto",+ let lang = sourceLanguages.first(where: { $0.locale == s }) {+ sourceMode = .fixed(lang)+ } else {+ sourceMode = .auto+ }+ target = defaults.string(forKey: "target") ?? "system"+ speakEnabled = defaults.bool(forKey: "speakEnabled")+ let prefersChinese = Locale.preferredLanguages.contains { $0.hasPrefix("zh") }+ speakFrom = defaults.string(forKey: "speakFrom") ?? (prefersChinese ? "zh-CN" : "en-US")+ speakTo = defaults.string(forKey: "speakTo") ?? "room"+ speakOutput = defaults.string(forKey: "speakOutput") ?? ""+ recordAudio = defaults.object(forKey: "recordAudio") as? Bool ?? true+ overlayAuto = defaults.object(forKey: "overlayAuto") as? Bool ?? true+ overlayHideAfter = defaults.object(forKey: "overlayHideAfter") as? Double ?? 4+ }++ private func save() {+ switch sourceMode {+ case .auto: defaults.set("auto", forKey: "sourceMode")+ case .fixed(let lang): defaults.set(lang.locale, forKey: "sourceMode")+ }+ defaults.set(target, forKey: "target")+ defaults.set(speakEnabled, forKey: "speakEnabled")+ defaults.set(speakFrom, forKey: "speakFrom")+ defaults.set(speakTo, forKey: "speakTo")+ defaults.set(speakOutput, forKey: "speakOutput")+ defaults.set(recordAudio, forKey: "recordAudio")+ defaults.set(overlayAuto, forKey: "overlayAuto")+ defaults.set(overlayHideAfter, forKey: "overlayHideAfter")+ }++ /// Target language. "Follow system" uses the first system language that+ /// differs from what is being spoken.+ func resolvedTarget(source: String?) -> String {+ if target != "system" { return target }+ let prefs = Locale.preferredLanguages.map(translationCode(forSystemLanguage:))+ if let src = source, let other = prefs.first(where: { $0 != src }) { return other }+ return prefs.first ?? "zh-CN"+ }++ func systemTargetDescription() -> String {+ let prefs = Locale.preferredLanguages.map(translationCode(forSystemLanguage:))+ var seen: [String] = []+ for p in prefs where !seen.contains(p) { seen.append(p) }+ return seen.prefix(2).map(targetName).joined(separator: " / ")+ }++ var speakFromLang: Lang {+ sourceLanguages.first(where: { $0.locale == speakFrom }) ?? sourceLanguages[0]+ }+}++func debugLog(_ message: String) {+ let line = "\(Date()) \(message)\n"+ let path = DevBuild.logPath+ if let handle = FileHandle(forWritingAtPath: path) {+ handle.seekToEndOfFile()+ handle.write(line.data(using: .utf8) ?? Data())+ handle.closeFile()+ } else {+ try? line.write(toFile: path, atomically: true, encoding: .utf8)+ }+}++/// Transcript content is only logged when `defaults write com.wquguru.cicada debug -bool true`.+func contentLog(_ message: @autoclosure () -> String) {+ if UserDefaults.standard.bool(forKey: "debug") { debugLog(message()) }+}diff --git a/Sources/LiveSubs/SpeakEngine.swift b/Sources/LiveSubs/SpeakEngine.swiftnew file mode 100644index 0000000..8fc7cd0--- /dev/null+++ b/Sources/LiveSubs/SpeakEngine.swift@@ -0,0 +1,435 @@+import AppKit+import AVFoundation+import Carbon.HIToolbox+import CoreAudio+import Speech++// MARK: - Output devices++struct OutputDevice: Identifiable, Hashable {+ let id: AudioObjectID+ let uid: String+ let name: String+ var isVirtualMic: Bool {+ let n = name.lowercased()+ return n.contains("blackhole") || n.contains("livesubs") || n.contains("loopback")+ }+}++enum AudioDevices {+ private static func string(_ device: AudioObjectID, _ selector: AudioObjectPropertySelector) -> String? {+ var value: CFString = "" as CFString+ var size = UInt32(MemoryLayout<CFString>.size)+ var addr = AudioObjectPropertyAddress(mSelector: selector, mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain)+ let status = withUnsafeMutablePointer(to: &value) { AudioObjectGetPropertyData(device, &addr, 0, nil, &size, $0) }+ return status == noErr ? value as String : nil+ }++ static func outputs() -> [OutputDevice] {+ var addr = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDevices,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain)+ var size: UInt32 = 0+ guard AudioObjectGetPropertyDataSize(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size) == noErr else { return [] }+ var ids = [AudioObjectID](repeating: 0, count: Int(size) / MemoryLayout<AudioObjectID>.size)+ guard AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &ids) == noErr else { return [] }+ return ids.compactMap { id in+ var streams = AudioObjectPropertyAddress(mSelector: kAudioDevicePropertyStreams,+ mScope: kAudioObjectPropertyScopeOutput,+ mElement: kAudioObjectPropertyElementMain)+ var s: UInt32 = 0+ guard AudioObjectGetPropertyDataSize(id, &streams, 0, nil, &s) == noErr, s > 0,+ let uid = string(id, kAudioDevicePropertyDeviceUID),+ let name = string(id, kAudioObjectPropertyName),+ !uid.hasPrefix("com.wquguru.cicada") else { return nil }+ return OutputDevice(id: id, uid: uid, name: name)+ }+ }++ static var virtualMic: OutputDevice? { outputs().first(where: \.isVirtualMic) }+}++// MARK: - Push-to-talk hotkey++/// A global hold-to-talk hotkey via Carbon. Unlike NSEvent global monitors it+/// needs no Accessibility / Input Monitoring permission and reports release.+final class HotKey {+ static let display = "⌥ Space"+ var onDown: (() -> Void)?+ var onUp: (() -> Void)?+ private var ref: EventHotKeyRef?+ private var handler: EventHandlerRef?+ private let id: UInt32+ private let keyCode: UInt32+ private let modifiers: UInt32++ init(id: UInt32 = 1, keyCode: Int = kVK_Space, modifiers: Int = optionKey) {+ self.id = id+ self.keyCode = UInt32(keyCode)+ self.modifiers = UInt32(modifiers)+ var types = [+ EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)),+ EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyReleased)),+ ]+ let me = Unmanaged.passUnretained(self).toOpaque()+ InstallEventHandler(GetApplicationEventTarget(), { _, event, user in+ guard let event, let user else { return noErr }+ let hk = Unmanaged<HotKey>.fromOpaque(user).takeUnretainedValue()+ var hkID = EventHotKeyID()+ GetEventParameter(event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID),+ nil, MemoryLayout<EventHotKeyID>.size, nil, &hkID)+ guard hkID.id == hk.id else { return OSStatus(eventNotHandledErr) }+ if GetEventKind(event) == UInt32(kEventHotKeyPressed) { hk.onDown?() } else { hk.onUp?() }+ return noErr+ }, 2, &types, me, &handler)+ }++ func register() {+ guard ref == nil else { return }+ let hkID = EventHotKeyID(signature: OSType(0x4C535542), id: id) // 'LSUB'+ RegisterEventHotKey(keyCode, modifiers, hkID, GetApplicationEventTarget(), 0, &ref)+ }++ func unregister() {+ if let ref { UnregisterEventHotKey(ref) }+ ref = nil+ }+}++// MARK: - Speak engine++/// Hold to talk: microphone → on-device transcription → translation →+/// system voice → chosen output device (a virtual microphone for the call).+@MainActor+final class SpeakEngine {+ enum Phase { case idle, listening, translating, speaking }++ var onLive: ((_ phase: Phase, _ source: String, _ translation: String) -> Void)?+ /// A finished utterance for the meeting record.+ var onUtterance: ((_ source: String, _ translation: String, _ from: String, _ to: String, _ secondsAgo: Double) -> Void)?+ var onStatus: ((String) -> Void)?+ /// Translator shared with the listening side.+ var translate: ((_ text: String, _ from: String, _ to: String) async -> String?)?+ /// Language the room speaks (for "follow the room").+ var roomLanguage: (() -> String?)?++ let settings: AppSettings+ private(set) var phase: Phase = .idle++ private let mic = AVAudioEngine()+ private let micQueue = DispatchQueue(label: "com.wquguru.cicada.mic", qos: .userInitiated)+ private let converter = PCMConverter()+ private var analyzerFormat: AVAudioFormat?+ private var analyzerLocale = ""+ private nonisolated(unsafe) var feeding = false+ private var finals: [String] = []+ private var volatile = ""+ private var pressStarted = Date()+ private nonisolated(unsafe) var micRecorder: AVAudioFile?+ private nonisolated(unsafe) var micRecordURL: URL?++ private let synth = AVSpeechSynthesizer()+ private let out = AVAudioEngine()+ private let player = AVAudioPlayerNode()+ private var outFormat: AVAudioFormat?+ private var outDeviceUID: String?+ /// Debug: also write synthesized speech here.+ var debugOutputURL: URL?++ init(settings: AppSettings) {+ self.settings = settings+ out.attach(player)+ }++ var targetCode: String {+ if settings.speakTo != "room" { return settings.speakTo }+ let room = roomLanguage?() ?? "en"+ return room == settings.speakFromLang.code ? "en" : room+ }++ func setRecording(_ url: URL?) {+ micQueue.sync {+ micRecorder = nil+ micRecordURL = url+ }+ }++ // MARK: Transcriber++ /// Makes sure the speech model for my language is installed and learns the+ /// audio format it wants. Each press then gets its own short-lived analyzer.+ func prepare() async {+ let lang = settings.speakFromLang+ guard analyzerLocale != lang.locale || analyzerFormat == nil else { return }+ let t = SpeechTranscriber(locale: Locale(identifier: lang.locale), transcriptionOptions: [],+ reportingOptions: [.volatileResults], attributeOptions: [])+ do {+ if await AssetInventory.status(forModules: [t]) != .installed,+ let req = try await AssetInventory.assetInstallationRequest(supporting: [t]) {+ onStatus?("正在下载 \(lang.name) 语音模型…")+ try await req.downloadAndInstall()+ }+ analyzerFormat = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [t])+ ?? AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: false)!+ analyzerLocale = lang.locale+ debugLog("speak transcriber ready locale=\(lang.locale)")+ } catch {+ debugLog("speak transcriber failed: \(error)")+ onStatus?("无法准备语音识别:\(error.localizedDescription)")+ }+ }++ func teardownAnalyzer() async {+ utterance?.input.finish()+ utterance = nil+ analyzerFormat = nil+ analyzerLocale = ""+ }++ /// 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 func beginUtterance() -> AsyncStream<AnalyzerInput>.Continuation? {+ guard analyzerFormat != nil else { return nil }+ let lang = settings.speakFromLang+ let t = SpeechTranscriber(locale: Locale(identifier: lang.locale), transcriptionOptions: [],+ reportingOptions: [.volatileResults], attributeOptions: [])+ let (stream, cont) = AsyncStream.makeStream(of: AnalyzerInput.self)+ finals = []+ volatile = ""+ 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()+ } catch {+ debugLog("speak analyzer error: \(error)")+ }+ await collector.value+ return self?.currentText ?? ""+ }+ utterance = (cont, task)+ return cont+ }++ private func handle(_ r: SpeechTranscriber.Result) {+ let text = String(r.text.characters).trimmingCharacters(in: .whitespacesAndNewlines)+ if r.isFinal {+ if !text.isEmpty { finals.append(text) }+ volatile = ""+ } else {+ volatile = text+ }+ if phase == .listening { onLive?(.listening, currentText, "") }+ }++ private var currentText: String {+ let j = joiner(for: settings.speakFromLang.code)+ return (finals + [volatile]).filter { !$0.isEmpty }.joined(separator: j.isEmpty ? "" : " ")+ }++ // MARK: Push to talk++ func pressBegan() {+ guard settings.speakEnabled, phase == .idle || phase == .speaking else { return }+ guard let format = analyzerFormat, let input = beginUtterance() else {+ Task { await prepare() }+ onStatus?("语音识别还在准备,请再按一次")+ return+ }+ pressStarted = Date()+ phase = .listening+ onLive?(.listening, "", "")+ startMic(format: format, input: input)+ }++ func pressEnded() {+ guard phase == .listening else { return }+ // Keep the mic open a moment so the last syllable isn't cut off.+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in+ MainActor.assumeIsolated { self?.finishUtterance() }+ }+ }++ /// Debug path: feed an audio file as if it were spoken into the mic.+ func speakFile(_ url: URL) {+ guard phase == .idle || phase == .speaking else { return }+ guard let format = analyzerFormat, let file = try? AVAudioFile(forReading: url),+ let input = beginUtterance() else {+ debugLog("speakFile: not ready or unreadable \(url.path)")+ return+ }+ pressStarted = Date()+ phase = .listening+ onLive?(.listening, "", "")+ let conv = PCMConverter()+ while true {+ guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 4096),+ (try? file.read(into: buf)) != nil, buf.frameLength > 0 else { break }+ if let c = conv.convert(buf, to: format) { input.yield(AnalyzerInput(buffer: c)) }+ }+ finishUtterance()+ }++ private func startMic(format: AVAudioFormat, input cont: AsyncStream<AnalyzerInput>.Continuation) {+ let inputNode = mic.inputNode+ let inFormat = inputNode.outputFormat(forBus: 0)+ guard inFormat.sampleRate > 0 else {+ onStatus?("没有可用的麦克风")+ phase = .idle+ return+ }+ inputNode.removeTap(onBus: 0)+ let conv = converter+ let queue = micQueue+ feeding = true+ inputNode.installTap(onBus: 0, bufferSize: 2048, format: inFormat) { [weak self] buf, _ in+ queue.async {+ guard let self, self.feeding else { return }+ if let c = conv.convert(buf, to: format) {+ cont.yield(AnalyzerInput(buffer: c))+ self.recordMic(c)+ }+ }+ }+ do {+ try mic.start()+ } catch {+ debugLog("mic start failed: \(error)")+ onStatus?("麦克风无法启动,请在系统设置里允许 Live Subs 使用麦克风")+ phase = .idle+ }+ }++ private nonisolated func recordMic(_ buffer: AVAudioPCMBuffer) {+ guard let url = micRecordURL else { return }+ if micRecorder == nil { micRecorder = AudioFileWriter.open(url, format: buffer.format) }+ try? micRecorder?.write(from: buffer)+ }++ private func stopMic() {+ micQueue.sync { feeding = false }+ if mic.isRunning {+ mic.inputNode.removeTap(onBus: 0)+ mic.stop()+ }+ }++ private func finishUtterance() {+ stopMic()+ phase = .translating+ guard let u = utterance else { phase = .idle; return }+ utterance = nil+ u.input.finish()+ Task {+ let text = await u.text.value+ finals = []+ volatile = ""+ guard !text.isEmpty else {+ phase = .idle+ onLive?(.idle, "", "")+ return+ }+ let from = settings.speakFromLang.code+ let to = targetCode+ onLive?(.translating, text, "")+ let translated = await translate?(text, from, to) ?? text+ contentLog("SPEAK [\(from)→\(to)] \(text) => \(translated)")+ onUtterance?(text, translated, from, to, Date().timeIntervalSince(pressStarted))+ phase = .speaking+ onLive?(.speaking, text, translated)+ await speak(translated, language: to)+ if phase == .speaking { phase = .idle }+ onLive?(.idle, text, translated)+ }+ }++ // MARK: Voice output++ private func voice(for code: String) -> AVSpeechSynthesisVoice? {+ let lang = code == "zh-CN" ? "zh-CN" : code == "zh-TW" ? "zh-TW" : code+ let voices = AVSpeechSynthesisVoice.speechVoices().filter { $0.language.hasPrefix(lang) }+ return voices.max(by: { $0.quality.rawValue < $1.quality.rawValue }) ?? AVSpeechSynthesisVoice(language: lang)+ }++ func outputDevice() -> OutputDevice? {+ let all = AudioDevices.outputs()+ if !settings.speakOutput.isEmpty, let d = all.first(where: { $0.uid == settings.speakOutput }) { return d }+ return all.first(where: \.isVirtualMic)+ }++ private func synthesize(_ text: String, language: String) async -> [AVAudioPCMBuffer] {+ let u = AVSpeechUtterance(string: text)+ u.voice = voice(for: language)+ 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)+ }+ }+ }++ func speak(_ text: String, language: String) async {+ let buffers = await synthesize(text, language: language)+ guard let first = buffers.first else { return }+ if let url = debugOutputURL, let f = AudioFileWriter.open(url, format: first.format) {+ for b in buffers { try? f.write(from: b) }+ }+ let device = outputDevice()+ configureOutput(format: first.format, device: device)+ do {+ if !out.isRunning { try out.start() }+ } catch {+ debugLog("voice output failed: \(error)")+ return+ }+ await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in+ for (i, b) in buffers.enumerated() {+ if i == buffers.count - 1 {+ player.scheduleBuffer(b, completionCallbackType: .dataPlayedBack) { _ in cont.resume() }+ } else {+ player.scheduleBuffer(b)+ }+ }+ player.play()+ }+ debugLog("spoke \(buffers.count) buffers to \(device?.name ?? "default output")")+ }++ private func configureOutput(format: AVAudioFormat, device: OutputDevice?) {+ let uid = device?.uid ?? ""+ guard outFormat != format || outDeviceUID != uid else { return }+ player.stop()+ out.stop()+ if let device, let unit = out.outputNode.audioUnit {+ var id = device.id+ AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,+ &id, UInt32(MemoryLayout<AudioObjectID>.size))+ }+ out.disconnectNodeOutput(player)+ out.connect(player, to: out.mainMixerNode, format: format)+ outFormat = format+ outDeviceUID = uid+ }++ /// Plays a short sample through the chosen output so the user can check it.+ func preview() {+ Task { await speak(targetCode.hasPrefix("zh") ? "这是对方会听到的声音。" : "This is the voice the room will hear.", language: targetCode) }+ }+}diff --git a/Sources/LiveSubs/SystemAudioTap.swift b/Sources/LiveSubs/SystemAudioTap.swiftnew file mode 100644index 0000000..91d8e1b--- /dev/null+++ b/Sources/LiveSubs/SystemAudioTap.swift@@ -0,0 +1,222 @@+import AppKit+import AVFoundation+import AudioToolbox+import CoreAudio+import CoreMedia+import Speech++// MARK: - System audio tap++/// 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.+final class SystemAudioTap {+ /// Called on the real-time audio thread. Must not block.+ var onAudio: ((AVAudioPCMBuffer) -> Void)?++ private var audioUnit: AudioUnit?+ private var tapID = AudioObjectID(kAudioObjectUnknown)+ private var aggregateID = AudioObjectID(kAudioObjectUnknown)+ private var clientFormat: AVAudioFormat?+ private var monoFormat: AVAudioFormat?+ private var renderBuffer: AVAudioPCMBuffer?++ static func defaultOutputDevice() -> AudioObjectID? {+ var device = AudioObjectID(kAudioObjectUnknown)+ var size = UInt32(MemoryLayout<AudioObjectID>.size)+ var addr = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyDefaultOutputDevice,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let status = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr, 0, nil, &size, &device)+ if status != noErr || device == kAudioObjectUnknown { return nil }+ return device+ }++ static func ownProcessObject() -> AudioObjectID? {+ var pid = getpid()+ var obj = AudioObjectID(kAudioObjectUnknown)+ var size = UInt32(MemoryLayout<AudioObjectID>.size)+ var addr = AudioObjectPropertyAddress(+ mSelector: kAudioHardwarePropertyTranslatePIDToProcessObject,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let status = AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &addr,+ UInt32(MemoryLayout<pid_t>.size), &pid, &size, &obj)+ return status == noErr && obj != kAudioObjectUnknown ? obj : nil+ }++ private static func defaultOutputUID() -> String? {+ guard let device = defaultOutputDevice() else { return nil }+ var uid: CFString = "" as CFString+ var size = UInt32(MemoryLayout<CFString>.size)+ var addr = AudioObjectPropertyAddress(+ mSelector: kAudioDevicePropertyDeviceUID,+ mScope: kAudioObjectPropertyScopeGlobal,+ mElement: kAudioObjectPropertyElementMain+ )+ let status = withUnsafeMutablePointer(to: &uid) { ptr in+ AudioObjectGetPropertyData(device, &addr, 0, nil, &size, ptr)+ }+ if status != noErr { return nil }+ return uid as String+ }++ private func fail(_ code: Int, _ message: String) -> NSError {+ stop()+ return NSError(domain: "LiveSubsAudio", code: code, userInfo: [NSLocalizedDescriptionKey: message])+ }++ func start() throws {+ stop()++ // Exclude our own process so the app's spoken translations never+ // come back in as subtitles.+ let desc = CATapDescription(stereoGlobalTapButExcludeProcesses: Self.ownProcessObject().map { [$0] } ?? [])+ desc.name = "Live Subs"+ desc.isPrivate = true++ var tap = AudioObjectID(kAudioObjectUnknown)+ var status = AudioHardwareCreateProcessTap(desc, &tap)+ guard status == noErr else { throw fail(Int(status), "无法创建系统音频 Tap(\(status))") }+ tapID = tap++ guard let outputUID = Self.defaultOutputUID() else { throw fail(-1, "找不到默认输出设备") }++ let aggregateUID = "com.wquguru.cicada.\(UUID().uuidString)"+ let aggregate: [String: Any] = [+ kAudioAggregateDeviceNameKey: "Live Subs Tap",+ kAudioAggregateDeviceUIDKey: aggregateUID,+ kAudioAggregateDeviceMainSubDeviceKey: outputUID,+ kAudioAggregateDeviceIsPrivateKey: true,+ kAudioAggregateDeviceIsStackedKey: false,+ kAudioAggregateDeviceTapAutoStartKey: true,+ kAudioAggregateDeviceSubDeviceListKey: [[kAudioSubDeviceUIDKey: outputUID]],+ kAudioAggregateDeviceTapListKey: [[+ kAudioSubTapUIDKey: desc.uuid.uuidString,+ kAudioSubTapDriftCompensationKey: true,+ ]],+ ]+ var aggregateID = AudioObjectID(kAudioObjectUnknown)+ status = AudioHardwareCreateAggregateDevice(aggregate as CFDictionary, &aggregateID)+ guard status == noErr else { throw fail(Int(status), "无法创建音频聚合设备(\(status))") }+ self.aggregateID = aggregateID++ var component = AudioComponentDescription(+ componentType: kAudioUnitType_Output,+ componentSubType: kAudioUnitSubType_HALOutput,+ componentManufacturer: kAudioUnitManufacturer_Apple,+ componentFlags: 0,+ componentFlagsMask: 0+ )+ guard let found = AudioComponentFindNext(nil, &component) else { throw fail(-2, "找不到 HAL 音频组件") }+ var unit: AudioUnit?+ status = AudioComponentInstanceNew(found, &unit)+ guard status == noErr, let unit else { throw fail(Int(status), "无法创建音频单元(\(status))") }+ audioUnit = unit++ var disableOutput: UInt32 = 0+ AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0,+ &disableOutput, UInt32(MemoryLayout<UInt32>.size))+ var enableInput: UInt32 = 1+ AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1,+ &enableInput, UInt32(MemoryLayout<UInt32>.size))++ var device = aggregateID+ status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,+ &device, UInt32(MemoryLayout<AudioObjectID>.size))+ guard status == noErr else { throw fail(Int(status), "无法连接音频聚合设备(\(status))") }++ var asbd = AudioStreamBasicDescription(+ mSampleRate: 48_000,+ mFormatID: kAudioFormatLinearPCM,+ mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved,+ mBytesPerPacket: 4,+ mFramesPerPacket: 1,+ mBytesPerFrame: 4,+ mChannelsPerFrame: 2,+ mBitsPerChannel: 32,+ mReserved: 0+ )+ guard let clientFormat = AVAudioFormat(streamDescription: &asbd) else { throw fail(-3, "无法创建音频格式") }+ self.clientFormat = clientFormat+ self.monoFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48_000, channels: 1, interleaved: false)+ // Pre-allocate so the real-time callback normally doesn't allocate.+ self.renderBuffer = AVAudioPCMBuffer(pcmFormat: clientFormat, frameCapacity: 4096)++ status = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1,+ &asbd, UInt32(MemoryLayout<AudioStreamBasicDescription>.size))+ guard status == noErr else { throw fail(Int(status), "无法设置音频格式(\(status))") }++ var callback = AURenderCallbackStruct(+ inputProc: { refCon, _, timestamp, bus, frames, _ in+ let tap = Unmanaged<SystemAudioTap>.fromOpaque(refCon).takeUnretainedValue()+ return tap.render(timestamp: timestamp, bus: bus, frames: frames)+ },+ inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()+ )+ status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0,+ &callback, UInt32(MemoryLayout<AURenderCallbackStruct>.size))+ guard status == noErr else { throw fail(Int(status), "无法设置音频回调(\(status))") }++ status = AudioUnitInitialize(unit)+ guard status == noErr else { throw fail(Int(status), "无法初始化音频单元(\(status))") }+ status = AudioOutputUnitStart(unit)+ guard status == noErr else { throw fail(Int(status), "无法启动音频采集(\(status))") }+ }++ private func render(timestamp: UnsafePointer<AudioTimeStamp>, bus: UInt32, frames: UInt32) -> OSStatus {+ guard let unit = audioUnit, let clientFormat else { return noErr }+ var pcm = renderBuffer+ if pcm == nil || pcm!.frameCapacity < frames {+ pcm = AVAudioPCMBuffer(pcmFormat: clientFormat, frameCapacity: frames)+ renderBuffer = pcm+ }+ guard let pcm else { return noErr }+ pcm.frameLength = frames+ var flags = AudioUnitRenderActionFlags()+ let status = AudioUnitRender(unit, &flags, timestamp, bus, frames, pcm.mutableAudioBufferList)+ guard status == noErr else { return status }++ guard let monoFormat, let mono = AVAudioPCMBuffer(pcmFormat: monoFormat, frameCapacity: frames),+ let src = pcm.floatChannelData, let dst = mono.floatChannelData else {+ return noErr+ }+ mono.frameLength = frames+ let n = Int(frames)+ if pcm.format.channelCount >= 2 {+ for i in 0..<n {+ dst[0][i] = (src[0][i] + src[1][i]) * 0.5+ }+ } else {+ memcpy(dst[0], src[0], n * MemoryLayout<Float>.size)+ }+ onAudio?(mono)+ return noErr+ }++ func stop() {+ if let unit = audioUnit {+ AudioOutputUnitStop(unit)+ AudioUnitUninitialize(unit)+ AudioComponentInstanceDispose(unit)+ }+ audioUnit = nil+ if aggregateID != kAudioObjectUnknown {+ AudioHardwareDestroyAggregateDevice(aggregateID)+ }+ aggregateID = kAudioObjectUnknown+ if tapID != kAudioObjectUnknown {+ AudioHardwareDestroyProcessTap(tapID)+ }+ tapID = kAudioObjectUnknown+ clientFormat = nil+ monoFormat = nil+ renderBuffer = nil+ }++ deinit { stop() }+}+diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftnew file mode 100644index 0000000..aac99ae--- /dev/null+++ b/Sources/LiveSubs/Translator.swift@@ -0,0 +1,46 @@+import AppKit+import AVFoundation+import AudioToolbox+import CoreAudio+import CoreMedia+import Speech++// MARK: - Translation++enum TranslateFailure: Error {+ case badURL+ case badResponse(Int)+ case parse+ case empty+}++struct GoogleTranslator {+ static func translate(_ text: String, source: String, target: String) async throws -> String {+ var comps = URLComponents(string: "https://translate.googleapis.com/translate_a/single")!+ comps.queryItems = [+ URLQueryItem(name: "client", value: "gtx"),+ URLQueryItem(name: "sl", value: source),+ URLQueryItem(name: "tl", value: target),+ URLQueryItem(name: "dt", value: "t"),+ URLQueryItem(name: "q", value: text),+ ]+ guard let url = comps.url else { throw TranslateFailure.badURL }+ var req = URLRequest(url: url)+ req.timeoutInterval = 8+ req.setValue("LiveSubs/1.1", forHTTPHeaderField: "User-Agent")+ let (data, response) = try await URLSession.shared.data(for: req)+ guard let http = response as? HTTPURLResponse else { throw TranslateFailure.parse }+ guard http.statusCode == 200 else { throw TranslateFailure.badResponse(http.statusCode) }+ guard+ let root = try JSONSerialization.jsonObject(with: data) as? [Any],+ let segments = root.first as? [Any]+ else { throw TranslateFailure.parse }+ let result = segments.compactMap { seg -> String? in+ guard let arr = seg as? [Any], let s = arr.first as? String else { return nil }+ return s+ }.joined()+ guard !result.isEmpty else { throw TranslateFailure.empty }+ return result+ }+}+diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftnew file mode 100644index 0000000..127a8ae--- /dev/null+++ b/Sources/LiveSubs/Views.swift@@ -0,0 +1,531 @@+import AppKit+import SwiftUI++enum Palette {+ static let ink = Color(red: 0.08, green: 0.09, blue: 0.11)+ static let ground = Color(red: 0.953, green: 0.957, blue: 0.965)+ static let line = Color(red: 0.894, green: 0.902, blue: 0.918)+ static let secondary = Color(red: 0.353, green: 0.373, blue: 0.42)+ static let tertiary = Color(red: 0.42, green: 0.44, blue: 0.50)+ static let accent = Color(red: 0.91, green: 0.33, blue: 0.17)+ static let accentInk = Color(red: 0.70, green: 0.23, blue: 0.08)+ static let accentPale = Color(red: 0.99, green: 0.93, blue: 0.906)+}++struct LogoTile: View {+ var size: CGFloat = 34+ var body: some View { BrandMark(size: size) }+}++/// A gray rounded row that opens a menu, used for the language choices.+struct ChoiceRow: View {+ let label: String+ let value: String+ var badge: String? = nil+ let options: [(id: String, title: String)]+ let onPick: (String) -> Void++ var body: some View {+ Menu {+ ForEach(options, id: \.id) { o in+ Button(o.title) { onPick(o.id) }+ }+ } label: {+ HStack(spacing: 10) {+ Text(label).font(.system(size: 12)).foregroundStyle(Palette.secondary).frame(width: 44, alignment: .leading)+ Text(value).font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(1)+ if let badge {+ Text(badge)+ .font(.system(size: 10, weight: .semibold))+ .foregroundStyle(Palette.accentInk)+ .padding(.horizontal, 7).padding(.vertical, 2)+ .background(Capsule().fill(Palette.accentPale))+ }+ Spacer(minLength: 4)+ Image(systemName: "chevron.down").font(.system(size: 10, weight: .semibold)).foregroundStyle(Palette.tertiary)+ }+ .padding(.horizontal, 12)+ .frame(height: 44)+ .background(RoundedRectangle(cornerRadius: 11).fill(Palette.ground))+ .contentShape(Rectangle())+ }+ .menuStyle(.button)+ .buttonStyle(.plain)+ .menuIndicator(.hidden)+ }+}++// MARK: - Menu bar panel++struct MenuPanelView: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings++ private var sourceOptions: [(id: String, title: String)] {+ let auto = model.candidates.map(\.name).joined(separator: "、")+ return [("auto", auto.isEmpty ? "自动识别" : "自动识别(\(auto))")] + sourceLanguages.map {+ ($0.locale, model.installed.isEmpty || model.installed.contains($0.locale) ? $0.name : "\($0.name)(需下载)")+ }+ }++ private var targetOptions: [(id: String, title: String)] {+ [("system", "跟随系统(\(settings.systemTargetDescription()))")] + targetLanguages.map { ($0.code, $0.name) }+ }++ private var heardValue: (String, String?) {+ switch settings.sourceMode {+ case .fixed(let l): return (l.name, nil)+ case .auto: return (model.listen.activeLang?.name ?? "自动", "自动识别")+ }+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 16) {+ HStack(spacing: 12) {+ LogoTile(size: 34)+ VStack(alignment: .leading, spacing: 3) {+ HStack(spacing: 6) {+ Text("Live Subs").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.ink)+ if let dev = DevBuild.label {+ Text("DEV").font(.system(size: 9, weight: .heavy)).foregroundStyle(.white)+ .padding(.horizontal, 5).padding(.vertical, 1)+ .background(Capsule().fill(Palette.ink))+ .help(dev)+ }+ }+ if let dev = DevBuild.label {+ Text(dev).font(.system(size: 10).monospaced()).foregroundStyle(Palette.tertiary).lineLimit(1)+ }+ HStack(spacing: 6) {+ Circle().fill(model.running ? Palette.accent : Color.gray.opacity(0.5)).frame(width: 7, height: 7)+ Text(model.running ? model.summary : "已暂停")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(1)+ }+ }+ Spacer()+ Toggle("字幕", isOn: Binding(get: { model.running }, set: { model.setRunning($0) }))+ .toggleStyle(.switch).labelsHidden().tint(Palette.ink)+ }++ VStack(spacing: 8) {+ ChoiceRow(label: "听到", value: heardValue.0, badge: heardValue.1, options: sourceOptions) {+ model.sourceSelection = $0+ }+ ChoiceRow(label: "翻译成",+ value: targetName(model.listen.resolvedTarget),+ badge: settings.target == "system" ? "跟随系统" : nil,+ options: targetOptions) {+ model.targetSelection = $0+ }+ }++ Divider()++ HStack(alignment: .top, spacing: 12) {+ VStack(alignment: .leading, spacing: 4) {+ Text("我说话也翻译").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)+ HStack(spacing: 5) {+ Text("按住").foregroundStyle(Palette.secondary)+ KeyCap(HotKey.display)+ Text("说\(settings.speakFromLang.name) → \(targetName(model.speak.targetCode))")+ .foregroundStyle(Palette.secondary).lineLimit(1)+ }+ .font(.system(size: 12))+ }+ Spacer()+ Toggle("我说话也翻译", isOn: Binding(get: { settings.speakEnabled }, set: { model.enableSpeaking($0) }))+ .toggleStyle(.switch).labelsHidden().tint(Palette.ink)+ }+ if settings.speakEnabled && model.virtualMic == nil {+ HStack {+ Text("还没有虚拟麦克风,对方听不到").font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ Spacer()+ InstallMicButton(installer: model.installer) { model.virtualMicInstalled() }+ .font(.system(size: 12))+ }+ .padding(10).frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 9).fill(Palette.accentPale))+ }++ Divider()++ VStack(spacing: 10) {+ HStack {+ Text("字幕条").font(.system(size: 14, weight: .semibold)).foregroundStyle(Palette.ink)+ Spacer()+ Picker("字幕条", selection: Binding(get: { settings.overlayAuto }, set: { model.setOverlayAuto($0) })) {+ Text("说话时显示").tag(true)+ Text("一直显示").tag(false)+ }+ .pickerStyle(.segmented).labelsHidden().frame(width: 170)+ }+ if settings.overlayAuto {+ HStack {+ Text("安静多久后收起").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ Spacer()+ Picker("收起前等待", selection: $settings.overlayHideAfter) {+ Text("2 秒").tag(2.0)+ Text("4 秒").tag(4.0)+ Text("8 秒").tag(8.0)+ }+ .pickerStyle(.segmented).labelsHidden().frame(width: 170)+ }+ }+ HStack(spacing: 5) {+ Text("随时显示 / 隐藏").foregroundStyle(Palette.secondary)+ Spacer()+ KeyCap("⌃ ⌥ S")+ }+ .font(.system(size: 12))+ }++ Divider()++ HStack {+ Button("会议记录") { model.openMainWindow?() }+ Spacer()+ Button("退出") { NSApp.terminate(nil) }+ }+ .buttonStyle(.plain)+ .font(.system(size: 13))+ .foregroundStyle(Palette.secondary)+ }+ .padding(18)+ .frame(width: 320)+ .background(Color.white)+ }+}++struct KeyCap: View {+ let text: String+ init(_ text: String) { self.text = text }+ var body: some View {+ Text(text)+ .font(.system(size: 11, weight: .semibold))+ .foregroundStyle(Palette.ink)+ .padding(.horizontal, 6).padding(.vertical, 1)+ .background(RoundedRectangle(cornerRadius: 5).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 5).stroke(Color(white: 0.82), lineWidth: 1))+ }+}++// MARK: - Main window++struct MainWindowView: View {+ @ObservedObject var model: AppModel+ @ObservedObject var store: SessionStore+ @ObservedObject var settings: AppSettings+ @State private var selection: String?+ @State private var query = ""+ @State private var view = "both"+ @State private var titleDraft = ""++ private var filtered: [Session] {+ guard !query.isEmpty else { return store.sessions }+ return store.sessions.filter { s in+ s.title.localizedCaseInsensitiveContains(query)+ || s.lines.contains { $0.src.localizedCaseInsensitiveContains(query) || ($0.dst ?? "").localizedCaseInsensitiveContains(query) }+ }+ }++ private var current: Session? { store.session(selection ?? store.sessions.first?.id) }++ var body: some View {+ HStack(spacing: 0) {+ sidebar+ .frame(width: 270)+ detail+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(RoundedRectangle(cornerRadius: 16).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 16).stroke(Palette.line, lineWidth: 1))+ .padding(.trailing, 14).padding(.bottom, 14).padding(.top, 38)+ }+ .background(Palette.ground)+ .sheet(isPresented: $model.showSettings) {+ SettingsSheet(model: model, settings: settings)+ }+ }++ // MARK: Sidebar++ private var sidebar: some View {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 10) {+ LogoTile(size: 28)+ Text("会议记录").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.ink)+ Spacer()+ Button { model.showSettings = true } label: {+ Image(systemName: "slider.horizontal.3").font(.system(size: 14)).frame(width: 32, height: 32)+ }+ .buttonStyle(.plain).foregroundStyle(Palette.secondary).help("设置")+ }+ .padding(.top, 38)++ HStack(spacing: 6) {+ Image(systemName: "magnifyingglass").foregroundStyle(Palette.tertiary)+ TextField("搜索会议内容", text: $query).textFieldStyle(.plain)+ }+ .font(.system(size: 13))+ .padding(.horizontal, 10).frame(height: 34)+ .background(RoundedRectangle(cornerRadius: 9).fill(Color.white))+ .overlay(RoundedRectangle(cornerRadius: 9).stroke(Palette.line, lineWidth: 1))++ ScrollView {+ LazyVStack(spacing: 4) {+ ForEach(filtered) { s in+ sessionRow(s)+ }+ }+ }+ if store.sessions.isEmpty {+ Text("打开字幕后,每场会议会自动记在这里。")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ .padding(.top, 8)+ Spacer()+ }+ }+ .padding(.horizontal, 14)+ .padding(.bottom, 14)+ }++ private func sessionRow(_ s: Session) -> some View {+ let selected = s.id == (selection ?? store.sessions.first?.id)+ let live = s.id == store.liveID+ return Button {+ selection = s.id+ titleDraft = s.title+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ HStack(spacing: 6) {+ if live { Circle().fill(Palette.accent).frame(width: 7, height: 7) }+ Text(s.title).font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.ink).lineLimit(1)+ }+ Text(meta(s, live: live)).font(.system(size: 11)).foregroundStyle(Palette.secondary).lineLimit(1)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12).padding(.vertical, 10)+ .background(RoundedRectangle(cornerRadius: 10).fill(selected ? Color.white : Color.clear))+ .overlay(RoundedRectangle(cornerRadius: 10).stroke(selected ? Palette.line : Color.clear, lineWidth: 1))+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .contextMenu {+ Button("在 Finder 中显示") { NSWorkspace.shared.activateFileViewerSelecting([store.folder(s.id)]) }+ Button("删除", role: .destructive) { store.delete(s.id) }.disabled(live)+ }+ }++ private func meta(_ s: Session, live: Bool) -> String {+ let f = DateFormatter()+ f.locale = Locale(identifier: "zh_CN")+ f.dateFormat = Calendar.current.isDateInToday(s.startedAt) ? "今天 HH:mm" : "M月d日 HH:mm"+ let mins = Int(s.duration / 60)+ let length = mins < 1 ? "不到 1 分钟" : "\(mins) 分钟"+ return live ? "进行中 · \(s.lines.count) 句" : "\(f.string(from: s.startedAt)) · \(length) · \(s.lines.count) 句"+ }++ // MARK: Detail++ @ViewBuilder+ private var detail: some View {+ if let s = current {+ VStack(alignment: .leading, spacing: 0) {+ HStack(alignment: .center, spacing: 14) {+ VStack(alignment: .leading, spacing: 6) {+ TextField("标题", text: Binding(+ get: { titleDraft.isEmpty ? s.title : titleDraft },+ set: { titleDraft = $0 }+ ))+ .textFieldStyle(.plain)+ .font(.system(size: 20, weight: .bold))+ .onSubmit { store.rename(s.id, to: titleDraft) }+ Text(TranscriptExport.header(s) + " · \(s.lines.count) 句")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ Spacer()+ Picker("显示", selection: $view) {+ Text("双语").tag("both")+ Text("原文").tag("src")+ Text("译文").tag("dst")+ }+ .pickerStyle(.segmented).labelsHidden().frame(width: 170)+ Menu {+ Button("复制为 Markdown") { model.export(s, kind: "copy") }+ Divider()+ Button("导出 Markdown…") { model.export(s, kind: "md") }+ Button("导出 Word…") { model.export(s, kind: "word") }+ Button("导出字幕 SRT…") { model.export(s, kind: "srt") }+ Divider()+ Button("在 Finder 中显示") { NSWorkspace.shared.activateFileViewerSelecting([store.folder(s.id)]) }+ } label: {+ Text("导出").font(.system(size: 13, weight: .semibold)).foregroundStyle(.white)+ .padding(.horizontal, 16).frame(height: 32)+ .background(RoundedRectangle(cornerRadius: 9).fill(Palette.ink))+ }+ .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden)+ .disabled(s.lines.isEmpty)+ }+ .padding(.horizontal, 28).padding(.top, 24).padding(.bottom, 16)+ .onChange(of: s.id) { _, _ in titleDraft = "" }++ Divider().padding(.horizontal, 28)++ if s.lines.isEmpty {+ VStack(spacing: 8) {+ Spacer()+ Text(s.id == store.liveID ? "正在听,说话的内容会出现在这里" : "这场会议没有记录到内容")+ .font(.system(size: 13)).foregroundStyle(Palette.secondary)+ Spacer()+ }+ .frame(maxWidth: .infinity)+ } else {+ ScrollViewReader { proxy in+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 0) {+ ForEach(s.lines) { l in+ lineRow(l).id(l.id)+ Divider()+ }+ }+ .padding(.horizontal, 28)+ }+ .onChange(of: s.lines.count) { _, _ in+ if s.id == store.liveID, let last = s.lines.last {+ withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }+ }+ }+ }+ }+ }+ } else {+ VStack(spacing: 10) {+ LogoTile(size: 44)+ Text("还没有会议记录").font(.system(size: 15, weight: .semibold))+ Text("打开字幕后,每场会议会自动保存一份双语稿子。")+ .font(.system(size: 13)).foregroundStyle(Palette.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ }++ private func lineRow(_ l: TranscriptLine) -> some View {+ let me = l.speaker == "me"+ return HStack(alignment: .top, spacing: 16) {+ Text(TranscriptExport.clock(l.t))+ .font(.system(size: 11).monospacedDigit()).foregroundStyle(Palette.tertiary)+ .frame(width: 44, alignment: .leading).padding(.top, 2)+ VStack(alignment: .leading, spacing: 5) {+ HStack(spacing: 6) {+ Circle().fill(me ? Palette.accent : Palette.ink.opacity(0.35)).frame(width: 7, height: 7)+ Text(me ? "你" : "对方").font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)+ }+ if view != "dst" {+ Text(l.src)+ .font(.system(size: view == "src" ? 14 : 13))+ .foregroundStyle(view == "src" ? Palette.ink : Palette.tertiary)+ .textSelection(.enabled)+ }+ if view != "src" {+ Text(l.dst ?? "翻译中…")+ .font(.system(size: 14))+ .foregroundStyle(l.dst == nil ? Palette.tertiary : Palette.ink)+ .textSelection(.enabled)+ }+ }+ Spacer(minLength: 0)+ }+ .padding(.vertical, 12)+ }+}++// MARK: - Settings sheet++struct SettingsSheet: View {+ @ObservedObject var model: AppModel+ @ObservedObject var settings: AppSettings+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ VStack(alignment: .leading, spacing: 18) {+ Text("设置").font(.system(size: 18, weight: .bold))++ group("会议记录") {+ Toggle("保存会议录音(只存在这台 Mac 上)", isOn: $settings.recordAudio)+ Button("打开记录文件夹") { NSWorkspace.shared.open(model.store.root) }+ }++ group("我说话也翻译") {+ Picker("我说的语言", selection: Binding(get: { settings.speakFrom },+ set: { settings.speakFrom = $0; model.speakFromChanged() })) {+ ForEach(sourceLanguages, id: \.locale) { Text($0.name).tag($0.locale) }+ }+ Picker("对方听到", selection: $settings.speakTo) {+ Text("跟随房间语言").tag("room")+ ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }+ }+ Picker("声音输出到", selection: $settings.speakOutput) {+ Text("自动(优先虚拟麦克风)").tag("")+ ForEach(model.outputs) { Text($0.name).tag($0.uid) }+ }+ HStack {+ Text("按住").foregroundStyle(Palette.secondary)+ KeyCap(HotKey.display)+ Text("说话,松开后发送译文").foregroundStyle(Palette.secondary)+ Spacer()+ Button("试听") { model.speak.preview() }+ }+ .font(.system(size: 12))+ if model.virtualMic == nil {+ HStack {+ Text("让对方听到译文,需要虚拟麦克风")+ .font(.system(size: 12)).foregroundStyle(Palette.accentInk)+ Spacer()+ InstallMicButton(installer: model.installer) { model.virtualMicInstalled() }+ }+ } else {+ Text("在会议软件里,把麦克风选成 \(model.virtualMic?.name ?? "")")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ }++ group("字幕条") {+ Text("说话时自动出现,安静后收成小点;鼠标经过会变透明。停住不动 0.6 秒可拖动,拖右下角缩放,双击回到默认位置。⌃⌥S 随时显示 / 隐藏。")+ .font(.system(size: 12)).foregroundStyle(Palette.secondary)+ HStack {+ Button("恢复默认位置") { model.overlay.resetPosition() }+ Button("重新看引导") { dismiss(); model.onboardingStep = 1; model.openOnboarding?() }+ }+ }++ HStack {+ Spacer()+ Button("完成") { dismiss() }.keyboardShortcut(.defaultAction)+ }+ }+ .padding(24)+ .frame(width: 460)+ }++ private func group<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(title).font(.system(size: 12, weight: .semibold)).foregroundStyle(Palette.secondary)+ VStack(alignment: .leading, spacing: 10) { content() }+ .padding(14)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12).fill(Palette.ground))+ }+ }+}++struct InstallMicButton: View {+ @ObservedObject var installer: VirtualMicInstaller+ var onInstalled: () -> Void+ var body: some View {+ switch installer.state {+ case .downloading, .installing:+ HStack(spacing: 6) { ProgressView().controlSize(.small); Text(installer.state == .downloading ? "下载中…" : "安装中…").font(.system(size: 12)) }+ default:+ Button("一键安装") { installer.install(onInstalled: onInstalled) }+ }+ }+}diff --git a/Sources/LiveSubs/VirtualMic.swift b/Sources/LiveSubs/VirtualMic.swiftnew file mode 100644index 0000000..d1ceb0e--- /dev/null+++ b/Sources/LiveSubs/VirtualMic.swift@@ -0,0 +1,92 @@+import AppKit+import CryptoKit+import Foundation++/// Installs the BlackHole 2ch virtual audio device without the Terminal:+/// download the official, Apple-notarized installer, verify its SHA-256,+/// then run it through the standard macOS administrator password dialog.+/// (We download it rather than bundling it, so we don't redistribute the GPL driver.)+@MainActor+final class VirtualMicInstaller: ObservableObject {+ enum State: Equatable {+ case idle+ case downloading+ case installing+ case done+ case failed(String)+ }++ @Published private(set) var state: State = .idle++ static let packageURL = URL(string: "https://existential.audio/downloads/BlackHole2ch-0.7.1.pkg")!+ static let packageSHA256 = "57b540f27a3e29c37e310e01bee0fdfab76733087e47f997ef9dccf851400dcf"++ var isInstalled: Bool { AudioDevices.virtualMic != nil }++ /// `verifyOnly` stops after the download and checksum (used by tests).+ func install(verifyOnly: Bool = false, onInstalled: (() -> Void)? = nil) {+ guard state != .downloading && state != .installing else { return }+ Task { await run(verifyOnly: verifyOnly, onInstalled: onInstalled) }+ }++ private func run(verifyOnly: Bool, onInstalled: (() -> Void)?) async {+ state = .downloading+ let pkg: URL+ do {+ let (tmp, response) = try await URLSession.shared.download(from: Self.packageURL)+ guard (response as? HTTPURLResponse)?.statusCode == 200 else {+ state = .failed("下载失败,请检查网络")+ return+ }+ let data = try Data(contentsOf: tmp)+ let digest = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()+ guard digest == Self.packageSHA256 else {+ debugLog("virtual mic: checksum mismatch \(digest)")+ state = .failed("安装包校验没通过,已停止")+ return+ }+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("LiveSubsMic", isDirectory: true)+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ pkg = dir.appendingPathComponent("BlackHole2ch.pkg")+ try? FileManager.default.removeItem(at: pkg)+ try FileManager.default.moveItem(at: tmp, to: pkg)+ debugLog("virtual mic: downloaded and verified \(pkg.path)")+ } catch {+ debugLog("virtual mic: download error \(error)")+ state = .failed("下载失败,请检查网络")+ return+ }+ if verifyOnly {+ state = .idle+ return+ }++ state = .installing+ // Give the UI a beat to show "安装中" before the system dialog appears.+ try? await Task.sleep(nanoseconds: 200_000_000)+ let script = """+ do shell script "/usr/sbin/installer -pkg " & quoted form of "\(pkg.path)" & " -target /" \+ with prompt "Live Subs 要安装虚拟麦克风,让会议里的人听到你的翻译。" with administrator privileges+ """+ var errorInfo: NSDictionary?+ NSAppleScript(source: script)?.executeAndReturnError(&errorInfo)+ if let errorInfo {+ let code = errorInfo[NSAppleScript.errorNumber] as? Int ?? 0+ debugLog("virtual mic: installer error \(errorInfo)")+ state = code == -128 ? .idle : .failed("安装没有完成,可以再试一次")+ return+ }+ // Core Audio picks the new device up after a moment.+ for _ in 0..<20 {+ if isInstalled { break }+ try? await Task.sleep(nanoseconds: 500_000_000)+ }+ if isInstalled {+ debugLog("virtual mic: installed")+ state = .done+ onInstalled?()+ } else {+ state = .failed("装好了,但系统还没识别到,请稍后再看")+ }+ }+}diff --git a/Sources/LiveSubsIcon/main.swift b/Sources/LiveSubsIcon/main.swiftnew file mode 100644index 0000000..1ebe30f--- /dev/null+++ b/Sources/LiveSubsIcon/main.swift@@ -0,0 +1,69 @@+// Renders the app icon (logo C: sound bars turning into lines of text, on orange)+// into an .iconset. `LiveSubsIcon [--dev] <out.iconset>`; --dev adds a "DEV" band.+import AppKit++let orange = NSColor(srgbRed: 0.91, green: 0.33, blue: 0.17, alpha: 1) // #E8552B+let ink = NSColor(srgbRed: 0.082, green: 0.09, blue: 0.11, alpha: 1) // #15171C++func render(_ px: Int, dev: Bool) -> Data {+ let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: px, pixelsHigh: px, bitsPerSample: 8,+ samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,+ bytesPerRow: 0, bitsPerPixel: 0)!+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)+ let s = CGFloat(px) / 1024+ // macOS icon grid: an 824 pt body inset 100 pt, corner ≈ 185 pt.+ let body = NSRect(x: 100 * s, y: 100 * s, width: 824 * s, height: 824 * s)+ let squircle = NSBezierPath(roundedRect: body, xRadius: 185 * s, yRadius: 185 * s)+ let shadow = NSShadow()+ shadow.shadowBlurRadius = 20 * s+ shadow.shadowOffset = NSSize(width: 0, height: -8 * s)+ shadow.shadowColor = NSColor.black.withAlphaComponent(0.25)+ shadow.set()+ orange.setFill()+ squircle.fill()+ NSShadow().set()++ // Design space is the 100-unit logo (y down); map it onto the body.+ let u = 824 * s / 92, ox = body.minX - 4 * u, top = body.maxY + 4 * u+ func r(_ x: CGFloat, _ y: CGFloat, _ w: CGFloat, _ h: CGFloat) -> NSRect {+ NSRect(x: ox + x * u, y: top - (y + h) * u, width: w * u, height: h * u)+ }+ func bar(_ rect: NSRect, alpha: CGFloat = 1) {+ NSColor.white.withAlphaComponent(alpha).setFill()+ let radius = min(rect.width, rect.height) / 2+ NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill()+ }+ bar(r(20, 42, 7, 16))+ bar(r(31, 34, 7, 32))+ bar(r(42, 40, 7, 20))+ bar(r(57, 40, 24, 7))+ bar(r(57, 53, 16, 7), alpha: 0.7)++ if dev {+ // Dev builds: a dark "DEV" band across the bottom, so the Dock, Finder and+ // Spotlight tell them apart from the installed app.+ NSGraphicsContext.saveGraphicsState()+ squircle.addClip()+ ink.setFill()+ NSRect(x: body.minX, y: body.minY, width: body.width, height: 170 * s).fill()+ let font = NSFont.systemFont(ofSize: 110 * s, weight: .heavy)+ let text = NSAttributedString(string: "DEV", attributes: [+ .font: font, .foregroundColor: NSColor.white, .kern: 14 * s,+ ])+ let size = text.size()+ text.draw(at: NSPoint(x: body.midX - size.width / 2 + 7 * s, y: body.minY + (170 * s - size.height) / 2 + 6 * s))+ NSGraphicsContext.restoreGraphicsState()+ }+ NSGraphicsContext.restoreGraphicsState()+ return rep.representation(using: .png, properties: [:])!+}++let args = Array(CommandLine.arguments.dropFirst())+let dev = args.contains("--dev")+let out = URL(fileURLWithPath: args.first { $0 != "--dev" } ?? "AppIcon.iconset")+try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)+for size in [16, 32, 128, 256, 512] {+ try render(size, dev: dev).write(to: out.appendingPathComponent("icon_\(size)x\(size).png"))+ try render(size * 2, dev: dev).write(to: out.appendingPathComponent("icon_\(size)x\(size)@2x.png"))+}diff --git a/scripts/build.sh b/scripts/build.shnew file mode 100755index 0000000..282f78d--- /dev/null+++ b/scripts/build.sh@@ -0,0 +1,43 @@+#!/usr/bin/env bash+# Builds build/LiveSubs.app (Apple silicon).+# Without RELEASE=1 it is a dev build: "Live Subs Dev", bundle id com.wquguru.cicada.dev (its own+# settings, permissions and meeting records), stamped with the branch and commit, which show in the+# menu bar and panel; its icon carries a "DEV" band. RELEASE=1 builds the real com.wquguru.cicada.+set -euo pipefail+cd "$(dirname "$0")/.."++swift build -c release --product LiveSubs+swift build -c release --product LiveSubsIcon+BIN=$(swift build -c release --show-bin-path)++APP=build/LiveSubs.app+ICONSET=build/AppIcon.iconset+rm -rf "$APP" "$ICONSET"+mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"++cp "$BIN/LiveSubs" "$APP/Contents/MacOS/LiveSubs"+cp Resources/Info.plist "$APP/Contents/Info.plist"+cp Resources/sample/sample.mp4 Resources/sample/sample.m4a "$APP/Contents/Resources/"++PLIST="$APP/Contents/Info.plist"+if [[ "${RELEASE:-}" != 1 ]]; then+ STAMP="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo local) @ $(git rev-parse --short HEAD 2>/dev/null || echo none)"+ [[ -n "$(git status --porcelain --untracked-files=no 2>/dev/null)" ]] && STAMP+="+"+ /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev" \+ -c "Set :CFBundleName Live Subs Dev" -c "Set :CFBundleDisplayName Live Subs Dev" \+ -c "Add :LiveSubsDev string $STAMP" "$PLIST"+fi+if [[ -n "${BUILD_NUMBER:-}" ]]; then+ /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD_NUMBER" "$PLIST"+fi++ICON_FLAGS=()+[[ "${RELEASE:-}" == 1 ]] || ICON_FLAGS=(--dev)+"$BIN/LiveSubsIcon" ${ICON_FLAGS[@]+"${ICON_FLAGS[@]}"} "$ICONSET"+iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/AppIcon.icns"++# A fixed designated requirement (the bundle id alone), so rebuilding keeps the system-audio and+# microphone permissions instead of asking again after every build.+ID=$(/usr/libexec/PlistBuddy -c "Print CFBundleIdentifier" "$PLIST")+codesign --force --sign - --requirements "=designated => identifier \"$ID\"" "$APP" >/dev/null+echo "Built $APP ($ID)"diff --git a/scripts/make-frame.swift b/scripts/make-frame.swiftnew file mode 100644index 0000000..e59ada3--- /dev/null+++ b/scripts/make-frame.swift@@ -0,0 +1,18 @@+import AppKit+let w = 1920, h = 1080+let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: w, pixelsHigh: h, bitsPerSample: 8, samplesPerPixel: 4,+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!+NSGraphicsContext.saveGraphicsState()+NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)+NSColor(srgbRed: 0.10, green: 0.11, blue: 0.13, alpha: 1).setFill(); NSRect(x: 0, y: 0, width: w, height: h).fill()+NSColor(srgbRed: 0.23, green: 0.25, blue: 0.29, alpha: 1).setFill()+NSBezierPath(ovalIn: NSRect(x: 560, y: 400, width: 280, height: 280)).fill()+let accent = NSColor(srgbRed: 0.91, green: 0.33, blue: 0.17, alpha: 1)+accent.setStroke(); let ring = NSBezierPath(ovalIn: NSRect(x: 548, y: 388, width: 304, height: 304)); ring.lineWidth = 10; ring.stroke()+("M" as NSString).draw(at: NSPoint(x: 648, y: 470), withAttributes: [.font: NSFont.systemFont(ofSize: 130, weight: .semibold), .foregroundColor: NSColor.white])+("Mia" as NSString).draw(at: NSPoint(x: 920, y: 580), withAttributes: [.font: NSFont.systemFont(ofSize: 72, weight: .bold), .foregroundColor: NSColor.white])+("Live stream · English" as NSString).draw(at: NSPoint(x: 922, y: 500), withAttributes: [.font: NSFont.systemFont(ofSize: 40), .foregroundColor: NSColor(white: 0.7, alpha: 1)])+accent.setFill(); NSBezierPath(roundedRect: NSRect(x: 80, y: 960, width: 150, height: 56), xRadius: 28, yRadius: 28).fill()+("LIVE" as NSString).draw(at: NSPoint(x: 112, y: 968), withAttributes: [.font: NSFont.systemFont(ofSize: 34, weight: .bold), .foregroundColor: NSColor.white])+NSGraphicsContext.restoreGraphicsState()+try! rep.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: CommandLine.arguments[1]))diff --git a/scripts/make-sample.sh b/scripts/make-sample.shnew file mode 100755index 0000000..6c2d50a--- /dev/null+++ b/scripts/make-sample.sh@@ -0,0 +1,17 @@+#!/bin/bash+# Builds the onboarding sample: Resources/sample/sample.mp4 (muted video track for display)+# and Resources/sample/sample.m4a (the speech, played by a helper process so the app's+# own system-audio capture hears it — the app excludes its own process).+set -euo pipefail+cd "$(dirname "$0")/.."+T=$(mktemp -d)+say -v 'Eddy (English (US))' -r 175 -o "$T/speech.aiff" \+ "Hi everyone, welcome to the live stream. Today we're talking about real time translation on the Mac."+swift scripts/make-frame.swift "$T/frame.png"+DUR=$(afinfo "$T/speech.aiff" | awk '/estimated duration/{print $3}')+ffmpeg -y -loglevel error -i "$T/speech.aiff" -c:a aac -b:a 64k Resources/sample/sample.m4a+ffmpeg -y -loglevel error -loop 1 -framerate 25 -t "$DUR" -i "$T/frame.png" \+ -vf "zoompan=z='min(zoom+0.0006,1.06)':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=1:s=960x540:fps=25,format=yuv420p" \+ -c:v libx264 -preset slow -crf 30 -an -movflags +faststart Resources/sample/sample.mp4+rm -rf "$T"+ls -la Resources/sample/sample.*diff --git a/tools/README.md b/tools/README.mdnew file mode 100644index 0000000..b275db4--- /dev/null+++ b/tools/README.md@@ -0,0 +1,20 @@+# 测试小工具++开发版(`scripts/build.sh`,bundle id `com.wquguru.cicada.dev`)默认就接受这些调试命令,日志在 `/tmp/livesubs-dev-debug.log`。+正式版需要先打开调试模式:`defaults write com.wquguru.cicada debug -bool true`,然后重启 App;日志在 `/tmp/livesubs-debug.log`。++编译:`swiftc -O lsctl.swift -o lsctl`(其他几个文件同理)。++- `lsctl <命令>`:通过分布式通知 `com.wquguru.cicada.debug` 遥控 App。+ - 开关字幕:`start` / `stop`+ - 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings`(设置)+ - 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置+ - 说话同传:`speakOn` / `speakOff` 开关,`speakFile:<音频>` 把文件当作麦克风输入,`speakOut:<路径>` 把译文语音另存一份+ - 导出:`export:<目录>`+- `mouse move|drag|dclick ...`:模拟鼠标移动、拖动、双击,坐标原点在主屏左下角。+- `key`:模拟按住 ⌥ Space 1.5 秒。+- `toggle-key`:模拟按一下 ⌃⌥S。+- `winall <pid>`:列出某个进程的窗口 ID,配合 `screencapture -l <ID>` 截图。+- `transcribe <音频> <locale>`:用本机模型转写一个文件,用来核对输出。++diff --git a/tools/key.swift b/tools/key.swiftnew file mode 100644index 0000000..8ae1a67--- /dev/null+++ b/tools/key.swift@@ -0,0 +1,5 @@+import CoreGraphics+import Foundation+let d = CGEvent(keyboardEventSource: nil, virtualKey: 49, keyDown: true)!; d.flags = .maskAlternate; d.post(tap: .cghidEventTap)+usleep(1_500_000)+let u = CGEvent(keyboardEventSource: nil, virtualKey: 49, keyDown: false)!; u.flags = .maskAlternate; u.post(tap: .cghidEventTap)diff --git a/tools/lsctl.swift b/tools/lsctl.swiftnew file mode 100644index 0000000..8b95025--- /dev/null+++ b/tools/lsctl.swift@@ -0,0 +1,4 @@+import Foundation+let cmd = CommandLine.arguments.dropFirst().joined(separator: " ")+DistributedNotificationCenter.default().postNotificationName(Notification.Name("com.wquguru.cicada.debug"), object: cmd, userInfo: nil, deliverImmediately: true)+RunLoop.main.run(until: Date().addingTimeInterval(0.2))diff --git a/tools/mouse.swift b/tools/mouse.swiftnew file mode 100644index 0000000..84a52d4--- /dev/null+++ b/tools/mouse.swift@@ -0,0 +1,24 @@+import Foundation+import CoreGraphics+// usage: mouse move x y | mouse drag x1 y1 x2 y2 | mouse dclick x y (Cocoa coords, origin bottom-left of main screen)+let a = CommandLine.arguments+let H = CGDisplayBounds(CGMainDisplayID()).height+func p(_ x: String, _ y: String) -> CGPoint { CGPoint(x: Double(x)!, y: Double(H) - Double(y)!) }+func post(_ t: CGEventType, _ pt: CGPoint, clicks: Int64 = 1) {+ let e = CGEvent(mouseEventSource: nil, mouseType: t, mouseCursorPosition: pt, mouseButton: .left)!+ e.setIntegerValueField(.mouseEventClickState, value: clicks); e.post(tap: .cghidEventTap)+}+switch a[1] {+case "move": post(.mouseMoved, p(a[2], a[3]))+case "drag":+ let s = p(a[2], a[3]), d = p(a[4], a[5])+ post(.mouseMoved, s); usleep(900_000) // rest so editing activates+ post(.leftMouseDown, s); usleep(80_000)+ for i in 1...20 { let f = Double(i)/20; post(.leftMouseDragged, CGPoint(x: s.x + (d.x-s.x)*f, y: s.y + (d.y-s.y)*f)); usleep(20_000) }+ post(.leftMouseUp, d)+case "dclick":+ let s = p(a[2], a[3]); post(.mouseMoved, s); usleep(600_000)+ post(.leftMouseDown, s, clicks: 1); post(.leftMouseUp, s, clicks: 1); usleep(50_000)+ post(.leftMouseDown, s, clicks: 2); post(.leftMouseUp, s, clicks: 2)+default: break+}diff --git a/tools/toggle-key.swift b/tools/toggle-key.swiftnew file mode 100644index 0000000..80dab5f--- /dev/null+++ b/tools/toggle-key.swift@@ -0,0 +1,6 @@+import CoreGraphics+import Foundation+// ⌃⌥S tap+let d = CGEvent(keyboardEventSource: nil, virtualKey: 1, keyDown: true)!; d.flags = [.maskControl, .maskAlternate]; d.post(tap: .cghidEventTap)+usleep(80_000)+let u = CGEvent(keyboardEventSource: nil, virtualKey: 1, keyDown: false)!; u.flags = [.maskControl, .maskAlternate]; u.post(tap: .cghidEventTap)diff --git a/tools/transcribe.swift b/tools/transcribe.swiftnew file mode 100644index 0000000..f8c98a8--- /dev/null+++ b/tools/transcribe.swift@@ -0,0 +1,11 @@+import Speech+import AVFoundation+let path = CommandLine.arguments[1], loc = CommandLine.arguments[2]+let t = SpeechTranscriber(locale: Locale(identifier: loc), transcriptionOptions: [], reportingOptions: [], attributeOptions: [])+let f = try AVAudioFile(forReading: URL(fileURLWithPath: path))+print("file", f.processingFormat, Double(f.length)/f.processingFormat.sampleRate, "s")+let a = try await SpeechAnalyzer(inputAudioFile: f, modules: [t], finishAfterFile: true)+_ = a+var text = ""+for try await r in t.results { text += String(r.text.characters) }+print(loc, "=>", text)diff --git a/tools/winall.swift b/tools/winall.swiftnew file mode 100644index 0000000..1477734--- /dev/null+++ b/tools/winall.swift@@ -0,0 +1,4 @@+import CoreGraphics+let list = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as! [[String: Any]]+for w in list { let o = w[kCGWindowOwnerName as String] as? String ?? "?"; let pid = w[kCGWindowOwnerPID as String] as? Int ?? 0+ if pid == Int(CommandLine.arguments[1])! { let b = w[kCGWindowBounds as String] as! [String: Any]; print(o, w[kCGWindowNumber as String]!, b["Width"]!, b["Height"]!, w[kCGWindowIsOnscreen as String] ?? false) } }diff --git "a/\345\220\257\345\212\250\345\255\227\345\271\225.command" "b/\345\220\257\345\212\250\345\255\227\345\271\225.command"new file mode 100755index 0000000..b63248e--- /dev/null+++ "b/\345\220\257\345\212\250\345\255\227\345\271\225.command"@@ -0,0 +1,4 @@+#!/bin/bash+# Opens the installed app, or the one built in this checkout.+cd "$(dirname "$0")"+if [ -d "/Applications/LiveSubs.app" ]; then open "/Applications/LiveSubs.app"; else open "build/LiveSubs.app"; fi