Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(ios): listen to video played aloud on the phone, with subtitles floating in picture in picture, and pick up again by itself after a call or Siri

wquguru81be0be1330d
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index 38761b9..556d17d 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -1400,3 +1400,16 @@
"选择麦克风" = "Choose microphone";
"会议室用哪个麦克风" = "Microphone for the room";
"%@(只听得到戴的人)" = "%@ (hears only the wearer)";
+
+/* iOS: 声音来源, interruptions, picture-in-picture subtitles */
+"声音来源" = "Audio source";
+"手机外放" = "Phone speaker";
+"外放" = "Speaker";
+"外放 · %@" = "Speaker · %@";
+"别戴耳机,字幕会浮在小窗里" = "No headphones; subtitles float in a small window";
+"听不到其他 app 的声音,线上会议请用电脑版" = "Can't hear other apps; use a computer for online meetings";
+"已暂停,结束后接着听" = "Paused; resumes when it's over";
+"继续听" = "Listening again";
+"正在听外放…" = "Listening to the speaker…";
+"知了 · 正在听" = "Cicada · Listening";
+"没听到声音,请拔掉耳机或调大音量" = "No sound; unplug headphones or turn it up";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index a8710f8..efaeea4 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -1400,3 +1400,16 @@
"选择麦克风" = "マイクを選択";
"会议室用哪个麦克风" = "会議室で使うマイク";
"%@(只听得到戴的人)" = "%@(装着している人の声だけ)";
+
+/* iOS: 声音来源, interruptions, picture-in-picture subtitles */
+"声音来源" = "音声の入力元";
+"手机外放" = "スピーカー再生";
+"外放" = "スピーカー";
+"外放 · %@" = "スピーカー · %@";
+"别戴耳机,字幕会浮在小窗里" = "イヤホンは外してください。字幕は小窓に表示されます";
+"听不到其他 app 的声音,线上会议请用电脑版" = "他のアプリの音は聞けません。オンライン会議はパソコン版で";
+"已暂停,结束后接着听" = "一時停止中。終わったら再開します";
+"继续听" = "再開しました";
+"正在听外放…" = "スピーカーを聞いています…";
+"知了 · 正在听" = "Cicada · 聞いています";
+"没听到声音,请拔掉耳机或调大音量" = "音が聞こえません。イヤホンを外すか音量を上げてください";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index aa6638b..8e564c1 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -1400,3 +1400,16 @@
"选择麦克风" = "마이크 선택";
"会议室用哪个麦克风" = "회의실에서 쓸 마이크";
"%@(只听得到戴的人)" = "%@ (착용한 사람 목소리만)";
+
+/* iOS: 声音来源, interruptions, picture-in-picture subtitles */
+"声音来源" = "소리 입력";
+"手机外放" = "휴대폰 스피커";
+"外放" = "스피커";
+"外放 · %@" = "스피커 · %@";
+"别戴耳机,字幕会浮在小窗里" = "이어폰을 빼세요. 자막은 작은 창에 떠 있어요";
+"听不到其他 app 的声音,线上会议请用电脑版" = "다른 앱 소리는 못 들어요. 온라인 회의는 컴퓨터 버전으로";
+"已暂停,结束后接着听" = "일시정지됨. 끝나면 이어서 들어요";
+"继续听" = "다시 듣는 중";
+"正在听外放…" = "스피커를 듣는 중…";
+"知了 · 正在听" = "Cicada · 듣는 중";
+"没听到声音,请拔掉耳机或调大音量" = "소리가 안 들려요. 이어폰을 빼거나 볼륨을 높이세요";
diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.strings
index 39ce922..b0e977c 100644
--- a/Resources/zh-Hans.lproj/Localizable.strings
+++ b/Resources/zh-Hans.lproj/Localizable.strings
@@ -1323,3 +1323,16 @@
"导入 %lld 个" = "导入 %lld 个";
/* Notes: a to-do's owner after it */
"待办的负责人 %@" = "(%@)";
+
+/* iOS: 声音来源, interruptions, picture-in-picture subtitles */
+"声音来源" = "声音来源";
+"手机外放" = "手机外放";
+"外放" = "外放";
+"外放 · %@" = "外放 · %@";
+"别戴耳机,字幕会浮在小窗里" = "别戴耳机,字幕会浮在小窗里";
+"听不到其他 app 的声音,线上会议请用电脑版" = "听不到其他 app 的声音,线上会议请用电脑版";
+"已暂停,结束后接着听" = "已暂停,结束后接着听";
+"继续听" = "继续听";
+"正在听外放…" = "正在听外放…";
+"知了 · 正在听" = "知了 · 正在听";
+"没听到声音,请拔掉耳机或调大音量" = "没听到声音,请拔掉耳机或调大音量";
diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swift
index d1195b0..54705c5 100644
--- a/ios/Sources/Cicada/CicadaApp.swift
+++ b/ios/Sources/Cicada/CicadaApp.swift
@@ -1,3 +1,4 @@
+import Combine
import SwiftUI
@main
@@ -12,6 +13,9 @@ struct CicadaApp: App {
.environmentObject(model.notes)
.environmentObject(model.room)
.onOpenURL { model.open($0) }
+ .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
+ model.room.appBecameActive()
+ }
.modifier(DevWindow(model: model))
}
}
@@ -34,6 +38,9 @@ enum Pref {
/// 会中改正听错的词, and 没见过的名字和专称先问我.
static let fixMisheard = "fixMisheard"
static let askNames = "askNames"
+ /// 声音来源 (iOS only): "room", people at the table, or "speaker", video this phone plays aloud.
+ static let hear = "iosHear"
+ static var speakerMode: Bool { UserDefaults.standard.string(forKey: hear) == "speaker" }
/// 对方说 on iOS: one language the user picks (detecting it comes later); the Mac's "auto" reads as English.
static var sourceLang: Lang {
@@ -79,8 +86,14 @@ final class AppModel: ObservableObject {
let r = RoomListen(store: store, translator: translator, notes: notes)
r.onStateChange = { [weak self] in self?.listeningChanged() }
r.onLine = { [weak self] line in self?.showOnLockScreen(line) }
+ // The floating window follows the 字幕 page: what is being said, else the newest line.
+ roomWatch = r.objectWillChange.sink { [weak self] _ in
+ DispatchQueue.main.async { self?.showInPiP() }
+ }
return r
}()
+ let pip = PiPSubtitles()
+ private var roomWatch: AnyCancellable?
let liveActivity = LiveActivityController()
/// 词表 and 改正听错的词, the Mac's own engines.
let vocabulary = Vocabulary(url: Vocabulary.defaultURL)
@@ -143,7 +156,21 @@ final class AppModel: ObservableObject {
searchPath = []
tab = .records
fixes.meetingStarted()
- room.start(source: Pref.sourceLang.locale, target: Pref.targetCode, voices: UserDefaults.standard.bool(forKey: Pref.voices))
+ room.start(source: Pref.sourceLang.locale, target: Pref.targetCode, voices: UserDefaults.standard.bool(forKey: Pref.voices),
+ speaker: Pref.speakerMode)
+ }
+
+ private func showInPiP() {
+ guard room.isRunning, room.speakerMode else { return }
+ let last = room.lines.last
+ let shown = last.flatMap { l in store.session(room.sessionID)?.lines.first { $0.id == l.id }?.shown } ?? last?.src
+ if room.paused || !room.status.isEmpty {
+ pip.show(src: "", dst: "", note: room.paused ? L("已暂停,结束后接着听") : room.status)
+ } else if !room.draft.isEmpty {
+ pip.show(src: room.draft, dst: room.draftTranslation, note: L("正在听外放…"))
+ } else {
+ pip.show(src: shown ?? "", dst: last?.dst ?? "", note: shown == nil ? L("正在听外放…") : "")
+ }
}
func stopListening() { room.stop() }
@@ -157,6 +184,7 @@ final class AppModel: ObservableObject {
private func listeningChanged() {
objectWillChange.send()
+ pip.setEnabled(room.isRunning && room.speakerMode)
if room.isRunning, let start = room.startedAt {
liveActivity.start(startedAt: start, pair: Pref.pairText(room.languagePair.source, room.languagePair.target))
} else if !room.isRunning {
diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swift
index 157022f..3b4cda2 100644
--- a/ios/Sources/Cicada/Debug.swift
+++ b/ios/Sources/Cicada/Debug.swift
@@ -65,6 +65,14 @@ extension AppModel {
case "import":
// What the import button shows until M3.
comingSoon = L("导入录音或视频")
+ case "hear":
+ // hear:room|speaker, 声音来源
+ UserDefaults.standard.set(arg == "speaker" ? "speaker" : "room", forKey: Pref.hear)
+ case "interrupt":
+ // interrupt:began|ended, what the system sends for a call or Siri
+ room.debugInterrupt(arg != "ended")
+ case "pip":
+ pip.start()
case "livePage":
livePage = arg == "notes" ? .notes : .subtitles
case "source":
@@ -221,7 +229,7 @@ extension AppModel {
case "wordDelete":
if let t = vocabulary.terms.first(where: { $0.word == arg }) { deleteWord(t) }
case "state":
- debugLog("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) session=\(room.sessionID ?? "-")")
+ debugLog("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) speaker=\(room.speakerMode) paused=\(room.paused) pip=\(pip.isActive) session=\(room.sessionID ?? "-")")
debugLog("state tab=\(tab.rawValue) selection=\(selection ?? "-") page=\(recordPage) sessions=\(store.sessions.count) query=\(query) notesLang=\(notesLanguageCode(selection ?? store.sessions.first?.id ?? "")) undo=\(speakerUndo?.text ?? "-")")
default:
debugLog("debug command unknown: \(cmd)")
diff --git a/ios/Sources/Cicada/LiveViews.swift b/ios/Sources/Cicada/LiveViews.swift
index 83987f8..dcc698a 100644
--- a/ios/Sources/Cicada/LiveViews.swift
+++ b/ios/Sources/Cicada/LiveViews.swift
@@ -25,7 +25,8 @@ struct HomeTitle: View {
.font(.footnote.weight(.semibold).monospacedDigit())
.foregroundStyle(Ink.accentText)
}
- Text(L("会议室 · \(Pref.pairText(room.languagePair.source, room.languagePair.target))"))
+ let pair = Pref.pairText(room.languagePair.source, room.languagePair.target)
+ Text(room.speakerMode ? L("外放 · \(pair)") : L("会议室 · \(pair)"))
.font(.system(size: titleSize - 4, weight: .bold)).foregroundStyle(Ink.ink)
.lineLimit(1).minimumScaleFactor(0.7)
} else {
@@ -58,6 +59,7 @@ struct ListenBar: View {
@EnvironmentObject var room: RoomListen
@AppStorage(Pref.source) private var source = "en-US"
@AppStorage(Pref.target) private var target = "system"
+ @AppStorage(Pref.hear) private var hear = "room"
/// Glass on the ground (iPhone); white on the iPad's glass sidebar.
var onGlass = false
@@ -80,6 +82,15 @@ struct ListenBar: View {
Text("开始听").font(.headline).foregroundStyle(Ink.ink).padding(.leading, 18)
Rectangle().fill(Ink.line).frame(width: 1, height: 20)
Menu {
+ Section {
+ Picker(selection: $hear) {
+ Text("会议室").tag("room")
+ Text("手机外放").tag("speaker")
+ } label: { Text("声音来源") }
+ .pickerStyle(.inline)
+ // The one grey line: what 手机外放 needs, else what iPhone can't hear at all.
+ Text(hear == "speaker" ? L("别戴耳机,字幕会浮在小窗里") : L("听不到其他 app 的声音,线上会议请用电脑版"))
+ }
Picker(selection: $source) {
ForEach(sourceLanguages, id: \.locale) { Text(Pref.name(of: $0)).tag($0.locale) }
} label: { Text("对方说") }
@@ -88,7 +99,7 @@ struct ListenBar: View {
ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }
} label: { Text("翻译成") }
} label: {
- Text(verbatim: "\(Pref.sourceName) → \(targetName(Pref.targetCode))")
+ Text(verbatim: (hear == "speaker" ? L("外放") + " · " : "") + "\(Pref.sourceName) → \(targetName(Pref.targetCode))")
.font(.subheadline).foregroundStyle(Ink.secondary).lineLimit(1).minimumScaleFactor(0.75)
.frame(maxWidth: .infinity, alignment: .leading)
.frame(minHeight: 44)
@@ -177,6 +188,7 @@ struct LivePhone: View {
ScrollView { NotesPage(notes: notes.notes).padding(20) }
}
}
+ .background(alignment: .topLeading) { PiPHost(pip: model.pip).frame(width: 4, height: 4) }
.background(Ink.ground)
.overlay(alignment: .bottom) { FixToast(fixes: model.fixes).padding(.horizontal, 16).padding(.bottom, 8) }
.animation(.snappy(duration: 0.2), value: model.fixes.toast)
@@ -281,6 +293,7 @@ struct LivePad: View {
}
}
}
+ .background(alignment: .topLeading) { PiPHost(pip: model.pip).frame(width: 4, height: 4) }
.background(Ink.ground)
.overlay(alignment: .bottom) { FixToast(fixes: model.fixes).frame(maxWidth: 560).padding(.horizontal, 20).padding(.bottom, 12) }
.animation(.snappy(duration: 0.2), value: model.fixes.toast)
diff --git a/ios/Sources/Cicada/PiPSubtitles.swift b/ios/Sources/Cicada/PiPSubtitles.swift
new file mode 100644
index 0000000..c63a4c9
--- /dev/null
+++ b/ios/Sources/Cicada/PiPSubtitles.swift
@@ -0,0 +1,186 @@
+import AVFoundation
+import AVKit
+import SwiftUI
+import UIKit
+
+/// 手机外放's subtitles over other apps: iOS lets an app float only a picture-in-picture video, so
+/// the newest line is drawn into frames and fed to a sample buffer layer as a live stream. It starts
+/// by itself when the app goes to the background while listening to video played aloud.
+@MainActor
+final class PiPSubtitles: NSObject, ObservableObject {
+ /// The layer PiP takes its frames from; it has to sit in the window (PiPHost).
+ let layer = AVSampleBufferDisplayLayer()
+ @Published private(set) var isActive = false
+ private var controller: AVPictureInPictureController?
+ private var shown: Caption?
+ private var pending: Caption?
+ private var drawing = false
+
+ struct Caption: Equatable {
+ var src: String
+ var dst: String
+ var note: String
+ }
+
+ /// 32:10 at the scale the window is drawn: wide enough for two lines of Chinese.
+ static let size = CGSize(width: 960, height: 300)
+
+ override init() {
+ super.init()
+ layer.videoGravity = .resizeAspect
+ draw(Caption(src: "", dst: "", note: L("正在听外放…")))
+ }
+
+ /// On while 手机外放 is listening, so leaving the app floats the window; off otherwise.
+ func setEnabled(_ on: Bool) {
+ if on, controller == nil, AVPictureInPictureController.isPictureInPictureSupported() {
+ let source = AVPictureInPictureController.ContentSource(sampleBufferDisplayLayer: layer, playbackDelegate: self)
+ let c = AVPictureInPictureController(contentSource: source)
+ c.delegate = self
+ c.requiresLinearPlayback = true
+ controller = c
+ }
+ controller?.canStartPictureInPictureAutomaticallyFromInline = on
+ if !on, controller?.isPictureInPictureActive == true { controller?.stopPictureInPicture() }
+ debugLog("pip: enabled=\(on) supported=\(AVPictureInPictureController.isPictureInPictureSupported())")
+ }
+
+ /// Debug (`pip`): float it now, as leaving the app would.
+ func start() {
+ debugLog("pip: start possible=\(controller?.isPictureInPicturePossible ?? false)")
+ controller?.startPictureInPicture()
+ }
+
+ func show(src: String, dst: String, note: String) {
+ let c = Caption(src: src, dst: dst, note: note)
+ guard c != shown else { return }
+ pending = c
+ guard !drawing else { return }
+ // A few frames a second at most: a draft changes on every word.
+ drawing = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { [weak self] in
+ guard let self else { return }
+ self.drawing = false
+ if let p = self.pending { self.pending = nil; self.draw(p) }
+ }
+ }
+
+ private func draw(_ c: Caption) {
+ shown = c
+ guard let buffer = Self.frame(c) else { return }
+ let renderer = layer.sampleBufferRenderer
+ if renderer.status == .failed { renderer.flush() }
+ renderer.enqueue(buffer)
+ }
+
+ /// The design's dark card: 知了 · 正在听 in the accent, what was said in grey, the translation in white.
+ private static func frame(_ c: Caption) -> CMSampleBuffer? {
+ let image = UIGraphicsImageRenderer(size: size, format: { let f = UIGraphicsImageRendererFormat(); f.scale = 1; return f }()).image { ctx in
+ UIColor(red: 0x15 / 255, green: 0x17 / 255, blue: 0x1C / 255, alpha: 1).setFill()
+ ctx.fill(CGRect(origin: .zero, size: size))
+ let pad: CGFloat = 40
+ let width = size.width - pad * 2
+ let accent = UIColor(red: 0xFF / 255, green: 0x8A / 255, blue: 0x63 / 255, alpha: 1)
+ accent.setFill()
+ UIBezierPath(ovalIn: CGRect(x: pad, y: 42, width: 14, height: 14)).fill()
+ (L("知了 · 正在听") as NSString).draw(at: CGPoint(x: pad + 26, y: 30), withAttributes: [
+ .font: UIFont.systemFont(ofSize: 30, weight: .semibold), .foregroundColor: accent])
+ let para = NSMutableParagraphStyle()
+ para.lineBreakMode = .byTruncatingHead
+ var y: CGFloat = 92
+ if !c.src.isEmpty {
+ (c.src as NSString).draw(in: CGRect(x: pad, y: y, width: width, height: 44), withAttributes: [
+ .font: UIFont.systemFont(ofSize: 30), .foregroundColor: UIColor(white: 0.74, alpha: 1), .paragraphStyle: para])
+ y += 52
+ }
+ let main = c.dst.isEmpty ? c.note : c.dst
+ let wrap = NSMutableParagraphStyle()
+ wrap.lineBreakMode = .byWordWrapping
+ wrap.lineSpacing = 6
+ // The end of a long line matters most: keep its last two lines.
+ let font = UIFont.systemFont(ofSize: 46, weight: .medium)
+ let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: UIColor.white, .paragraphStyle: wrap]
+ let text = tail(main, fitting: CGSize(width: width, height: size.height - y - 24), attrs)
+ (text as NSString).draw(in: CGRect(x: pad, y: y, width: width, height: size.height - y - 16), withAttributes: attrs)
+ }
+ guard let cg = image.cgImage else { return nil }
+ var pb: CVPixelBuffer?
+ let props = [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary
+ guard CVPixelBufferCreate(nil, Int(size.width), Int(size.height), kCVPixelFormatType_32BGRA, props, &pb) == kCVReturnSuccess,
+ let pb else { return nil }
+ CVPixelBufferLockBaseAddress(pb, [])
+ let ctx = CGContext(data: CVPixelBufferGetBaseAddress(pb), width: Int(size.width), height: Int(size.height),
+ bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pb), space: CGColorSpaceCreateDeviceRGB(),
+ bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
+ ctx?.draw(cg, in: CGRect(origin: .zero, size: size))
+ CVPixelBufferUnlockBaseAddress(pb, [])
+ var format: CMVideoFormatDescription?
+ CMVideoFormatDescriptionCreateForImageBuffer(allocator: nil, imageBuffer: pb, formatDescriptionOut: &format)
+ guard let format else { return nil }
+ var timing = CMSampleTimingInfo(duration: .invalid, presentationTimeStamp: CMClockGetTime(CMClockGetHostTimeClock()), decodeTimeStamp: .invalid)
+ var sample: CMSampleBuffer?
+ CMSampleBufferCreateReadyWithImageBuffer(allocator: nil, imageBuffer: pb, formatDescription: format, sampleTiming: &timing, sampleBufferOut: &sample)
+ if let sample, let list = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true), CFArrayGetCount(list) > 0 {
+ let dict = unsafeBitCast(CFArrayGetValueAtIndex(list, 0), to: CFMutableDictionary.self)
+ CFDictionarySetValue(dict, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(),
+ Unmanaged.passUnretained(kCFBooleanTrue).toOpaque())
+ }
+ return sample
+ }
+
+ /// The shortest ending of `text` that fills `box`, starting at a character boundary.
+ private static func tail(_ text: String, fitting box: CGSize, _ attrs: [NSAttributedString.Key: Any]) -> String {
+ func fits(_ s: String) -> Bool {
+ (s as NSString).boundingRect(with: CGSize(width: box.width, height: .greatestFiniteMagnitude),
+ options: .usesLineFragmentOrigin, attributes: attrs, context: nil).height <= box.height
+ }
+ if fits(text) { return text }
+ var s = Substring(text)
+ while !s.isEmpty, !fits("…" + s) { s = s.dropFirst(max(1, s.count / 12)) }
+ return "…" + s
+ }
+}
+
+extension PiPSubtitles: AVPictureInPictureControllerDelegate, AVPictureInPictureSampleBufferPlaybackDelegate {
+ nonisolated func pictureInPictureControllerDidStartPictureInPicture(_ c: AVPictureInPictureController) {
+ MainActor.assumeIsolated { isActive = true; debugLog("pip: started") }
+ }
+
+ nonisolated func pictureInPictureControllerDidStopPictureInPicture(_ c: AVPictureInPictureController) {
+ MainActor.assumeIsolated { isActive = false; debugLog("pip: stopped") }
+ }
+
+ nonisolated func pictureInPictureController(_ c: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) {
+ MainActor.assumeIsolated { debugLog("pip: failed \(error)") }
+ }
+
+ nonisolated func pictureInPictureController(_ c: AVPictureInPictureController, setPlaying playing: Bool) {}
+
+ /// A live stream: no timeline, no skipping.
+ nonisolated func pictureInPictureControllerTimeRangeForPlayback(_ c: AVPictureInPictureController) -> CMTimeRange {
+ CMTimeRange(start: .negativeInfinity, duration: .positiveInfinity)
+ }
+
+ nonisolated func pictureInPictureControllerIsPlaybackPaused(_ c: AVPictureInPictureController) -> Bool { false }
+
+ nonisolated func pictureInPictureController(_ c: AVPictureInPictureController, didTransitionToRenderSize newRenderSize: CMVideoDimensions) {}
+
+ nonisolated func pictureInPictureController(_ c: AVPictureInPictureController, skipByInterval skipInterval: CMTime,
+ completion: @escaping () -> Void) { completion() }
+}
+
+/// Holds the PiP layer in the window, as PiP requires; a few points, under the page.
+struct PiPHost: UIViewRepresentable {
+ let pip: PiPSubtitles
+
+ func makeUIView(context: Context) -> UIView {
+ let v = UIView()
+ v.isUserInteractionEnabled = false
+ v.layer.addSublayer(pip.layer)
+ return v
+ }
+
+ func updateUIView(_ v: UIView, context: Context) {
+ pip.layer.frame = v.bounds
+ }
+}
diff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swift
index 825bd27..0597374 100644
--- a/ios/Sources/Cicada/RoomListen.swift
+++ b/ios/Sources/Cicada/RoomListen.swift
@@ -26,6 +26,11 @@ final class RoomListen: ObservableObject {
@Published private(set) var level: Float = 0
@Published private(set) var status = ""
@Published private(set) var sessionID: String?
+ /// 手机外放: a video app plays aloud while we listen from the background, so its audio keeps
+ /// playing beside ours and the subtitles go to the picture-in-picture window (PiPSubtitles).
+ @Published private(set) var speakerMode = false
+ /// A call, Siri or another app took the audio: the microphone is off until it ends.
+ @Published private(set) var paused = false
/// Every finished line, for the Live Activity.
var onLine: ((Line) -> Void)?
@@ -73,8 +78,10 @@ final class RoomListen: ObservableObject {
var elapsed: TimeInterval { startedAt.map { Date().timeIntervalSince($0) } ?? 0 }
var languagePair: (source: String, target: String) { (lang.code, target) }
- func start(source: String, target: String, voices: Bool) {
+ func start(source: String, target: String, voices: Bool, speaker: Bool = false) {
guard !isRunning else { return }
+ speakerMode = speaker
+ paused = false
lang = sourceLanguages.first { $0.locale == source } ?? sourceLanguages[0]
self.target = target
status = L("正在准备…")
@@ -118,16 +125,23 @@ final class RoomListen: ObservableObject {
guard isRunning else { await stream.cancel(); return }
self.stream = stream
let s = store.begin()
- store.markLiveInRoom()
+ // Video played aloud is what the computer plays, not people in the room (the Mac's 会议室 tag).
+ if !speakerMode { store.markLiveInRoom() }
sessionID = s.id
startedAt = s.startedAt
notes.begin(s.id)
audio.voices = voices
+ audio.mix = speakerMode
+ audio.onInterruption = { [weak self] began in self?.interrupted(began) }
try audio.start(recognizer: stream, recording: AudioFileWriter.partial(store.systemAudioURL(s.id)))
heardVoice = false
audio.onLevel = { [weak self] v in
- self?.level = v
- if v > 0.55 { self?.heardVoice = true }
+ guard let self, !self.paused else { return }
+ self.level = v
+ if v > 0.55 {
+ self.heardVoice = true
+ if self.status == L("没听到声音,请拔掉耳机或调大音量") { self.status = "" }
+ }
}
reader = Task { [weak self] in
do {
@@ -141,7 +155,8 @@ final class RoomListen: ObservableObject {
}
}
status = ""
- debugLog("room: listening locale=\(lang.locale) target=\(target) format=\(stream.format) session=\(s.id)")
+ if speakerMode { watchSilence(s.id) }
+ debugLog("room: listening locale=\(lang.locale) target=\(target) speaker=\(speakerMode) format=\(stream.format) session=\(s.id)")
onStateChange?()
} catch {
debugLog("room: start failed: \(error)")
@@ -149,6 +164,56 @@ final class RoomListen: ObservableObject {
}
}
+ /// Paused while the audio is taken, then on again by itself; if the system won't give the
+ /// microphone back yet (the app is still behind a call screen), again when the app comes back.
+ private func interrupted(_ began: Bool) {
+ guard isRunning else { return }
+ if began {
+ guard !paused else { return }
+ paused = true
+ level = 0
+ status = L("已暂停,结束后接着听")
+ debugLog("room: interrupted")
+ return
+ }
+ guard paused else { return }
+ do {
+ try audio.resume()
+ paused = false
+ status = L("继续听")
+ debugLog("room: resumed")
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
+ if self?.status == L("继续听") { self?.status = "" }
+ }
+ } catch {
+ debugLog("room: resume failed: \(error)")
+ resumeWhenActive = true
+ }
+ onStateChange?()
+ }
+
+ private var resumeWhenActive = false
+
+ /// The app is in front again: a pause whose end came too early to take the microphone back.
+ func appBecameActive() {
+ guard resumeWhenActive, isRunning, paused else { return }
+ resumeWhenActive = false
+ interrupted(false)
+ }
+
+ /// 手机外放 with nothing loud enough after ten seconds: most likely headphones or a low volume.
+ private func watchSilence(_ id: String) {
+ Task { [weak self] in
+ try? await Task.sleep(nanoseconds: 10_000_000_000)
+ guard let self, self.isRunning, self.sessionID == id, !self.paused,
+ !self.heardVoice, self.lines.isEmpty, self.status.isEmpty else { return }
+ self.status = L("没听到声音,请拔掉耳机或调大音量")
+ }
+ }
+
+ /// Debug (`interrupt:began|ended`): what the system sends for a call or Siri.
+ func debugInterrupt(_ began: Bool) { audio.debugInterrupt(began) }
+
private func fail(_ message: String) {
status = message
isRunning = false
@@ -158,6 +223,8 @@ final class RoomListen: ObservableObject {
func stop() {
guard isRunning else { return }
isRunning = false
+ paused = false
+ resumeWhenActive = false
if !Self.silent { audio.stop() }
let stream = self.stream, reader = self.reader
self.stream = nil
@@ -268,7 +335,14 @@ final class RoomListen: ObservableObject {
/// the meeting's recording, a level and the last minute of 16 kHz audio for voiceprints.
final class RoomAudio: @unchecked Sendable {
var voices = true
+ /// 手机外放: other apps keep playing beside us (without it, starting stops their audio).
+ var mix = false
var onLevel: (@MainActor (Float) -> Void)?
+ /// true when a call, Siri or another app takes the audio, false when it gives it back.
+ var onInterruption: (@MainActor (Bool) -> Void)?
+ private var observers: [NSObjectProtocol] = []
+ /// Inside an interruption: a configuration change then must not take the microphone back.
+ private var held = false
/// A new engine for each meeting: one restarted after `stop` hears only silence in the simulator.
private var engine = AVAudioEngine()
@@ -290,7 +364,8 @@ final class RoomAudio: @unchecked Sendable {
func start(recognizer: RecognitionStream, recording: URL) throws {
let session = AVAudioSession.sharedInstance()
// .measurement: no voice processing, which would duck what the room says as "echo".
- try session.setCategory(.playAndRecord, mode: .measurement, options: [.defaultToSpeaker])
+ // .defaultToSpeaker sends every app's sound to the speaker, not the earpiece, while we record.
+ try session.setCategory(.playAndRecord, mode: .measurement, options: mix ? [.defaultToSpeaker, .mixWithOthers] : [.defaultToSpeaker])
try session.setActive(true)
engine = AVAudioEngine()
queue.sync {
@@ -300,9 +375,15 @@ final class RoomAudio: @unchecked Sendable {
ring = []
ringStart = 0
}
+ try tapAndStart()
+ observe(session)
+ }
+
+ private func tapAndStart() throws {
let input = engine.inputNode
+ input.removeTap(onBus: 0)
let format = input.outputFormat(forBus: 0)
- debugLog("room: input \(format) route=\(session.currentRoute.inputs.map(\.portName))")
+ debugLog("room: input \(format) route=\(AVAudioSession.sharedInstance().currentRoute.inputs.map(\.portName))")
input.installTap(onBus: 0, bufferSize: 4096, format: format) { [weak self] buffer, _ in
guard let self, let copy = buffer.copy() as? AVAudioPCMBuffer else { return }
self.queue.async { self.feed(copy) }
@@ -311,7 +392,42 @@ final class RoomAudio: @unchecked Sendable {
try engine.start()
}
+ /// The microphone again after an interruption, in whatever format the route now has.
+ func resume() throws {
+ held = false
+ try AVAudioSession.sharedInstance().setActive(true)
+ if !engine.isRunning { try tapAndStart() }
+ }
+
+ private func observe(_ session: AVAudioSession) {
+ let center = NotificationCenter.default
+ observers = [
+ center.addObserver(forName: AVAudioSession.interruptionNotification, object: session, queue: .main) { [weak self] n in
+ guard let raw = n.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
+ let type = AVAudioSession.InterruptionType(rawValue: raw) else { return }
+ let began = type == .began
+ self?.held = began
+ if began { self?.engine.pause() }
+ let cb = self?.onInterruption
+ MainActor.assumeIsolated { cb?(began) }
+ },
+ // A route change (headphones in or out) stops the engine: on again in the new format.
+ center.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in
+ guard let self, !self.held, !self.engine.isRunning else { return }
+ debugLog("room: engine configuration changed")
+ try? self.tapAndStart()
+ },
+ ]
+ }
+
+ func debugInterrupt(_ began: Bool) {
+ NotificationCenter.default.post(name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance(),
+ userInfo: [AVAudioSessionInterruptionTypeKey: (began ? AVAudioSession.InterruptionType.began : .ended).rawValue])
+ }
+
func stop() {
+ observers.forEach(NotificationCenter.default.removeObserver)
+ observers = []
engine.inputNode.removeTap(onBus: 0)
engine.stop()
queue.sync {