知了 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: Import a recording or video and turn it into a meeting record
wquguru6f6eba22cd4f
diff --git a/Resources/Info.plist b/Resources/Info.plistindex 56468c1..7e304b7 100644--- a/Resources/Info.plist+++ b/Resources/Info.plist@@ -4,6 +4,22 @@<dict><key>CFBundleDevelopmentRegion</key><string>en</string>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeName</key>+ <string>Audio or video recording</string>+ <key>CFBundleTypeRole</key>+ <string>Viewer</string>+ <key>LSHandlerRank</key>+ <string>Alternate</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>public.audio</string>+ <string>public.movie</string>+ </array>+ </dict>+ </array><key>CFBundleDisplayName</key><string>Cicada</string><key>CFBundleExecutable</key>diff --git a/Sources/LiveSubs/AppMenu.swift b/Sources/LiveSubs/AppMenu.swiftindex 9ce514b..2bd1fe7 100644--- a/Sources/LiveSubs/AppMenu.swift+++ b/Sources/LiveSubs/AppMenu.swift@@ -32,6 +32,13 @@ final class AppMenu: NSObject, NSMenuItemValidation {app.addItem(item(L("退出 \(name)"), #selector(NSApplication.terminate(_:)), "q", target: NSApp))add(app, to: main)+ let file = NSMenu(title: L("文件"))+ file.addItem(item(L("导入录音或视频…"), #selector(importFiles), "o"))+ file.addItem(item(L("停止转写"), #selector(stopImport)))+ file.addItem(.separator())+ file.addItem(item(L("会议记录"), #selector(openRecords)))+ add(file, to: main)+let notes = NSMenu(title: L("纪要"))notes.addItem(item(L("停止记录"), #selector(toggleRecording), "r"))notes.addItem(item(L("立即更新纪要"), #selector(updateNotes), "u"))@@ -118,6 +125,8 @@ final class AppMenu: NSObject, NSMenuItemValidation {let notesWindow = model.notesWindowlet session = model.store.session(model.store.liveID ?? model.notes.shownID)switch item.action {+ case #selector(stopImport):+ return model.importer.busycase #selector(toggleRecording):item.title = model.running ? L("停止记录") : L("开始记录")return true@@ -175,6 +184,8 @@ final class AppMenu: NSObject, NSMenuItemValidation {@objc private func openAI() { model?.openSettings(.ai) }@objc private func openRecords() { showMainWindow() }@objc private func onboarding() { showOnboarding() }+ @objc private func importFiles() { model?.chooseImportFiles() }+ @objc private func stopImport() { model?.importer.cancelAll() }@objc private func openNotes() { model?.openNotesWindow() }@objc private func toggleRecording() {diff --git a/Sources/LiveSubs/AppModel.swift b/Sources/LiveSubs/AppModel.swiftindex e4eb93c..5b03269 100644--- a/Sources/LiveSubs/AppModel.swift+++ b/Sources/LiveSubs/AppModel.swift@@ -111,6 +111,7 @@ final class AppModel: ObservableObject {let loginItem = LoginItem()lazy var notes = NotesEngine(ling: ling, store: store)lazy var notesWindow = NotesWindowController(model: self)+ lazy var importer = FileImporter(store: store, settings: settings, translator: translator)let sample = SamplePlayer()let speakers = SpeakerTagger()lazy var speakerNamer = SpeakerNamer(ling: ling, store: store)@@ -184,6 +185,7 @@ final class AppModel: ObservableObject {ling.model = { [weak self] in self?.settings.aiModel ?? "Ling-3.1-flash" }listen.translator = translatortranslator.glossary = { [weak self] in self?.notes.glossary ?? [] }+ importer.onFinished = { [weak self] id in self?.importFinished(id) }notes.language = { [weak self] id inTranslationService.englishName(self?.notesLanguageCode(id) ?? "zh-CN")}@@ -1071,6 +1073,52 @@ final class AppModel: ObservableObject {heardWords()}+ // MARK: Imported files++ /// 导入录音或视频…: the open panel, then the files go into the queue.+ func chooseImportFiles() {+ let panel = NSOpenPanel()+ panel.allowedContentTypes = [.audio, .movie, .audiovisualContent]+ panel.allowsMultipleSelection = true+ panel.canChooseDirectories = false+ panel.prompt = L("导入")+ NSApp.activate()+ guard panel.runModal() == .OK else { return }+ importFiles(panel.urls)+ }++ /// Dropped on the window or the Dock icon, opened with Cicada, or chosen: each file becomes a+ /// record, shown in the main window.+ func importFiles(_ urls: [URL]) {+ let files = urls.filter(FileImporter.importable)+ guard !files.isEmpty else { return }+ UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { _, _ in }+ Task {+ let ids = await importer.add(files)+ openMainWindow?()+ if let first = ids.first { mainShow = "\(first),transcript" }+ }+ }++ /// Deleting a record also stops transcribing it; the original file stays where it was.+ func deleteSession(_ id: String) {+ importer.cancel(id)+ store.delete(id)+ }++ private func importFinished(_ id: String) {+ guard let s = store.session(id) else { return }+ let notesToo = settings.importNotes && ling.hasKey && !s.lines.isEmpty+ if notesToo { notes.generate(for: id) }+ let content = UNMutableNotificationContent()+ content.title = L("\(s.displayTitle) 转好了")+ content.body = L("\(MainWindowView.length(s)) · \(s.lines.count) 句") + (notesToo ? L(",正在整理纪要") : "")+ content.userInfo = ["session": id]+ UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "import-\(id)", content: content, trigger: nil)) { error in+ if let error { debugLog("import: notification not shown: \(error)") }+ }+ }+// MARK: Exportfunc export(_ session: Session, kind: String) {@@ -1444,6 +1492,13 @@ final class AppModel: ObservableObject {case "hideAfter": settings.overlayHideAfter = Double(arg) ?? 4case "frame":debugLog("overlay frame=\(overlay.barFrame) font=\(overlay.currentFontSize)")+ case "import": importFiles(arg.split(separator: ",").map { URL(fileURLWithPath: String($0)) })+ case "importCancel": importer.cancelAll()+ case "importRetry": importer.retry(arg)+ case "importNotify":+ UNUserNotificationCenter.current().getNotificationSettings { s in debugLog("import: notifications \(s.authorizationStatus.rawValue) alert=\(s.alertSetting.rawValue)") }+ case "importState":+ debugLog("import state: current=\(importer.current?.id ?? "-") phase=\(importer.phase) heard=\(Int(importer.heard))/\(Int(importer.duration)) untranslated=\(importer.untranslated) queue=\(importer.queue.map(\.id))")case "export":guard let s = store.sessions.first(where: { $0.id != store.liveID }) ?? store.sessions.first else { return }let dir = URL(fileURLWithPath: arg)@@ -1459,7 +1514,7 @@ final class AppModel: ObservableObject {// MARK: - App delegate@MainActor-final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {+final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, UNUserNotificationCenterDelegate {let model = AppModel()private var statusItem: NSStatusItem!private let popover = NSPopover()@@ -1503,11 +1558,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {showMainWindow()}model.installDebugControl()+ UNUserNotificationCenter.current().delegate = selfinstallDeviceListener()Task { await model.launch() }model.updates.start()}+ /// Files dropped on the Dock icon or opened with Cicada: imported as records.+ func application(_ application: NSApplication, open urls: [URL]) {+ model.importFiles(urls)+ }++ /// "转好了": shown even while Cicada is in front; a click opens that record.+ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {+ [.banner]+ }++ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {+ let id = response.notification.request.content.userInfo["session"] as? String+ await MainActor.run {+ showMainWindow()+ if let id { model.mainShow = id }+ }+ }+/// Started by the system at login: stay in the menu bar.private static var launchedAsLoginItem: Bool {guard let event = NSAppleEventManager.shared().currentAppleEvent else { return false }@@ -1603,7 +1677,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {w.isReleasedWhenClosed = falsew.minSize = NSSize(width: 760, height: 480)w.delegate = self- w.contentView = NSHostingView(rootView: MainWindowView(model: model, store: model.store, settings: model.settings))+ w.contentView = NSHostingView(rootView: MainWindowView(model: model, store: model.store, settings: model.settings,+ importer: model.importer))w.toolbar = mainToolbar.make()w.toolbarStyle = .unifiedw.titlebarSeparatorStyle = .nonediff --git a/Sources/LiveSubs/FileImport.swift b/Sources/LiveSubs/FileImport.swiftnew file mode 100644index 0000000..39ecacb--- /dev/null+++ b/Sources/LiveSubs/FileImport.swift@@ -0,0 +1,381 @@+import AVFoundation+import CoreMedia+import Foundation+import Speech+import UniformTypeIdentifiers++/// Recordings and videos the user brings in: each becomes a meeting record, transcribed on device+/// faster than real time, one file at a time. It never touches the live pipeline, so a meeting can+/// be listened to meanwhile; its translations wait behind the live ones (`TranslationService.Kind.file`).+/// UI-free: AppModel shows the state and writes the notes when a file is done.+@MainActor+final class FileImporter: ObservableObject {+ struct Job: Equatable {+ let id: String+ let url: URL+ }++ enum Phase: Equatable {+ case preparing, detecting, downloading(String), transcribing, translating+ }++ /// Files waiting, in order; the one being transcribed is `current`.+ @Published private(set) var queue: [Job] = []+ @Published private(set) var current: Job?+ @Published private(set) var phase: Phase = .preparing+ /// Seconds of the current file transcribed so far, and its length.+ @Published private(set) var heard = 0.0+ @Published private(set) var duration = 0.0+ /// Lines of the current file sent for translation, and those still waiting for it.+ @Published private(set) var toTranslate = 0+ @Published private(set) var untranslated = 0++ /// A file was transcribed and translated to the end.+ var onFinished: ((_ sessionID: String) -> Void)?++ let store: SessionStore+ let settings: AppSettings+ let translator: TranslationService+ private var task: Task<Void, Never>?+ /// The running `SpeechAnalyzer` (macOS 26) or `RecognitionStream`, for 停止转写.+ private var analyzer: AnyObject?++ init(store: SessionStore, settings: AppSettings, translator: TranslationService) {+ self.store = store+ self.settings = settings+ self.translator = translator+ }++ var busy: Bool { current != nil }++ /// 0…1 of the current step: how much of the file is transcribed, then how many lines are translated.+ var progress: Double {+ if phase == .translating { return toTranslate > 0 ? Double(toTranslate - untranslated) / Double(toTranslate) : 1 }+ guard duration > 0 else { return 0 }+ return min(1, heard / duration)+ }++ /// Only things AVFoundation can play: audio, or video with a sound track.+ nonisolated static func importable(_ url: URL) -> Bool {+ guard let type = UTType(filenameExtension: url.pathExtension.lowercased()) else { return false }+ return type.conforms(to: .audio) || type.conforms(to: .movie) || type.conforms(to: .audiovisualContent)+ }++ /// Adds the files to the queue as records right away (so they show in the list); returns their ids.+ @discardableResult+ func add(_ urls: [URL]) async -> [String] {+ var ids: [String] = []+ for url in urls where Self.importable(url) {+ let (date, length) = await Self.facts(url)+ let s = store.beginImport(file: url, recordedAt: date, duration: length)+ queue.append(Job(id: s.id, url: url))+ ids.append(s.id)+ debugLog("import: queued \(s.id) (\(Int(length)) s)")+ }+ next()+ return ids+ }++ /// Transcribe a record again from the start (one that stopped halfway, or by request).+ func retry(_ id: String) {+ guard let path = store.session(id)?.sourcePath, current?.id != id, !queue.contains(where: { $0.id == id }) else { return }+ store.restartImport(id)+ queue.append(Job(id: id, url: URL(fileURLWithPath: path)))+ next()+ }++ enum Status: Equatable {+ /// Waiting, with this many files to go before it.+ case queued(ahead: Int)+ case running+ /// Stopped before the end (quit, 停止转写, or the file couldn't be read).+ case unfinished+ }++ /// Where a record stands; nil once it is transcribed (or not imported at all).+ func status(of s: Session) -> Status? {+ if current?.id == s.id { return .running }+ if let i = queue.firstIndex(where: { $0.id == s.id }) { return .queued(ahead: i + (current == nil ? 0 : 1)) }+ return s.importing == true ? .unfinished : nil+ }++ /// Stops a file (deleted, or 停止转写); what was transcribed stays.+ func cancel(_ id: String) {+ queue.removeAll { $0.id == id }+ guard current?.id == id else { return }+ task?.cancel()+ if #available(macOS 26, *), let a = analyzer as? SpeechAnalyzer { Task { await a.cancelAndFinishNow() } }+ if let s = analyzer as? RecognitionStream { Task { await s.cancel() } }+ }++ func cancelAll() {+ let ids = queue.map(\.id) + [current?.id].compactMap { $0 }+ ids.forEach(cancel)+ }++ // MARK: Running++ private func next() {+ guard current == nil, !queue.isEmpty else { return }+ let job = queue.removeFirst()+ current = job+ phase = .preparing+ heard = 0+ duration = 0+ untranslated = 0+ toTranslate = 0+ task = Task { [weak self] in+ await self?.run(job)+ guard let self else { return }+ self.current = nil+ self.analyzer = nil+ self.next()+ }+ }++ private func run(_ job: Job) async {+ let started = Date()+ // The file's sound as 16 kHz mono PCM: video containers and any codec AVFoundation reads.+ let pcm = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-import-\(job.id).caf")+ defer { try? FileManager.default.removeItem(at: pcm) }+ do {+ let gotAccess = job.url.startAccessingSecurityScopedResource()+ defer { if gotAccess { job.url.stopAccessingSecurityScopedResource() } }+ duration = try await Task.detached(priority: .userInitiated) { try await Self.extractAudio(job.url, to: pcm) }.value+ } catch {+ // Left unfinished: the record offers 重新转写.+ debugLog("import: \(job.id) can't read the file: \(error)")+ return+ }+ guard !Task.isCancelled, store.session(job.id) != nil else { return }++ let lang = await language(of: pcm)+ guard !Task.isCancelled else { return }+ let target = settings.resolvedTarget(source: lang.code)+ debugLog("import: \(job.id) \(lang.locale) → \(target)")++ do {+ if await Recognition.status(lang.locale) != .installed {+ try await Recognition.install(lang.locale) { _ in self.phase = .downloading(lang.name) }+ }+ guard !Task.isCancelled else { return }+ phase = .transcribing+ var n = 0+ var translations: [Task<Void, Never>] = []+ let add = { (sentences: [(text: String, t: Double)]) in+ for sentence in sentences {+ let text = HeardText.clean(sentence.text)+ guard text.contains(where: \.isLetter) else { continue }+ n += 1+ let line = TranscriptLine(id: "f\(n)", t: max(0, sentence.t), speaker: "them",+ src: text, dst: lang.code == target ? text : nil, srcLang: lang.code, dstLang: target)+ self.store.append(line, to: job.id)+ if line.dst == nil { translations.append(self.translate(line, session: job.id)) }+ }+ }+ if !Recognition.legacy, #available(macOS 26, *) {+ let transcriber = SpeechTranscriber(locale: Locale(identifier: lang.locale), transcriptionOptions: [],+ reportingOptions: [], attributeOptions: [.audioTimeRange])+ let file = try AVAudioFile(forReading: pcm)+ let analyzer = try await SpeechAnalyzer(inputAudioFile: file, modules: [transcriber], finishAfterFile: true)+ self.analyzer = analyzer+ for try await result in transcriber.results {+ guard !Task.isCancelled, store.session(job.id) != nil else { break }+ heard = CMTimeGetSeconds(result.range.end)+ let pieces = result.text.runs.map { run in+ (String(result.text[run.range].characters), run.audioTimeRange.map { CMTimeGetSeconds($0.start) })+ }+ add(Self.sentences(pieces, start: CMTimeGetSeconds(result.range.start)))+ }+ _ = analyzer+ } else {+ try await transcribeLegacy(pcm, locale: lang.locale, session: job.id) { piece in+ add(Self.sentences(Self.words(piece), start: piece.start))+ }+ }+ guard !Task.isCancelled, store.session(job.id) != nil else { return }+ heard = duration+ phase = .translating+ for t in translations { await t.value }+ store.finishImport(job.id)+ debugLog(String(format: "import: %@ done, %d lines from %.0f s of audio in %.0f s", job.id, n, duration, Date().timeIntervalSince(started)))+ onFinished?(job.id)+ } catch {+ debugLog("import: \(job.id) failed: \(error)")+ }+ }++ /// macOS 14.4–15: the file fed through the older recognizer, which ends a line at each pause.+ /// It is fed only a couple of lines ahead of what has come back, so a long file doesn't queue up in memory.+ private func transcribeLegacy(_ pcm: URL, locale: String, session id: String,+ line: @escaping (Recognition.Piece) -> Void) async throws {+ let stream = try await Recognition.start(locale, drafts: false)+ analyzer = stream+ let file = try AVAudioFile(forReading: pcm)+ let rate = file.processingFormat.sampleRate+ var fedSeconds = 0.0+ let reader = Task { @MainActor in+ do {+ for try await piece in stream.results where piece.isFinal {+ line(piece)+ }+ } catch {+ debugLog("import: recognizer error \(error)")+ }+ }+ let conv = PCMConverter()+ let chunk = AVAudioFrameCount(rate / 10)+ while !Task.isCancelled, store.session(id) != nil {+ guard let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: chunk),+ (try? file.read(into: buf, frameCount: chunk)) != nil, buf.frameLength > 0 else { break }+ if let c = conv.convert(buf, to: stream.format) { stream.append(c) }+ fedSeconds += Double(buf.frameLength) / rate+ heard = max(heard, fedSeconds - 10)+ // A couple of lines in the recognizer at a time.+ while ((stream as? LegacyStream)?.backlog ?? 0) > 2, !Task.isCancelled { try? await Task.sleep(for: .milliseconds(50)) }+ }+ if Task.isCancelled { await stream.cancel() } else { await stream.finish() }+ await reader.value+ }++ /// The older recognizer times a line, not its words: the line cut after each sentence mark,+ /// each piece timed by where its characters fall in the line.+ nonisolated static func words(_ piece: Recognition.Piece) -> [(String, Double?)] {+ var out: [(String, Double?)] = []+ var current = "", offset = 0+ let total = max(1, piece.text.count)+ func flush() {+ guard !current.isEmpty else { return }+ out.append((current, piece.start + (piece.end - piece.start) * Double(offset) / Double(total)))+ offset += current.count+ current = ""+ }+ for ch in piece.text {+ current.append(ch)+ if "。!?!?.".contains(ch) { flush() }+ }+ flush()+ return out+ }++ /// At most a few translations in flight: Ling takes about two a second across the whole app.+ private var inFlight = 0+ private func translate(_ line: TranscriptLine, session id: String) -> Task<Void, Never> {+ untranslated += 1+ toTranslate += 1+ return Task { [weak self] in+ guard let self else { return }+ while self.inFlight >= 3 { try? await Task.sleep(for: .milliseconds(150)) }+ self.inFlight += 1+ defer { self.inFlight -= 1; self.untranslated -= 1 }+ guard !Task.isCancelled, self.store.session(id) != nil else { return }+ for attempt in 0..<3 {+ if let out = await self.translator.translate(line.src, source: line.srcLang, target: line.dstLang, kind: .file) {+ self.store.setTranslation(in: id, lineID: line.id, out)+ return+ }+ try? await Task.sleep(for: .seconds(attempt == 0 ? 5 : 15))+ }+ }+ }++ /// The file's language: the one chosen in settings, else the installed model that understands+ /// a few clips from across the file best.+ private func language(of pcm: URL) async -> Lang {+ if let fixed = sourceLanguages.first(where: { $0.locale == settings.importLanguage }) { return fixed }+ let langs = await Self.installed()+ guard langs.count > 1 else { return langs.first ?? sourceLanguages[0] }+ phase = .detecting+ guard let file = try? AVAudioFile(forReading: pcm) else { return langs[0] }+ let rate = file.processingFormat.sampleRate+ let clipFrames = AVAudioFrameCount(rate * 8)+ var scores: [String: Double] = [:]+ // Three clips from across the file (fewer in a short one): an intro may be music or silence.+ let starts = Set([0.15, 0.45, 0.75].map { min(AVAudioFramePosition(Double(file.length) * $0), max(0, file.length - AVAudioFramePosition(clipFrames))) })+ for start in starts.sorted() {+ guard let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: clipFrames) else { continue }+ file.framePosition = start+ guard (try? file.read(into: buffer, frameCount: clipFrames)) != nil, buffer.frameLength > 0 else { continue }+ for c in await LanguageDetector.rank([buffer], candidates: langs) { scores[c.lang.locale, default: 0] += c.score }+ }+ debugLog("import: language scores \(scores.map { String(format: "%@=%.2f", $0.key, $0.value) }.sorted())")+ let best = scores.max { $0.value < $1.value }?.key+ return langs.first { $0.locale == best } ?? langs[0]+ }++ /// With no long pause the recognizer hands back minutes as one result (a speech, a fluent+ /// reader): split it after each sentence, each line timed at its first word. `pieces` are the+ /// result's runs with their start, when known; `start` is the result's own.+ nonisolated static func sentences(_ pieces: [(String, Double?)], start: Double) -> [(text: String, t: Double)] {+ var out: [(text: String, t: Double)] = []+ var text = "", t: Double?+ for (piece, at) in pieces {+ if t == nil, !piece.trimmingCharacters(in: .whitespaces).isEmpty { t = at }+ text += piece+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)+ // Short ones ("Mr.", "OK.") stay with what follows.+ if let last = trimmed.last, "。!?!?.".contains(last), trimmed.filter(\.isLetter).count >= 8 {+ out.append((trimmed, t ?? out.last?.t ?? start))+ text = ""+ t = nil+ }+ }+ let rest = text.trimmingCharacters(in: .whitespacesAndNewlines)+ if !rest.isEmpty { out.append((rest, t ?? out.last?.t ?? start)) }+ return out+ }++ /// The languages whose speech model is on this Mac, asked per model: the installed-locale list+ /// can come back short right after a model download.+ nonisolated static func installed() async -> [Lang] {+ var out: [Lang] = []+ for lang in sourceLanguages where await Recognition.status(lang.locale) == .installed {+ out.append(lang)+ }+ return out+ }++ // MARK: Files++ /// When it was recorded (the file's own creation date, else the file system's) and how long it is.+ nonisolated static func facts(_ url: URL) async -> (Date, Double) {+ let asset = AVURLAsset(url: url)+ let length = (try? await asset.load(.duration)).map(CMTimeGetSeconds) ?? 0+ var date: Date?+ if let item = try? await asset.load(.creationDate) { date = (try? await item.load(.dateValue)) ?? nil }+ if date == nil { date = (try? url.resourceValues(forKeys: [.creationDateKey]))?.creationDate }+ return (date ?? Date(), length.isFinite ? length : 0)+ }++ /// Decodes the first sound track to 16 kHz mono Float32 PCM; returns its length in seconds.+ nonisolated static func extractAudio(_ url: URL, to out: URL) async throws -> Double {+ let asset = AVURLAsset(url: url)+ guard let track = try await asset.loadTracks(withMediaType: .audio).first else {+ throw NSError(domain: "CicadaImport", code: 1, userInfo: [NSLocalizedDescriptionKey: "no sound track"])+ }+ let reader = try AVAssetReader(asset: asset)+ let output = AVAssetReaderTrackOutput(track: track, outputSettings: [+ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 16_000, AVNumberOfChannelsKey: 1,+ AVLinearPCMBitDepthKey: 32, AVLinearPCMIsFloatKey: true, AVLinearPCMIsBigEndianKey: false,+ AVLinearPCMIsNonInterleaved: false,+ ])+ reader.add(output)+ guard reader.startReading() else { throw reader.error ?? NSError(domain: "CicadaImport", code: 2) }+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!+ try? FileManager.default.removeItem(at: out)+ let file = try AVAudioFile(forWriting: out, settings: format.settings, commonFormat: .pcmFormatFloat32, interleaved: false)+ var frames: AVAudioFramePosition = 0+ while let sample = output.copyNextSampleBuffer() {+ if Task.isCancelled { reader.cancelReading(); throw CancellationError() }+ let n = AVAudioFrameCount(CMSampleBufferGetNumSamples(sample))+ guard n > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: n) else { continue }+ buffer.frameLength = n+ let status = CMSampleBufferCopyPCMDataIntoAudioBufferList(sample, at: 0, frameCount: Int32(n), into: buffer.mutableAudioBufferList)+ guard status == noErr else { continue }+ try file.write(from: buffer)+ frames += AVAudioFramePosition(n)+ }+ if reader.status == .failed { throw reader.error ?? NSError(domain: "CicadaImport", code: 3) }+ return Double(frames) / 16_000+ }+}diff --git a/Sources/LiveSubs/ImportViews.swift b/Sources/LiveSubs/ImportViews.swiftnew file mode 100644index 0000000..1f068a7--- /dev/null+++ b/Sources/LiveSubs/ImportViews.swift@@ -0,0 +1,189 @@+import AVFoundation+import SwiftUI++/// Plays an imported record's original file, for the player bar and a click on a line's time.+@MainActor+final class RecordingPlayer: ObservableObject {+ @Published private(set) var sessionID: String?+ @Published private(set) var playing = false+ @Published private(set) var time = 0.0+ @Published private(set) var length = 0.0+ /// The file was moved or deleted since it was imported.+ @Published private(set) var missing = false+ @Published private(set) var rate: Float = 1+ private var player: AVPlayer?+ private var observer: Any?++ var ready: Bool { player != nil }++ func load(_ s: Session?) {+ guard s?.id != sessionID else { return }+ unload()+ guard let s, let path = s.sourcePath else { return }+ sessionID = s.id+ length = s.duration+ guard FileManager.default.fileExists(atPath: path) else { missing = true; return }+ let p = AVPlayer(url: URL(fileURLWithPath: path))+ player = p+ observer = p.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 4), queue: .main) { [weak self] t in+ MainActor.assumeIsolated {+ guard let self, let p = self.player else { return }+ self.time = max(0, t.seconds)+ self.playing = p.rate > 0+ if let d = p.currentItem?.duration.seconds, d.isFinite, d > 0 { self.length = d }+ }+ }+ }++ func unload() {+ if let observer { player?.removeTimeObserver(observer) }+ player?.pause()+ observer = nil+ player = nil+ sessionID = nil+ playing = false+ missing = false+ time = 0+ }++ func toggle() {+ guard let player else { return }+ if playing { player.pause() } else { player.playImmediately(atRate: rate) }+ playing.toggle()+ }++ func play(from t: Double) {+ guard let player else { return }+ seek(t)+ player.playImmediately(atRate: rate)+ playing = true+ }++ func seek(_ t: Double) {+ time = t+ player?.seek(to: CMTime(seconds: t, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero)+ }++ /// 1× → 1.5× → 2×.+ func nextRate() {+ rate = rate >= 2 ? 1 : rate + 0.5+ if playing { player?.rate = rate }+ }+}++/// Under an imported record's title: how far transcribing got, or that it stopped.+struct ImportStatusStrip: View {+ @ObservedObject var model: AppModel+ @ObservedObject var importer: FileImporter+ let session: Session++ var body: some View {+ if let status = importer.status(of: session) {+ VStack(alignment: .leading, spacing: 8) {+ HStack(spacing: 10) {+ Text(title(status)).font(.system(size: 12)).foregroundStyle(Palette.ink)+ Spacer(minLength: 8)+ switch status {+ case .running where importer.phase == .transcribing || importer.phase == .translating:+ Text("\(Int(importer.progress * 100))%").font(.system(size: 12).monospacedDigit())+ .foregroundStyle(Palette.secondary)+ case .unfinished:+ if fileExists {+ SoftButton(L("重新转写"), dark: true) { importer.retry(session.id) }+ }+ default:+ EmptyView()+ }+ }+ if status == .running {+ let done = importer.phase == .transcribing || importer.phase == .translating ? importer.progress : 0+ Capsule().fill(Palette.line).frame(height: 4)+ .overlay(alignment: .leading) {+ GeometryReader { g in Capsule().fill(Palette.ink).frame(width: g.size.width * done) }+ }+ .animation(.easeOut(duration: 0.3), value: done)+ }+ if let helper = helper(status) {+ Text(helper).font(.system(size: 11)).foregroundStyle(Palette.secondary)+ }+ }+ .padding(.horizontal, 14).padding(.vertical, 11)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 10).fill(Palette.fill))+ }+ }++ private var fileExists: Bool { session.sourcePath.map { FileManager.default.fileExists(atPath: $0) } ?? false }++ private func title(_ status: FileImporter.Status) -> String {+ switch status {+ case .queued(let ahead): return ahead > 0 ? L("排队中,前面还有 \(ahead) 个文件") : L("排队中")+ case .unfinished: return fileExists ? L("没转完") : L("没转完,原文件已不在原来的位置")+ case .running:+ switch importer.phase {+ case .preparing: return L("正在读取文件…")+ case .detecting: return L("正在听是哪种语言…")+ case .downloading(let name): return L("正在下载 \(name) 语音模型…")+ case .transcribing:+ return L("文字记录已转到 \(TranscriptExport.clock(importer.heard)) / \(TranscriptExport.clock(importer.duration))")+ case .translating: return L("还有 \(importer.untranslated) 句在翻译")+ }+ }+ }++ private func helper(_ status: FileImporter.Status) -> String? {+ guard status == .running else { return nil }+ guard model.settings.importNotes, model.ling.hasKey else { return nil }+ return L("纪要等文字记录转完再整理;正在听的会议优先")+ }+}++/// Play / pause, where in the file, and the speed, for an imported record.+struct RecordingPlayerBar: View {+ @ObservedObject var player: RecordingPlayer++ var body: some View {+ if player.missing {+ Text("找不到原文件,没法播放").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ } else if player.ready {+ HStack(spacing: 12) {+ Button { player.toggle() } label: {+ Image(systemName: player.playing ? "pause.fill" : "play.fill")+ .font(.system(size: 11)).foregroundStyle(.white)+ .frame(width: 28, height: 28).background(Circle().fill(Palette.ink))+ .contentShape(Circle())+ }+ .buttonStyle(.plain)+ .help(player.playing ? L("暂停") : L("播放"))+ .accessibilityLabel(player.playing ? L("暂停") : L("播放"))+ Text(TranscriptExport.clock(player.time)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)+ Slider(value: Binding(get: { min(player.time, max(player.length, 1)) }, set: { player.seek($0) }),+ in: 0...max(player.length, 1))+ .controlSize(.small).tint(Palette.accent)+ Text(TranscriptExport.clock(player.length)).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary)+ Button { player.nextRate() } label: {+ Text(player.rate == 1 ? "1×" : player.rate == 1.5 ? "1.5×" : "2×")+ .font(.system(size: 11, weight: .semibold)).foregroundStyle(Palette.secondary)+ .padding(.horizontal, 7).padding(.vertical, 2)+ .background(RoundedRectangle(cornerRadius: 6).fill(Palette.fill))+ }+ .buttonStyle(.plain).help(L("播放速度"))+ }+ }+ }+}++/// Over the whole main window while files are dragged onto it.+struct ImportDropOverlay: View {+ var body: some View {+ VStack(spacing: 8) {+ Image(systemName: "arrow.down.to.line").font(.system(size: 26, weight: .medium)).foregroundStyle(Palette.ink)+ Text("松开,开始转写").font(.system(size: 15, weight: .semibold)).foregroundStyle(Palette.ink)+ Text("录音或视频,一次可放多个").font(.system(size: 12)).foregroundStyle(Palette.secondary)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(Color.white.opacity(0.92))+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Palette.ink.opacity(0.35), style: StrokeStyle(lineWidth: 1.5, dash: [6, 5])).padding(12))+ .allowsHitTesting(false)+ }+}diff --git a/Sources/LiveSubs/Notes.swift b/Sources/LiveSubs/Notes.swiftindex eb106d1..9ac62ef 100644--- a/Sources/LiveSubs/Notes.swift+++ b/Sources/LiveSubs/Notes.swift@@ -105,8 +105,9 @@ final class NotesEngine: ObservableObject {private(set) var shownID: String?private var timer: Timer?private var inFlight = false- /// A final pass asked for while another call was running; it runs right after.- private var pendingFinal: String?+ /// Final passes asked for while another call was running, in order; each runs after it.+ /// Several can wait: an imported file can finish while the meeting's own pass is queued.+ private var pendingFinals: [String] = []/// A language change that arrived while another update was running: rewrite after it.private var pendingRewrite: String?private var lastAttempt = Date.distantPast@@ -203,7 +204,10 @@ final class NotesEngine: ObservableObject {private func update(_ id: String, final: Bool, upto: Int? = nil, fresh: Bool = false) async {if inFlight {// Never drop the end-of-meeting pass or a "生成纪要" request: queue it.- if final { pendingFinal = id; generatingID = id }+ if final {+ if !pendingFinals.contains(id) { pendingFinals.append(id) }+ if generatingID == nil { generatingID = id }+ }if fresh { pendingRewrite = id }return}@@ -216,9 +220,9 @@ final class NotesEngine: ObservableObject {defer {inFlight = falseif final, generatingID == id { generatingID = nil }- if let next = pendingFinal {- pendingFinal = nil- pendingRewrite = nil // the final pass starts from nothing anyway+ if !pendingFinals.isEmpty {+ let next = pendingFinals.removeFirst()+ if pendingRewrite == next { pendingRewrite = nil } // the final pass starts from nothing anywayTask { await update(next, final: true) }} else if let next = pendingRewrite {pendingRewrite = nildiff --git a/Sources/LiveSubs/SessionStore.swift b/Sources/LiveSubs/SessionStore.swiftindex c980adc..ddf8ab3 100644--- a/Sources/LiveSubs/SessionStore.swift+++ b/Sources/LiveSubs/SessionStore.swift@@ -37,6 +37,13 @@ struct Session: Codable, Identifiable, Equatable {var voiceNames: [String: String]? = nil/// Names Ling read from the conversation, keyed by voice id; shown until the user says otherwise.var voiceGuesses: [String: VoiceGuess]? = nil+ /// An imported recording or video: its file name, where it was (played from there; never+ /// copied or deleted), and true until transcribing it finished.+ var sourceFile: String? = nil+ var sourcePath: String? = nil+ var importing: Bool? = nil+ /// Heard through the microphone in the room (会议室) for some or all of it.+ var room: Bool? = nilvar duration: TimeInterval { (endedAt ?? Date()).timeIntervalSince(startedAt) }@@ -45,7 +52,11 @@ struct Session: Codable, Identifiable, Equatable {var displayTitle: String {if renamed ?? !title.hasPrefix("会议 ") { return title }// The stored default title is Chinese ("会议 11月1日 14:30"); shown in the UI language.- guard let name = notes?.title, !name.isEmpty else { return L("会议 \(dateText(startedAt, "MMMdHHmm"))") }+ guard let name = notes?.title, !name.isEmpty else {+ // An imported file is known by its name until the notes give it one.+ if let file = sourceFile { return (file as NSString).deletingPathExtension }+ return L("会议 \(dateText(startedAt, "MMMdHHmm"))")+ }let thisYear = Calendar.current.isDate(startedAt, equalTo: Date(), toGranularity: .year)return "\(dateText(startedAt, thisYear ? "MMMd" : "yMMMd")) \(name)"}@@ -66,7 +77,8 @@ final class SessionStore: ObservableObject {@Published private(set) var liveID: String?let root: URL- private var saveWork: DispatchWorkItem?+ /// Per meeting: a file being imported saves alongside the live meeting without delaying it.+ private var saveWork: [String: DispatchWorkItem] = [:]/// `root`: tests keep their meetings in a folder of their own.init(root: URL? = nil) {@@ -227,6 +239,52 @@ final class SessionStore: ObservableObject {id == liveID ? scheduleSave(id) : saveNow(id)}+ // MARK: Imported files++ /// A record for a recording or video, dated when it was recorded; filled by `FileImporter`.+ func beginImport(file: URL, recordedAt: Date, duration: Double) -> Session {+ let fid = DateFormatter()+ fid.dateFormat = "yyyyMMdd-HHmmss"+ let id = "import-\(fid.string(from: Date()))-\(UUID().uuidString.prefix(4).lowercased())"+ var s = Session(id: id, title: Session.defaultTitle(recordedAt), startedAt: recordedAt,+ endedAt: recordedAt.addingTimeInterval(max(1, duration)), lines: [], hasAudio: false)+ s.sourceFile = file.lastPathComponent+ s.sourcePath = file.path+ s.importing = true+ sessions.append(s)+ sessions.sort { $0.startedAt > $1.startedAt }+ saveNow(id)+ return s+ }++ /// Transcribing again from the start: the old lines and notes go.+ func restartImport(_ id: String) {+ guard let i = index(id) else { return }+ sessions[i].lines = []+ sessions[i].notes = nil+ sessions[i].importing = true+ saveNow(id)+ }++ func append(_ line: TranscriptLine, to id: String) {+ guard let i = index(id) else { return }+ sessions[i].lines.append(line)+ scheduleSave(id)+ }++ func setTranslation(in id: String, lineID: String, _ text: String) {+ guard let i = index(id), let j = sessions[i].lines.firstIndex(where: { $0.id == lineID }) else { return }+ sessions[i].lines[j].dst = text+ scheduleSave(id)+ }++ func finishImport(_ id: String) {+ guard let i = index(id) else { return }+ sessions[i].importing = nil+ saveWork.removeValue(forKey: id)?.cancel()+ saveNow(id)+ }+// MARK: Editing/// An empty title, or the one shown already, goes back to the automatic one.@@ -246,6 +304,7 @@ final class SessionStore: ObservableObject {func delete(_ id: String) {guard id != liveID, let i = index(id) else { return }+ saveWork.removeValue(forKey: id)?.cancel()try? FileManager.default.removeItem(at: folder(id))sessions.remove(at: i)}@@ -254,12 +313,15 @@ final class SessionStore: ObservableObject {private func index(_ id: String) -> Int? { sessions.firstIndex(where: { $0.id == id }) }+ /// At most one save per meeting every 1.5 s. A save already waiting writes the latest state,+ /// so it is never pushed back: an imported file adds lines and translations many times a+ /// second and would otherwise not reach the disk until it went quiet.private func scheduleSave(_ id: String) {- saveWork?.cancel()+ guard saveWork[id] == nil else { return }let work = DispatchWorkItem { [weak self] in- MainActor.assumeIsolated { self?.saveNow(id) }+ MainActor.assumeIsolated { self?.saveWork[id] = nil; self?.saveNow(id) }}- saveWork = work+ saveWork[id] = workDispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: work)}@@ -329,7 +391,9 @@ enum TranscriptExport {if !notes.isEmpty { out += notes + "## \(L("文字记录"))\n\n" }let numbers = speakerNumbers(s), names = SpeakerLabels.names(s)for l in s.lines {- out += "**[\(clock(l.t))] \(speakerName(l, numbers, names))** \n\(l.src)\n"+ // An imported file has no "other side" to name.+ let who = s.sourceFile == nil ? " \(speakerName(l, numbers, names))" : ""+ out += "**[\(clock(l.t))]\(who)** \n\(l.src)\n"if let d = l.dst, d != l.src { out += "> \(d)\n" }out += "\n"}@@ -390,7 +454,7 @@ enum TranscriptExport {}let numbers = speakerNumbers(s), names = SpeakerLabels.names(s)for l in s.lines {- add("[\(clock(l.t))] \(speakerName(l, numbers, names))", size: 9, weight: .semibold, color: .darkGray, after: 2)+ add("[\(clock(l.t))]" + (s.sourceFile == nil ? " \(speakerName(l, numbers, names))" : ""), 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) }}diff --git a/Sources/LiveSubs/Settings.swift b/Sources/LiveSubs/Settings.swiftindex 7ce1c1d..878388d 100644--- a/Sources/LiveSubs/Settings.swift+++ b/Sources/LiveSubs/Settings.swift@@ -62,6 +62,14 @@ final class AppSettings: ObservableObject {@Published var recordAudio: Bool {didSet { save() }}+ /// Imported files: the language they are in ("auto" or a locale), and whether notes are written+ /// once one is transcribed.+ @Published var importLanguage: String {+ didSet { save() }+ }+ @Published var importNotes: Bool {+ didSet { save() }+ }/// Subtitle bar: show only while someone talks ("auto") or always.@Published var overlayAuto: Bool {didSet { save() }@@ -151,6 +159,8 @@ final class AppSettings: ObservableObject {speakMic = defaults.string(forKey: "speakMic") ?? ""savedSystemInput = defaults.string(forKey: "savedSystemInput") ?? ""recordAudio = defaults.object(forKey: "recordAudio") as? Bool ?? true+ importLanguage = defaults.string(forKey: "importLanguage") ?? "auto"+ importNotes = defaults.object(forKey: "importNotes") as? Bool ?? trueoverlayAuto = defaults.object(forKey: "overlayAuto") as? Bool ?? trueoverlayHideAfter = defaults.object(forKey: "overlayHideAfter") as? Double ?? 4talkKey = Shortcut(stored: defaults.string(forKey: "talkKey")) ?? .defaultTalk@@ -184,6 +194,8 @@ final class AppSettings: ObservableObject {defaults.set(speakMic, forKey: "speakMic")defaults.set(savedSystemInput, forKey: "savedSystemInput")defaults.set(recordAudio, forKey: "recordAudio")+ defaults.set(importLanguage, forKey: "importLanguage")+ defaults.set(importNotes, forKey: "importNotes")defaults.set(overlayAuto, forKey: "overlayAuto")defaults.set(overlayHideAfter, forKey: "overlayHideAfter")defaults.set(talkKey.stored, forKey: "talkKey")diff --git a/Sources/LiveSubs/SettingsWindow.swift b/Sources/LiveSubs/SettingsWindow.swiftindex 82298bd..296a544 100644--- a/Sources/LiveSubs/SettingsWindow.swift+++ b/Sources/LiveSubs/SettingsWindow.swift@@ -725,6 +725,20 @@ struct SettingsView: View {SoftButton(L("打开")) { NSWorkspace.shared.open(model.store.root) }}}+ Text("导入的文件").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary).padding(.top, 4)+ SettingsCard {+ SettingsRow(title: L("文件里说的"), detail: L("译成“翻译成”里的语言")) {+ Picker("文件里说的", selection: $settings.importLanguage) {+ Text("自动识别").tag("auto")+ ForEach(sourceLanguages, id: \.locale) { Text($0.name).tag($0.locale) }+ }+ .labelsHidden().fixedSize()+ }+ SettingsRow(title: L("转完后生成纪要"), detail: L("需要 Ling key;没有也能转出文字记录"), divider: false) {+ Toggle("转完后生成纪要", isOn: $settings.importNotes)+ .toggleStyle(.switch).labelsHidden().controlSize(.small).tint(Palette.ink)+ }+ }Text("结束会议").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.secondary).padding(.top, 4)SettingsCard {SettingsRow(title: L("会议应用挂断后结束"), detail: L("Zoom、腾讯会议、飞书、Teams 等")) {diff --git a/Sources/LiveSubs/Translator.swift b/Sources/LiveSubs/Translator.swiftindex ee2e526..b10d1d5 100644--- a/Sources/LiveSubs/Translator.swift+++ b/Sources/LiveSubs/Translator.swift@@ -54,7 +54,8 @@ struct GoogleTranslator {/// does: it would use up the account's ~2 requests per second.@MainActorfinal class TranslationService {- enum Kind { case draft, sentence, speak }+ /// `file`: a line of an imported recording, sent to Ling behind everything live.+ enum Kind { case draft, sentence, speak, file }let ling: LingClient/// Names and terms the notes have settled on, e.g. "江充 (Jiang Chong)".@@ -123,8 +124,9 @@ final class TranslationService {if !names.isEmpty { prompt += "\nKnown names and terms (use these spellings): " + names.joined(separator: "; ") }prompt += "\nSubtitle: " + textdo {- let out = try await ling.chat(content: prompt, instruction: "Translate.", priority: kind == .speak ? .speak : .translate,- maxTokens: 400, timeout: kind == .speak ? 10 : 6,+ let priority: LingClient.Priority = kind == .speak ? .speak : kind == .file ? .notes : .translate+ let out = try await ling.chat(content: prompt, instruction: "Translate.", priority: priority,+ maxTokens: 400, timeout: kind == .speak ? 10 : kind == .file ? 20 : 6,onQueued: { [weak trace] in trace?.lingQueue += $0 })if out.isEmpty { return (nil, "empty") }guard let clean = Self.cleanTranslation(out, target: target) else {diff --git a/Sources/LiveSubs/Views.swift b/Sources/LiveSubs/Views.swiftindex a692e25..ab7e5ea 100644--- a/Sources/LiveSubs/Views.swift+++ b/Sources/LiveSubs/Views.swift@@ -177,6 +177,7 @@ struct MenuPanelView: View {.font(.system(size: 12)).foregroundStyle(Palette.secondary).lineLimit(2).fixedSize(horizontal: false, vertical: true)}+ PanelImportLine(importer: model.importer, store: model.store)}Spacer()Toggle("字幕", isOn: Binding(get: { model.running }, set: { model.setRunning($0) }))@@ -680,6 +681,9 @@ struct MainWindowView: View {@ObservedObject var model: AppModel@ObservedObject var store: SessionStore@ObservedObject var settings: AppSettings+ @ObservedObject var importer: FileImporter+ @StateObject private var player = RecordingPlayer()+ @State private var dropping = false@State private var selection: String?@State private var query = ""@State private var view = "both"@@ -724,6 +728,15 @@ struct MainWindowView: View {}.background(Color.white.ignoresSafeArea()).background(Button("") { searchFocused = true }.keyboardShortcut("f").opacity(0))+ // Recordings and videos dropped anywhere on the window become records.+ .dropDestination(for: URL.self) { urls, _ in+ let files = urls.filter(FileImporter.importable)+ guard !files.isEmpty else { return false }+ model.importFiles(files)+ return true+ } isTargeted: { dropping = $0 }+ .overlay { if dropping { ImportDropOverlay() } }+ .onChange(of: current?.id, initial: true) { _, _ in player.load(current) }.onChange(of: model.mainShow) { _, show inguard let parts = show?.split(separator: ",").map(String.init), let id = parts.first else { return }selection = id@@ -821,10 +834,17 @@ struct MainWindowView: View {// stay grey so the one being read stands out.HStack(spacing: 8) {if live { BreathingDot(size: 6) }+ if s.sourceFile != nil {+ Image(systemName: "doc").font(.system(size: 11)).foregroundStyle(Palette.secondary)+ } else if s.room == true {+ Image(systemName: "mic").font(.system(size: 11)).foregroundStyle(Palette.secondary)+ .help(L("会议室"))+ }Text(Self.untitled(s) ? L("未命名会议") : Self.listTitle(s)).font(.system(size: 13, weight: selected ? .semibold : .regular)).foregroundStyle(selected || live ? Palette.ink : Palette.secondary).lineLimit(1)Spacer(minLength: 0)+ if let status = importer.status(of: s) { Tag(rowTag(status), live: status == .running) }}.padding(.horizontal, 12).padding(.vertical, 9).background(RoundedRectangle(cornerRadius: 8).fill(selected ? Color.white : Color.clear)@@ -834,11 +854,39 @@ struct MainWindowView: View {.help(live ? L("正在记录") : [when(s), Self.length(s)].joined(separator: " · ")).buttonStyle(.plain).contextMenu {+ if let path = s.sourcePath, FileManager.default.fileExists(atPath: path) {+ Button("显示原文件") { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)]) }+ }Button("在 Finder 中显示") { NSWorkspace.shared.activateFileViewerSelecting([store.folder(s.id)]) }+ if s.sourcePath != nil, !working(s) {+ Button("重新转写") { importer.retry(s.id) }+ }if s.renamed ?? !s.title.hasPrefix("会议 "), s.notes?.title != nil {Button("恢复自动标题") { store.rename(s.id, to: "") }}- Button("删除", role: .destructive) { store.delete(s.id) }.disabled(live)+ Button("删除", role: .destructive) { model.deleteSession(s.id) }.disabled(live)+ }+ }++ /// Being transcribed or waiting to be.+ private func working(_ s: Session) -> Bool {+ switch importer.status(of: s) {+ case .running, .queued: return true+ default: return false+ }+ }++ /// The list row's word for an imported file still being worked on.+ private func rowTag(_ status: FileImporter.Status) -> String {+ switch status {+ case .queued: return L("排队中")+ case .unfinished: return L("没转完")+ case .running:+ switch importer.phase {+ case .transcribing: return L("转写中 \(Int(importer.progress * 100))%")+ case .translating: return L("翻译中")+ default: return L("准备中")+ }}}@@ -861,7 +909,7 @@ struct MainWindowView: View {/// Still on the stored "会议 <date>" title: not renamed, and no notes title to show.static func untitled(_ s: Session) -> Bool {- !(s.renamed ?? !s.title.hasPrefix("会议 ")) && (s.notes?.title ?? "").isEmpty+ !(s.renamed ?? !s.title.hasPrefix("会议 ")) && (s.notes?.title ?? "").isEmpty && s.sourceFile == nil}static func length(_ s: Session) -> String {@@ -903,10 +951,11 @@ struct MainWindowView: View {.frame(maxWidth: .infinity)}.overlay {- Text(s.id == store.liveID ? L("正在听,说话的内容会出现在这里") : L("这场会议没有记录到内容"))+ Text(s.id == store.liveID ? L("正在听,说话的内容会出现在这里")+ : working(s) ? L("转出的文字会陆续出现在这里") : L("这场会议没有记录到内容")).font(.system(size: 13)).foregroundStyle(Palette.secondary)}- } else if tab == "notes" {+ } else if tab == "notes", importer.status(of: s) == nil {HStack(spacing: 0) {SessionNotesView(model: model, engine: model.notes, ling: model.ling, session: s,header: AnyView(header(s))) { t in@@ -948,6 +997,8 @@ struct MainWindowView: View {.buttonStyle(.plain).padding(.top, 32)Button("先听一段示例") { model.ensureListening(); model.sample.play() }.buttonStyle(.plain).font(.system(size: 13)).foregroundStyle(Palette.secondary).padding(.top, 16)+ Button("或导入录音、视频…") { model.chooseImportFiles() }+ .buttonStyle(.plain).font(.system(size: 13)).foregroundStyle(Palette.ink).padding(.top, 8)}.frame(maxWidth: 420).padding(.bottom, 60)@@ -986,10 +1037,13 @@ struct MainWindowView: View {/// Text tabs, the transcript's language choice and 导出…, under the title: no toolbar band.private func tabsRow(_ s: Session) -> some View {HStack(alignment: .center, spacing: 22) {- tabButton(L("纪要"), id: "notes")- tabButton(L("文字记录"), id: "transcript", count: s.lines.count)+ // Notes wait until an imported file is transcribed to the end.+ let importing = importer.status(of: s) != nil+ let active = importing ? "transcript" : tab+ tabButton(L("纪要"), id: "notes", active: active, badge: importing ? L("转完后生成") : nil).disabled(importing)+ tabButton(L("文字记录"), id: "transcript", active: active, count: s.lines.count)Spacer()- if tab == "transcript" {+ if active == "transcript" {Segments(options: [("both", L("双语")), ("src", L("原文")), ("dst", L("译文"))], value: view) { view = $0 }} else if wideEnough, !s.lines.isEmpty {Button { withAnimation(.easeOut(duration: 0.2)) { showQuotes.toggle() } } label: {@@ -1019,13 +1073,14 @@ struct MainWindowView: View {}}- private func tabButton(_ title: String, id: String, count: Int? = nil) -> some View {- let on = tab == id+ private func tabButton(_ title: String, id: String, active: String, count: Int? = nil, badge: String? = nil) -> some View {+ let on = active == idreturn Button { tab = id } label: {HStack(spacing: 5) {Text(title).font(.system(size: 13, weight: on ? .semibold : .regular)).foregroundStyle(on ? Palette.ink : Palette.secondary)if let count { Text("\(count)").font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.secondary) }+ if let badge { Tag(badge) }}.padding(.bottom, 6).overlay(alignment: .bottom) { Rectangle().fill(on ? Palette.ink : .clear).frame(height: 2) }@@ -1044,7 +1099,8 @@ struct MainWindowView: View {return VStack(alignment: .leading, spacing: 0) {HStack(spacing: 8) {if live { Tag(L("正在记录"), live: true) }- Text([dateText(s.startedAt, "MMMdHHmm"), Self.length(s)].joined(separator: " · "))+ Text(([dateText(s.startedAt, "MMMdHHmm"), Self.length(s)] + (s.sourceFile.map { [$0, L("导入")] } ?? [])+ + (s.room == true ? [L("会议室")] : [])).joined(separator: " · ")).font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary).lineLimit(1).help(([dateLine(s, live: live)] + more.compactMap { $0 }).joined(separator: " · "))}@@ -1060,6 +1116,13 @@ struct MainWindowView: View {if !titleDraft.isEmpty { store.rename(s.id, to: titleDraft) }titleDraft = ""}+ if s.sourceFile != nil {+ VStack(alignment: .leading, spacing: 12) {+ ImportStatusStrip(model: model, importer: importer, session: s)+ if player.sessionID == s.id { RecordingPlayerBar(player: player) }+ }+ .padding(.top, 16)+ }tabsRow(s).padding(.top, 24)}.frame(maxWidth: .infinity, alignment: .leading)@@ -1164,12 +1227,22 @@ struct MainWindowView: View {}}- private func lineRow(_ l: TranscriptLine, speaker: Int? = nil, label: Bool = true, voices: Bool = false) -> some View {+ private func lineRow(_ l: TranscriptLine, speaker: Int? = nil, label: Bool = true, voices: Bool = false, in shownSession: Session? = nil) -> some View {let me = l.speaker == "me"return HStack(alignment: .top, spacing: 16) {- Text(TranscriptExport.clock(l.t))- .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary)- .frame(width: 52, alignment: .leading).padding(.top, 1)+ if let shownSession, player.sessionID == shownSession.id, player.ready {+ // An imported file plays from this line.+ Button { player.play(from: l.t) } label: {+ Text(TranscriptExport.clock(l.t))+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.link)+ .frame(width: 52, alignment: .leading).padding(.top, 1).contentShape(Rectangle())+ }+ .buttonStyle(.plain).help(L("从这里播放"))+ } else {+ Text(TranscriptExport.clock(l.t))+ .font(.system(size: 12).monospacedDigit()).foregroundStyle(Palette.tertiary)+ .frame(width: 52, alignment: .leading).padding(.top, 1)+ }VStack(alignment: .leading, spacing: 5) {if !label {} else if let speaker { SpeakerTag(number: speaker) }diff --git a/Tests/LiveSubsTests/ImportTests.swift b/Tests/LiveSubsTests/ImportTests.swiftnew file mode 100644index 0000000..84ce4c1--- /dev/null+++ b/Tests/LiveSubsTests/ImportTests.swift@@ -0,0 +1,91 @@+import AVFoundation+import Foundation+import Testing+@testable import LiveSubs++@Suite struct ImportTests {+ @Test func importableFiles() {+ for name in ["a.m4a", "b.MP3", "c.wav", "d.mp4", "e.mov", "f.aiff"] {+ #expect(FileImporter.importable(URL(fileURLWithPath: "/tmp/\(name)")), "\(name)")+ }+ for name in ["a.txt", "b.pdf", "c", "d.png"] {+ #expect(!FileImporter.importable(URL(fileURLWithPath: "/tmp/\(name)")), "\(name)")+ }+ }++ /// Records written before importing existed still load, and count as not imported.+ @Test func olderSessionsDecode() throws {+ let json = #"{"id":"x","title":"会议 11月1日 14:30","startedAt":"2026-11-01T06:30:00Z","lines":[],"hasAudio":false}"#+ let d = JSONDecoder()+ d.dateDecodingStrategy = .iso8601+ let s = try d.decode(Session.self, from: Data(json.utf8))+ #expect(s.sourceFile == nil && s.sourcePath == nil && s.importing == nil)+ }++ /// An imported file is known by its name until the notes name the meeting.+ @Test func importedTitleIsTheFileName() {+ var s = Session(id: "i", title: Session.defaultTitle(Date()), startedAt: Date(), endedAt: nil, lines: [], hasAudio: false)+ s.sourceFile = "客户访谈.m4a"+ #expect(s.displayTitle == "客户访谈")+ #expect(!MainWindowView.untitled(s))+ s.renamed = true+ s.title = "Renamed"+ #expect(s.displayTitle == "Renamed")+ }++ /// The sound of any file AVFoundation reads comes out as 16 kHz mono, as long as the original.+ @Test func extractsSixteenKilohertzMono() async throws {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-import-test-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: dir) }+ // Two seconds of a stereo 44.1 kHz tone.+ let src = dir.appendingPathComponent("tone.m4a")+ let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)!+ do {+ // Closed when it goes out of scope (`close()` is macOS 15 and later).+ let writer = try AVAudioFile(forWriting: src, settings: [AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 2])+ let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 88_200)!+ buffer.frameLength = 88_200+ for ch in 0..<2 { for i in 0..<88_200 { buffer.floatChannelData![ch][i] = 0.3 * sin(Float(i) * 0.06) } }+ try writer.write(from: buffer)+ }+ let length = try await FileImporter.extractAudio(src, to: dir.appendingPathComponent("out.caf"))+ #expect(abs(length - 2) < 0.1)+ let out = try AVAudioFile(forReading: dir.appendingPathComponent("out.caf"))+ #expect(out.processingFormat.sampleRate == 16_000)+ #expect(out.processingFormat.channelCount == 1)+ }+}++@Suite struct ImportSentenceTests {+ @Test func longResultSplitsAtSentenceEnds() {+ let pieces: [(String, Double?)] = [("来年", 0.2), ("一月から", 0.6), ("試験導入できます。", 1.0),+ ("法務の", 3.1), ("確認は", 3.4), ("今週中に", 3.8), ("お返事します。", 4.2),+ ("以上", 6.0)]+ let s = FileImporter.sentences(pieces, start: 0)+ #expect(s.map(\.text) == ["来年一月から試験導入できます。", "法務の確認は今週中にお返事します。", "以上"])+ #expect(s.map(\.t) == [0.2, 3.1, 6.0])+ }++ @Test func shortSentencesStayTogether() {+ let pieces: [(String, Double?)] = [("OK.", 1), (" Mr.", 2), (" Lee will call.", 3)]+ let s = FileImporter.sentences(pieces, start: 0.5)+ #expect(s.map(\.text) == ["OK. Mr. Lee will call."])+ #expect(s.first?.t == 1)+ }++ /// macOS 14/15: one timed line, split at its sentence marks, each timed by its place in the line.+ @Test func legacyLineSplitsByCharacters() {+ let line = Recognition.Piece(text: "Good morning everyone. Let's review the launch plan.", isFinal: true,+ start: 10, end: 20.4, confidence: nil)+ let s = FileImporter.sentences(FileImporter.words(line), start: line.start)+ #expect(s.map(\.text) == ["Good morning everyone.", "Let's review the launch plan."])+ #expect(s.first?.t == 10)+ #expect(abs((s.last?.t ?? 0) - 14.4) < 0.01)+ }++ @Test func missingTimesFallBack() {+ let s = FileImporter.sentences([("Hello there, everyone.", nil), (" How are you?", nil)], start: 7)+ #expect(s.map(\.t) == [7, 7])+ }+}diff --git a/tools/README.md b/tools/README.mdindex 7c0d329..2d1abe5 100644--- a/tools/README.md+++ b/tools/README.md@@ -19,9 +19,10 @@- 识别引擎:`recognizer:legacy` 在 macOS 26 上改用 14 / 15 的识别(`SFSpeechRecognizer`,第一次会要“语音识别”权限),`recognizer:auto` 换回;下一次开始听起生效(或启动时 `open --env CICADA_RECOGNIZER=legacy`),日志里 `transcriber started recognizer=…`- 多开:两边都设 `CICADA_DEBUG_CHANNEL=x`(`open -n --env CICADA_DEBUG_CHANNEL=x build/Cicada.app`),命令只发给这一份,日志在 `/tmp/livesubs-dev-debug-x.log`- 导出:`export:<目录>`- - 新手引导与窗口:`onboarding:<步骤>[,skip|ask|setup]`(1–5,5 是收尾页;skip 是第 3 步点了“先不接”,ask / setup 是第 4 步的二选一 / 清单)、`samplePlay`、`speakers:<on|off>`(实验功能“说话人识别”)、`speakerGuess:<会议 id>`(马上让 Ling 认一遍名字)、`speakersRender:<会议 id>=<png>`、`voiceprintFile:<音频>=<json>`(用 app 里的声纹模型算整个文件的声纹,和参考模型对比)、`closeWindow:<main|settings|onboarding>`、`settings:<overlay|language|speak|records|ai|diagnostics>`、`about`- - 显示与字幕:`display:<notes|bar|none>`、`subtitles:<both|translation|original>`、`meetingSubtitles:<…>`、`overlayState`、`overlayToggle`、`overlayAuto[:off]`、`hideAfter:<秒>`- - 纪要:`notesLang:<mine|source>`、`meetingNotesLang:<…>`、`notesRegenerate:<id>=<mine|source>`、`notesWindow[:x,y,w,h]`、`notesClose`、`notesFrame`、`notesNow`、`notesState`、`notesShow:<id>`、`notesReplay:<id>`、`notesCapturable[:off]`(只改窗口能否被截屏)、`notesShare:<on|off>`(改“共享屏幕时让对方看到”这个设置,等于点图标或开关)+ - 导入录音或视频:`import:<路径>[,<路径>…]`(等于拖进会议记录窗口),`importState` 把进度写进日志,`importCancel` 停止转写,`importRetry:<会议 id>` 重新转写,`importNotify` 把通知权限写进日志+ - 新手引导与窗口:`onboarding:<步骤>[,skip|ask|setup]`(1–5,5 是收尾页;skip 是第 3 步点了“先不接”,ask / setup 是第 4 步的二选一 / 清单)、`samplePlay`、`speakers:<on|off>`(“说话人识别”)、`speakerGuess:<会议 id>`(马上让 Ling 认一遍名字)、`speakersRender:<会议 id>=<png>`、`voiceprintFile:<音频>=<json>`(用 app 里的声纹模型算整个文件的声纹,和参考模型对比)、`closeWindow:<main|settings|onboarding>`、`settings:<overlay|language|speak|records|ai|diagnostics>`、`about`+ - 显示与字幕:`display:<notes|bar|none>`、`subtitles:<both|translation|original>`、`meetingSubtitles:<…>`、`overlayState`、`overlayToggle`、`pillClick`(等于点主窗口顶部的“正在听”)、`overlayAuto[:off]`、`hideAfter:<秒>`+ - 纪要:`notesLang:<mine|source>`、`meetingNotesLang:<…>`、`notesRegenerate:<id>=<mine|source>`、`notesWindow[:x,y,w,h]`、`notesClose`、`notesMinimize`、`notesFrame`、`notesNow`、`notesState`、`notesShow:<id>`、`notesReplay:<id>`、`notesCapturable[:off]`(只改窗口能否被截屏)、`notesShare:<on|off>`(改“共享屏幕时让对方看到”这个设置,等于点图标或开关)- 结束会议:`endSim:<应用名>[,…]` 假装这些会议应用在通话(`endSim:` 全部挂断,`endSim:off` 回到真实情况),`endTimes:<静默秒>,<倒计时秒>,<挂断宽限秒>` 缩短等待(`endTimes:` 回到设置),`endKeep` 等于点“继续记录”,`endState` 写进日志- 渲染(不需要录屏权限):`panelRender:<png>`(菜单栏面板,离屏画)、`windowsRender:<目录>`、`settingsRender:<栏目>=<png>`、`notesRender:<png>`、`mainShow:<id>[,transcript]`、`mainRender:<png>`、`speakTestRender:<png>`- AI:`aiKeyFile:<路径>`(从 0600 文件读 key,不经过日志;测完就删掉文件)、`aiCheck`、`aiRemove`、`aiHide:<on|off>`(只在内存里当作没有 key,文件不动;用于截图)、`aiState`、`lingSimulate:<429|hijack|timeout|off>`、`translateFail:<n>`(接下来 n 句在所有翻译来源都失败,用来测重试)