知了 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
fix: end long lines at short pauses so sentences finish sooner
wqugurua5e3a99b0679
diff --git a/Sources/LiveSubs/AudioRouter.swift b/Sources/LiveSubs/AudioRouter.swiftindex 0719ee9..b6fa81f 100644--- a/Sources/LiveSubs/AudioRouter.swift+++ b/Sources/LiveSubs/AudioRouter.swift@@ -59,6 +59,8 @@ final class AudioRouter: @unchecked Sendable {private var voicedTotal = 0.0private var silenceRun = 0.0private var sinceGap = 0.0+ /// The last short pause between words, on the analyzer's clock: where it ended and how long it was.+ private var pause: (end: Double, length: Double) = (0, 0)private var recordURL: URL?private var recorder: AVAudioFile?@@ -79,6 +81,7 @@ final class AudioRouter: @unchecked Sendable {let seconds = Double(n) / mono.format.sampleRatelet voiced = rms >= voiceThresholdif voiced {+ if silenceRun >= 0.12, continuation != nil { pause = (fed, silenceRun) }if silenceRun >= Self.gapSeconds { sinceGap = 0 }voicedTotal += secondssilenceRun = 0@@ -121,10 +124,15 @@ final class AudioRouter: @unchecked Sendable {/// result ending at t was spoken (fed − t) seconds ago, since the tap runs in real time.private var fed = 0.0func fedSeconds() -> Double { queue.sync { fed } }+ /// Analyzer clock now, the silence running at the end of it, and the last pause before that.+ func clock() -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) {+ queue.sync { (fed, silenceRun, pause) }+ }func attach(format: AVAudioFormat, continuation: AsyncStream<AnalyzerInput>.Continuation, replaySeconds: Double = 0) {queue.sync {fed = 0+ pause = (0, 0)if self.format != format {ring.removeAll()ringSeconds = 0diff --git a/Sources/LiveSubs/ListenEngine.swift b/Sources/LiveSubs/ListenEngine.swiftindex 34f2acb..d251025 100644--- a/Sources/LiveSubs/ListenEngine.swift+++ b/Sources/LiveSubs/ListenEngine.swift@@ -58,6 +58,14 @@ final class ListenEngine {private var volatileInFlight = falseprivate var volatileEpoch = 0private var tickTimer: Timer?+ private var ticks = 0+ /// When the line in progress started and last grew, for cutting long ones at a pause.+ private var volatileStartedAt = Date()+ private var volatileStartClock = 0.0+ private var volatileChangedAt = Date()+ private var cutting = false+ private var lastCut = ""+ private var lastCutThrough = 0.0/// Final transcript time and how long after the last word it came, per segment, until its translation lands.private var finalTiming: [Int: (at: Date, recognize: Double?)] = [:]@@ -344,6 +352,8 @@ final class ListenEngine {needsDetection = true}} else {+ if volatileText.isEmpty { volatileStartedAt = Date(); volatileStartClock = router.fedSeconds() }+ if text != volatileText { volatileChangedAt = Date() }volatileText = text}renderSubtitles()@@ -447,10 +457,15 @@ final class ListenEngine {private func startTickTimer() {tickTimer?.invalidate()- let timer = Timer(timeInterval: 1.0, repeats: true) { [weak self] _ in+ // Pauses are short: look for one four times a second; the rest runs once a second.+ let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ inMainActor.assumeIsolated {- self?.translateVolatile()- self?.maybeDetectLanguage()+ guard let self else { return }+ self.maybeCutSentence()+ self.ticks += 1+ guard self.ticks % 4 == 0 else { return }+ self.translateVolatile()+ self.maybeDetectLanguage()}}tickTimer = timer@@ -497,6 +512,45 @@ final class ListenEngine {}}+ /// SpeechTranscriber ends a sentence only at a clear pause; in a quick conversation that can+ /// take 15–20 s, and the subtitle stays a draft that long (the notes wait for it too). A long+ /// line in progress is ended at the next small pause: a dip in the sound, or no new words for+ /// a moment.+ private func maybeCutSentence() {+ guard isRunning, !cutting, let analyzer, !volatileText.isEmpty, volatileText != lastCut else { return }+ let cjk = joiner(for: activeLang?.code ?? "") == ""+ let long = cjk ? volatileText.count >= 24 : volatileText.split(separator: " ").count >= 10+ guard long else { return }+ // The longer the line has run, the smaller the pause that may end it.+ let held = Date().timeIntervalSince(volatileStartedAt)+ let needed = held >= 8 ? 0.15 : 0.3+ let c = router.clock()+ let mid = c.pause.end - c.pause.length / 2+ let through: Double, why: String+ if c.silence >= needed {+ (through, why) = (c.fed, "quiet")+ } else if c.pause.length >= needed, mid > volatileStartClock + 1.5, mid > lastCutThrough, c.pause.end <= c.fed {+ (through, why) = (mid, "pause") // a pause already behind us: end the line there+ } else if Date().timeIntervalSince(volatileChangedAt) >= (held >= 8 ? 0.6 : 1.2) {+ (through, why) = (c.fed, "stalled")+ } else {+ return+ }+ cutting = true+ lastCut = volatileText+ lastCutThrough = through+ let chars = volatileText.count+ Task { [weak self] in+ do {+ try await analyzer.finalize(through: CMTime(seconds: through, preferredTimescale: 1000))+ debugLog(String(format: "cut: line of %d chars ended after %.1f s (%@)", chars, held, why))+ } catch {+ debugLog("cut: finalize failed \(error)")+ }+ self?.cutting = false+ }+ }+private func translateVolatile() {guard isRunning, !translationOff(), !volatileInFlight, volatileText.count >= 2, volatileText != lastVolatileSent else { return }let text = volatileText