知了 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(ios): Listen to the phone's sound, such as an X Space, through a screen broadcast
wquguru7a1b9f93d5bb
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex e029cce..879486d 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -1658,3 +1658,26 @@/* iOS: playback */"播放进度" = "Playback position";"本场 %lld / %lld" = "This meeting %lld / %lld";++/* iOS: phone's sound */+"正在听手机里的声音…" = "Listening to the phone's sound…";+"手机里的声音" = "Phone's sound";+"手机里的声音 · %@" = "Phone's sound · %@";+"X Space、播客、视频 · 听不到你自己说的话" = "X Spaces, podcasts, videos · Not your own voice";+"别的 app 里的声音,选“手机里的声音”" = "For sound from other apps, pick Phone's sound";+"别的 app 在用麦克风" = "Another app is using the mic";+"可以改听手机放出来的声音,接着出字幕。" = "Listen to what the phone plays instead, and subtitles carry on.";+"比如 X Space、电话" = "Like an X Space or a call";+"改听手机里的声音" = "Listen to the phone's sound";+"等它结束再听" = "Wait until it's done";+"听不到你自己说的话" = "Your own voice isn't included";+"点“开始直播”后开始听" = "Tap Start Broadcast to begin";+"顶部亮红色就是在听" = "Red at the top means it's listening";+"打开直播" = "Open broadcast";+"没录到声音" = "No sound coming through";+"有些通话 app 不让别人录它的声音" = "Some call apps block recording their sound";+"换一台手机或电脑放在旁边,用“会议室”听。" = "Put another phone or computer nearby and listen with Room.";+"接着等" = "Keep waiting";+"听不到你自己说的话 · 顶部红色结束后消失" = "Your own voice isn't included · The red at the top goes when it ends";+"先在知了里点开始听" = "Start listening in Cicada first";+"知了已结束收听" = "Cicada stopped listening";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 17797a1..1bf7157 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -1658,3 +1658,26 @@/* iOS: playback */"播放进度" = "再生位置";"本场 %lld / %lld" = "この会議 %lld / %lld";++/* iOS: phone's sound */+"正在听手机里的声音…" = "スマホの音声を聞いています…";+"手机里的声音" = "スマホの音声";+"手机里的声音 · %@" = "スマホの音声 · %@";+"X Space、播客、视频 · 听不到你自己说的话" = "X スペース、ポッドキャスト、動画 · 自分の声は入りません";+"别的 app 里的声音,选“手机里的声音”" = "ほかのアプリの音声は「スマホの音声」で";+"别的 app 在用麦克风" = "ほかのアプリがマイクを使用中";+"可以改听手机放出来的声音,接着出字幕。" = "スマホから流れる音声に切り替えれば、字幕を続けられます。";+"比如 X Space、电话" = "X スペースや通話など";+"改听手机里的声音" = "スマホの音声に切り替える";+"等它结束再听" = "終わるまで待つ";+"听不到你自己说的话" = "自分の声は入りません";+"点“开始直播”后开始听" = "「ブロードキャストを開始」をタップすると始まります";+"顶部亮红色就是在听" = "画面上部が赤いあいだは聞いています";+"打开直播" = "ブロードキャストを開く";+"没录到声音" = "音声が入ってきません";+"有些通话 app 不让别人录它的声音" = "通話アプリには音声の録音を許さないものがあります";+"换一台手机或电脑放在旁边,用“会议室”听。" = "別のスマホやパソコンをそばに置いて「会議室」で聞いてください。";+"接着等" = "もう少し待つ";+"听不到你自己说的话 · 顶部红色结束后消失" = "自分の声は入りません · 上部の赤は終了すると消えます";+"先在知了里点开始听" = "先に Cicada で聞き取りを開始してください";+"知了已结束收听" = "Cicada の聞き取りが終わりました";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex 0b95e4a..79470d1 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -1658,3 +1658,26 @@/* iOS: playback */"播放进度" = "재생 위치";"本场 %lld / %lld" = "이 회의 %lld / %lld";++/* iOS: phone's sound */+"正在听手机里的声音…" = "휴대폰 소리를 듣는 중…";+"手机里的声音" = "휴대폰 소리";+"手机里的声音 · %@" = "휴대폰 소리 · %@";+"X Space、播客、视频 · 听不到你自己说的话" = "X 스페이스, 팟캐스트, 동영상 · 내 목소리는 안 들려요";+"别的 app 里的声音,选“手机里的声音”" = "다른 앱의 소리는 ‘휴대폰 소리’를 고르세요";+"别的 app 在用麦克风" = "다른 앱이 마이크를 쓰고 있어요";+"可以改听手机放出来的声音,接着出字幕。" = "휴대폰에서 나오는 소리로 바꿔 들으면 자막이 이어져요.";+"比如 X Space、电话" = "X 스페이스나 통화 등";+"改听手机里的声音" = "휴대폰 소리로 바꿔 듣기";+"等它结束再听" = "끝날 때까지 기다리기";+"听不到你自己说的话" = "내 목소리는 안 들려요";+"点“开始直播”后开始听" = "‘방송 시작’을 누르면 시작돼요";+"顶部亮红色就是在听" = "화면 위가 빨간색이면 듣는 중이에요";+"打开直播" = "방송 열기";+"没录到声音" = "소리가 들어오지 않아요";+"有些通话 app 不让别人录它的声音" = "일부 통화 앱은 소리 녹음을 막아요";+"换一台手机或电脑放在旁边,用“会议室”听。" = "다른 휴대폰이나 컴퓨터를 옆에 두고 ‘회의실’로 들어 보세요.";+"接着等" = "더 기다리기";+"听不到你自己说的话 · 顶部红色结束后消失" = "내 목소리는 안 들려요 · 위의 빨간색은 끝나면 사라져요";+"先在知了里点开始听" = "먼저 Cicada에서 듣기를 시작하세요";+"知了已结束收听" = "Cicada가 듣기를 마쳤어요";diff --git a/docs/ios-plan.md b/docs/ios-plan.mdindex 7f7bf38..231e351 100644--- a/docs/ios-plan.md+++ b/docs/ios-plan.md@@ -12,7 +12,9 @@ iPhone 和 iPad 拿不到其他 app 的声音,也不能往别的 app 的麦克- 会议记录:搜索、双语全文、纪要、原声回放、导出 Markdown / Word / SRT- 引导、设置、实时活动和灵动岛-第一版不做:听其他 app 的声音(ReplayKit 广播扩展,单独做原型再说)、往会议里送语音、会议软件挂断时自动结束(iOS 看不到别的 app 用不用麦克风,只靠 10 分钟没人说话结束)。+听其他 app 的声音(2026-11-28 加上):ReplayKit 广播扩展 `ios/Broadcast` 只把别的 app 的声音转成 16 kHz 单声道,经本机回环 TCP 交给 app,识别、翻译、纪要、记录都走 app 原来的流程,字幕浮在画中画小窗里。端口和一次性口令放在共用钥匙串(`$TEAM.<bundle>.cast`),不用 App Group。入口:被别的 app 抢了麦克风时弹卡片“改听手机里的声音”,声音来源菜单里也能选。实测 X Space 能听到;开了回声消除的通话 app 录屏是静音,15 秒没声音就提示换设备。听不到自己在 Space 里说的话。App Store 的 `.broadcast` App ID 已注册(要 Admin 权限的 key);构建默认带上扩展,`BROADCAST=0` 去掉。++第一版不做:往会议里送语音、会议软件挂断时自动结束(iOS 看不到别的 app 用不用麦克风,只靠 10 分钟没人说话结束)。## 关键决策diff --git a/ios/AGENTS.md b/ios/AGENTS.mdindex 22bca9e..13ba0fd 100644--- a/ios/AGENTS.md+++ b/ios/AGENTS.md@@ -1,10 +1,10 @@# AGENTS.md (iOS / iPadOS)-The iPhone and iPad app: listens to the room with the microphone, interprets face to face through the speaker, imports recordings and keeps meeting records. It cannot hear other apps or speak into them. The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). The plan is `docs/ios-plan.md`; the design canvas on claude.ai (知了 iOS 设计) is the source of truth for the UI.+The iPhone and iPad app: listens to the room with the microphone, interprets face to face through the speaker, imports recordings and keeps meeting records. It hears other apps only through a screen broadcast (`ios/Broadcast`: the extension pumps their sound over loopback into the app's own pipeline; apps with echo cancellation come through silent), and cannot speak into them. The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). The plan is `docs/ios-plan.md`; the design canvas on claude.ai (知了 iOS 设计) is the source of truth for the UI.- iOS / iPadOS 26 and later, SwiftUI. Engines are the Mac's own files, listed in `ios/shared-sources.txt` and compiled into the iOS app; `ios/Sources` has the iOS side. Change a shared file and keep both working: `ios/scripts/typecheck.sh`, then `scripts/test.sh` and a Mac dev build.- Built by `ios/scripts/build.sh` with `xcrun swiftc`, no `.xcodeproj`; `DEVICE=1` builds and signs for a device. Needs full Xcode, not only the Command Line Tools.-- Bundle id `com.indaloop.cicada` (dev `.dev`, extension `.live`); the Mac keeps `com.wquguru.cicada`. Signing (team Indaloop LLC) goes through the App Store Connect API: `ios/tools/provision.py`, then `ios/scripts/device.sh` or `ios/scripts/testflight.sh`. Keys and profiles live in `~/.cicada-signing`, never in the repo.+- Bundle id `com.indaloop.cicada` (dev `.dev`, extensions `.live` and `.broadcast`); the Mac keeps `com.wquguru.cicada`. Signing (team Indaloop LLC) goes through the App Store Connect API: `ios/tools/provision.py`, then `ios/scripts/device.sh` or `ios/scripts/testflight.sh`. Keys and profiles live in `~/.cicada-signing`, never in the repo.- The key: the `ling-api-key` file in the app container readable only after the first unlock (listening goes on while locked), excluded from backups; never UserDefaults, logs or exports.- UI text: the same Chinese keys and `Resources/*.lproj/Localizable.strings` as the Mac; reuse a Mac key where the feature is the same. `python3 scripts/strings.py` checks the iOS build too when Xcode is there.- Verify in the iPhone and iPad simulators: `ios/scripts/build.sh`, `ios/scripts/run.sh "<device>" [--seed <Mac meeting folders>]`, drive it with `ios/scripts/ctl.sh` (commands in `Debug.swift`), read `Library/Caches/livesubs-dev-debug.log` in the app container, `xcrun simctl io <device> screenshot` against the design; pass `-AppleLanguages "(zh-Hans)"` to `simctl launch` for Chinese. A real microphone, the lock screen, the Dynamic Island and TestFlight need a person.diff --git a/ios/Broadcast/Info.plist b/ios/Broadcast/Info.plistnew file mode 100644index 0000000..8b012a9--- /dev/null+++ b/ios/Broadcast/Info.plist@@ -0,0 +1,43 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>Cicada</string>+ <key>CFBundleExecutable</key>+ <string>CicadaBroadcast</string>+ <key>CFBundleIdentifier</key>+ <string>com.indaloop.cicada.broadcast</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleName</key>+ <string>CicadaBroadcast</string>+ <key>CFBundlePackageType</key>+ <string>XPC!</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0.0</string>+ <key>CFBundleSupportedPlatforms</key>+ <array>+ <string>iPhoneSimulator</string>+ </array>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>MinimumOSVersion</key>+ <string>26.0</string>+ <key>NSExtension</key>+ <dict>+ <key>NSExtensionPointIdentifier</key>+ <string>com.apple.broadcast-services-upload</string>+ <key>NSExtensionPrincipalClass</key>+ <string>SampleHandler</string>+ <key>RPBroadcastProcessMode</key>+ <string>RPBroadcastProcessModeSampleBuffer</string>+ </dict>+ <key>UIRequiredDeviceCapabilities</key>+ <array>+ <string>arm64</string>+ </array>+</dict>+</plist>diff --git a/ios/Broadcast/SampleHandler.swift b/ios/Broadcast/SampleHandler.swiftnew file mode 100644index 0000000..de1bf1f--- /dev/null+++ b/ios/Broadcast/SampleHandler.swift@@ -0,0 +1,147 @@+import AVFoundation+import CoreMedia+import Network+import ReplayKit++@objc(SampleHandler)+final class SampleHandler: RPBroadcastSampleHandler, @unchecked Sendable {+ private let queue = DispatchQueue(label: "com.indaloop.cicada.broadcast", qos: .userInitiated)+ private var connection: NWConnection?+ private var ready = false+ private var done = false+ private var converter: AVAudioConverter?+ private let target = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16_000, channels: 1, interleaved: true)!++ override func broadcastStarted(withSetupInfo setupInfo: [String: NSObject]?) {+ guard let (port, token) = Self.endpoint(), let p = NWEndpoint.Port(rawValue: port) else {+ queue.async { self.finish(Self.L("先在知了里点开始听")) }+ return+ }+ let params = NWParameters.tcp+ params.requiredInterfaceType = .loopback+ let c = NWConnection(host: "127.0.0.1", port: p, using: params)+ c.stateUpdateHandler = { [weak self, weak c] state in+ guard let self, let c else { return }+ switch state {+ case .ready:+ c.send(content: Data((token + "\n").utf8), completion: .idempotent)+ self.ready = true+ self.watch(c)+ case .waiting, .failed:+ self.finish(Self.L(self.ready ? "知了已结束收听" : "先在知了里点开始听"))+ default:+ break+ }+ }+ connection = c+ c.start(queue: queue)+ }++ override func broadcastFinished() {+ queue.sync {+ done = true+ connection?.cancel()+ connection = nil+ }+ }++ override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) {+ guard sampleBufferType == .audioApp, let mono = Self.mono(sampleBuffer) else { return }+ queue.async { [weak self] in self?.send(mono) }+ }++ private func watch(_ c: NWConnection) {+ c.receive(minimumIncompleteLength: 1, maximumLength: 64) { [weak self, weak c] _, _, complete, error in+ guard let self, let c else { return }+ if complete || error != nil { self.finish(Self.L("知了已结束收听")) } else { self.watch(c) }+ }+ }++ private func send(_ mono: AVAudioPCMBuffer) {+ guard ready, !done, let c = connection else { return }+ if converter?.inputFormat != mono.format { converter = AVAudioConverter(from: mono.format, to: target) }+ guard let converter else { return }+ let capacity = AVAudioFrameCount(Double(mono.frameLength) * target.sampleRate / mono.format.sampleRate) + 64+ guard let out = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: capacity) else { return }+ var given = false+ var error: NSError?+ converter.convert(to: out, error: &error) { _, status in+ if given { status.pointee = .noDataNow; return nil }+ given = true+ status.pointee = .haveData+ return mono+ }+ guard error == nil, out.frameLength > 0, let samples = out.int16ChannelData?[0] else { return }+ let bytes = Int(out.frameLength) * 2+ var frame = Data(capacity: bytes + 4)+ withUnsafeBytes(of: UInt32(bytes).littleEndian) { frame.append(contentsOf: $0) }+ frame.append(Data(bytes: samples, count: bytes))+ c.send(content: frame, completion: .idempotent)+ }++ private func finish(_ message: String) {+ guard !done else { return }+ done = true+ connection?.cancel()+ finishBroadcastWithError(NSError(domain: "Cicada", code: 1, userInfo: [NSLocalizedDescriptionKey: message]))+ }++ private static func L(_ key: String) -> String { Bundle.main.localizedString(forKey: key, value: key, table: nil) }++ private static func endpoint() -> (UInt16, String)? {+ guard let prefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as? String, !prefix.isEmpty,+ var app = Bundle.main.bundleIdentifier, app.hasSuffix(".broadcast") else { return nil }+ app.removeLast(".broadcast".count)+ let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "cast-link",+ kSecAttrAccount as String: "endpoint", kSecAttrAccessGroup as String: prefix + app + ".cast",+ kSecReturnData as String: true, kSecMatchLimit as String: kSecMatchLimitOne]+ var out: AnyObject?+ guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }+ let parts = String(decoding: data, as: UTF8.self).split(separator: " ")+ guard parts.count == 2, let port = UInt16(parts[0]) else { return nil }+ return (port, String(parts[1]))+ }++ private static func mono(_ sampleBuffer: CMSampleBuffer) -> AVAudioPCMBuffer? {+ guard let desc = CMSampleBufferGetFormatDescription(sampleBuffer),+ let asbd = CMAudioFormatDescriptionGetStreamBasicDescription(desc)?.pointee,+ asbd.mFormatID == kAudioFormatLinearPCM,+ let block = CMSampleBufferGetDataBuffer(sampleBuffer) else { return nil }+ let frames = CMSampleBufferGetNumSamples(sampleBuffer)+ let channels = Int(asbd.mChannelsPerFrame)+ let bytes = Int(asbd.mBitsPerChannel) / 8+ let isFloat = asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0+ let bigEndian = asbd.mFormatFlags & kAudioFormatFlagIsBigEndian != 0+ let interleaved = asbd.mFormatFlags & kAudioFormatFlagIsNonInterleaved == 0+ guard frames > 0, channels > 0, [2, 4].contains(bytes) else { return nil }+ let length = CMBlockBufferGetDataLength(block)+ guard length >= frames * channels * bytes else { return nil }+ var data = Data(count: length)+ let status = data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(block, atOffset: 0, dataLength: length, destination: $0.baseAddress!) }+ guard status == kCMBlockBufferNoErr,+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: asbd.mSampleRate, channels: 1, interleaved: false),+ let out = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)),+ let dst = out.floatChannelData?[0] else { return nil }+ data.withUnsafeBytes { raw in+ func sample(_ offset: Int) -> Float {+ if bytes == 2 {+ var v = raw.loadUnaligned(fromByteOffset: offset, as: UInt16.self)+ if bigEndian { v = v.byteSwapped }+ return Float(Int16(bitPattern: v)) / 32768+ }+ var v = raw.loadUnaligned(fromByteOffset: offset, as: UInt32.self)+ if bigEndian { v = v.byteSwapped }+ return isFloat ? Float(bitPattern: v) : Float(Int32(bitPattern: v)) / 2_147_483_648+ }+ for i in 0..<frames {+ var sum: Float = 0+ for c in 0..<channels {+ sum += sample(interleaved ? (i * channels + c) * bytes : (c * frames + i) * bytes)+ }+ dst[i] = sum / Float(channels)+ }+ }+ out.frameLength = AVAudioFrameCount(frames)+ return out+ }+}diff --git a/ios/Sources/Cicada/CastLink.swift b/ios/Sources/Cicada/CastLink.swiftnew file mode 100644index 0000000..517b9a2--- /dev/null+++ b/ios/Sources/Cicada/CastLink.swift@@ -0,0 +1,171 @@+import AVFoundation+import Network+import ReplayKit+import UIKit++final class CastLink: @unchecked Sendable {+ enum State: Equatable { case waiting, connected, ended }++ static var available: Bool {+ guard let dir = Bundle.main.builtInPlugInsURL else { return false }+ return FileManager.default.fileExists(atPath: dir.appendingPathComponent("CicadaBroadcast.appex").path)+ }+ static var extensionID: String { (Bundle.main.bundleIdentifier ?? "") + ".broadcast" }++ var onAudio: ((AVAudioPCMBuffer) -> Void)?+ var onState: (@MainActor (State) -> Void)?+ private let queue = DispatchQueue(label: "com.indaloop.cicada.cast", qos: .userInitiated)+ private var listener: NWListener?+ private var connection: NWConnection?+ private let token = UUID().uuidString+ private let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!++ func start() throws {+ let params = NWParameters.tcp+ params.requiredInterfaceType = .loopback+ let listener = try NWListener(using: params, on: .any)+ listener.stateUpdateHandler = { [weak self, weak listener] state in+ guard let self else { return }+ switch state {+ case .ready:+ guard let port = listener?.port?.rawValue else { return }+ CastEndpoint.store(port: port, token: self.token)+ debugLog("cast: waiting on port \(port)")+ case .failed(let error):+ debugLog("cast: listener failed \(error)")+ default: break+ }+ }+ listener.newConnectionHandler = { [weak self] c in self?.accept(c) }+ self.listener = listener+ listener.start(queue: queue)+ }++ func stop() {+ queue.sync {+ onAudio = nil+ connection?.cancel()+ connection = nil+ listener?.cancel()+ listener = nil+ }+ CastEndpoint.clear()+ }++ private func accept(_ c: NWConnection) {+ guard connection == nil else { c.cancel(); return }+ connection = c+ c.stateUpdateHandler = { [weak self, weak c] state in+ switch state {+ case .failed, .cancelled:+ guard let self, let c, self.connection === c else { return }+ self.lost()+ default: break+ }+ }+ c.start(queue: queue)+ let want = token.utf8.count + 1+ c.receive(minimumIncompleteLength: want, maximumLength: want) { [weak self, weak c] data, _, _, _ in+ guard let self, let c else { return }+ guard let data, String(decoding: data, as: UTF8.self) == self.token + "\n" else {+ debugLog("cast: wrong token, closed")+ c.cancel()+ if self.connection === c { self.connection = nil }+ return+ }+ debugLog("cast: broadcast connected")+ self.report(.connected)+ self.readFrame(c)+ }+ }++ private func readFrame(_ c: NWConnection) {+ c.receive(minimumIncompleteLength: 4, maximumLength: 4) { [weak self, weak c] head, _, done, error in+ guard let self, let c else { return }+ guard let head, head.count == 4, error == nil else { if done || error != nil { self.close(c) }; return }+ let count = Int(head.withUnsafeBytes { $0.loadUnaligned(as: UInt32.self) }.littleEndian)+ guard count > 0, count <= 1 << 20, count % 2 == 0 else { self.close(c); return }+ c.receive(minimumIncompleteLength: count, maximumLength: count) { [weak self, weak c] body, _, done, error in+ guard let self, let c else { return }+ guard let body, body.count == count, error == nil else { self.close(c); return }+ if let b = self.buffer(body) { self.onAudio?(b) }+ if done { self.close(c) } else { self.readFrame(c) }+ }+ }+ }++ private func buffer(_ data: Data) -> AVAudioPCMBuffer? {+ let n = data.count / 2+ guard let b = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(n)), let dst = b.floatChannelData?[0] else { return nil }+ data.withUnsafeBytes { raw in+ for i in 0..<n { dst[i] = Float(Int16(littleEndian: raw.loadUnaligned(fromByteOffset: i * 2, as: Int16.self))) / 32768 }+ }+ b.frameLength = AVAudioFrameCount(n)+ return b+ }++ private func close(_ c: NWConnection) {+ c.cancel()+ if connection === c { lost() }+ }++ private func lost() {+ connection = nil+ debugLog("cast: broadcast ended")+ report(.ended)+ }++ private func report(_ s: State) {+ let cb = onState+ DispatchQueue.main.async { MainActor.assumeIsolated { cb?(s) } }+ }+}++enum CastEndpoint {+ private static var group: String? {+ guard let prefix = Bundle.main.object(forInfoDictionaryKey: "AppIdentifierPrefix") as? String, !prefix.isEmpty,+ let id = Bundle.main.bundleIdentifier else { return nil }+ return prefix + id + ".cast"+ }++ private static var query: [String: Any] {+ var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "cast-link",+ kSecAttrAccount as String: "endpoint"]+ if let group { q[kSecAttrAccessGroup as String] = group }+ return q+ }++ static func store(port: UInt16, token: String) {+ SecItemDelete(query as CFDictionary)+ var add = query+ add[kSecValueData as String] = Data("\(port) \(token)".utf8)+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly+ let status = SecItemAdd(add as CFDictionary, nil)+ if status != errSecSuccess { debugLog("cast: keychain store failed \(status)") }+ #if targetEnvironment(simulator)+ debugLog("cast: simulator endpoint \(port) \(token)")+ #endif+ }++ static func clear() { SecItemDelete(query as CFDictionary) }+}++@MainActor+enum CastPicker {+ private static var picker: RPSystemBroadcastPickerView?++ static func show() {+ guard let window = UIApplication.shared.connectedScenes.compactMap({ ($0 as? UIWindowScene)?.keyWindow }).first else { return }+ picker?.removeFromSuperview()+ let p = RPSystemBroadcastPickerView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))+ p.preferredExtension = CastLink.extensionID+ p.showsMicrophoneButton = false+ p.alpha = 0.01+ p.isAccessibilityElement = false+ window.addSubview(p)+ picker = p+ let button = p.subviews.compactMap { $0 as? UIButton }.first+ debugLog("cast: picker \(button == nil ? "has no button" : "shown")")+ button?.sendActions(for: .touchUpInside)+ }+}diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swiftindex e6de8b3..ae76225 100644--- a/ios/Sources/Cicada/CicadaApp.swift+++ b/ios/Sources/Cicada/CicadaApp.swift@@ -40,6 +40,7 @@ enum Pref {static let silenceEnd = "silenceEnd"static let silenceMinutes = "silenceMinutes"static var speakerMode: Bool { UserDefaults.standard.string(forKey: hear) == "speaker" }+ static var castMode: Bool { UserDefaults.standard.string(forKey: hear) == "cast" && CastLink.available }static var sourceAuto: Bool { (UserDefaults.standard.string(forKey: source) ?? "auto") == "auto" }@@ -181,6 +182,7 @@ final class AppModel: ObservableObject {notes.finalDone = { [weak self] id in self?.folderExport.settled(id) }room.onEnded = { [weak self] id in self?.folderExport.ended(id) }room.profiles = profiles+ room.onWantsPicker = { CastPicker.show() }speakerProfiles = profiles.all()folderExport.retry()wireFixes()@@ -195,7 +197,7 @@ final class AppModel: ObservableObject {// MARK: 听会议室- func startListening() {+ func startListening(cast: Bool? = nil) {guard !room.isRunning else { return }selection = nilliveHidden = false@@ -204,19 +206,20 @@ final class AppModel: ObservableObject {livePage = ling.hasKey ? .notes : .subtitlesfixes.meetingStarted()room.start(source: Pref.sourceAuto ? "auto" : Pref.sourceLang.locale, target: Pref.target(for: Pref.sourceCode), voices: UserDefaults.standard.bool(forKey: Pref.voices),- speaker: Pref.speakerMode)+ speaker: Pref.speakerMode, cast: (cast ?? Pref.castMode) && CastLink.available)}private func showInPiP() {- guard room.isRunning, room.speakerMode else { return }+ guard room.isRunning, room.speakerMode || room.cast else { return }+ let waiting = room.cast ? L("正在听手机里的声音…") : L("正在听外放…")let last = room.lines.lastlet shown = last.flatMap { l in store.session(room.sessionID)?.lines.first { $0.id == l.id }?.shown } ?? last?.srcif 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("正在听外放…"))+ pip.show(src: room.draft, dst: room.draftTranslation, note: waiting)} else {- pip.show(src: shown ?? "", dst: last?.dst ?? "", note: shown == nil ? L("正在听外放…") : "")+ pip.show(src: shown ?? "", dst: last?.dst ?? "", note: shown == nil ? waiting : "")}}@@ -243,7 +246,7 @@ final class AppModel: ObservableObject {private func listeningChanged() {objectWillChange.send()liveActivity.setPaused(room.paused)- pip.setEnabled(room.isRunning && room.speakerMode)+ pip.setEnabled(room.isRunning && (room.speakerMode || room.cast))if room.isRunning, let start = room.startedAt {liveActivity.start(startedAt: start, pair: Pref.pairText(room.languagePair.source, room.languagePair.target))watchEnd()diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swiftindex df81e6c..3867990 100644--- a/ios/Sources/Cicada/Debug.swift+++ b/ios/Sources/Cicada/Debug.swift@@ -67,6 +67,10 @@ extension AppModel {playSample()case "sampleStop":stopSample()+ case "castPick":+ CastPicker.show()+ case "castSwitch":+ room.switchToCast()case "import":importFiles(arg.split(separator: "|").map {$0.hasPrefix("/") ? URL(fileURLWithPath: String($0)) : URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent(String($0))@@ -79,7 +83,7 @@ extension AppModel {case "importExpire":importer.cancelAll()case "hear":- UserDefaults.standard.set(arg == "speaker" ? "speaker" : "room", forKey: Pref.hear)+ UserDefaults.standard.set(["speaker", "cast"].contains(arg) ? arg : "room", forKey: Pref.hear)case "interrupt":room.debugInterrupt(arg != "ended")case "quickStart":@@ -366,7 +370,7 @@ extension AppModel {case "state":debugLog("memory \(DeviceLoad.line)")debugLog("room problem=\(room.problem.map { "\($0)" } ?? "-") downloading=\(room.downloading?.name ?? "-")")- 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("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) speaker=\(room.speakerMode) cast=\(room.cast) castState=\(room.castState.map { "\($0)" } ?? "-") micBusy=\(room.micBusy) castSilent=\(room.castSilent) 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.swiftindex dcee273..377862d 100644--- a/ios/Sources/Cicada/LiveViews.swift+++ b/ios/Sources/Cicada/LiveViews.swift@@ -22,7 +22,8 @@ struct HomeTitle: View {.foregroundStyle(room.paused ? Ink.secondary : Ink.accentText)}let pair = Pref.pairText(room.languagePair.source, room.languagePair.target)- Text(pair.isEmpty ? (room.speakerMode ? L("外放") : L("会议室"))+ Text(room.cast ? (pair.isEmpty ? L("手机里的声音") : L("手机里的声音 · \(pair)"))+ : pair.isEmpty ? (room.speakerMode ? L("外放") : L("会议室")): (room.speakerMode ? L("外放 · \(pair)") : L("会议室 · \(pair)"))).font(.system(size: titleSize - 4, weight: .bold)).foregroundStyle(Ink.ink).lineLimit(1).minimumScaleFactor(0.7)@@ -82,9 +83,12 @@ struct ListenBar: View {Picker(selection: $hear) {Text("会议室").tag("room")Text("手机外放").tag("speaker")+ if CastLink.available { Text("手机里的声音").tag("cast") }} label: { Text("声音来源") }.pickerStyle(.inline)- Text(hear == "speaker" ? L("别戴耳机,字幕会浮在小窗里") : L("听不到其他 app 的声音,线上会议请用电脑版"))+ Text(hear == "speaker" ? L("别戴耳机,字幕会浮在小窗里")+ : hear == "cast" && CastLink.available ? L("X Space、播客、视频 · 听不到你自己说的话")+ : CastLink.available ? L("别的 app 里的声音,选“手机里的声音”") : L("听不到其他 app 的声音,线上会议请用电脑版"))}Picker(selection: $source) {Text("自动识别").tag("auto")@@ -95,7 +99,7 @@ struct ListenBar: View {ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }} label: { Text("翻译成") }} label: {- Text(verbatim: (hear == "speaker" ? L("外放") + " · " : "") + "\(Pref.sourceName) → \(targetName(Pref.target(for: Pref.sourceCode)))")+ Text(verbatim: (hear == "speaker" ? L("外放") + " · " : hear == "cast" && CastLink.available ? L("手机里的声音") + " · " : "") + "\(Pref.sourceName) → \(targetName(Pref.target(for: Pref.sourceCode)))").font(.subheadline).foregroundStyle(Ink.secondary).lineLimit(1).minimumScaleFactor(0.75).frame(maxWidth: .infinity, alignment: .leading).frame(minHeight: 44)@@ -193,6 +197,7 @@ struct LivePhone: View {.buttonStyle(.plain).accessibilityLabel(Text("收起"))))ListenBar()+ CastCard()PillSwitch(selection: $model.livePage, options: [(.notes, notesTitle), (.subtitles, "字幕")])EndingStrip()ModelWaitCard()@@ -352,6 +357,7 @@ struct LivePad: View {VStack(spacing: 0) {EndingStrip().frame(maxWidth: 560).padding(.horizontal, 20).padding(.top, 18)ModelWaitCard().frame(maxWidth: 560).padding(.horizontal, 20).padding(.top, 18)+ CastCard().frame(maxWidth: 560).padding(.horizontal, 20).padding(.top, 12)TranslateDownCard().frame(maxWidth: 560).padding(.horizontal, 20).padding(.top, 18)NotesStatusLine().frame(maxWidth: 560).padding(.horizontal, 20).padding(.top, 18)if let id = room.sessionID {@@ -425,6 +431,7 @@ struct ModelWaitCard: View {}struct StartProblemCard: View {+ @EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListenvar body: some View {@@ -463,12 +470,14 @@ struct StartProblemCard: View {private func title(_ p: RoomListen.StartProblem) -> String {switch p {case .microphone: L("请在设置里允许知了使用麦克风")+ case .micBusy: L("别的 app 在用麦克风")case .model(let m): L("没能下载 \(m.lang.name) 语音模型")case .other(let message): message}}private func reason(_ p: RoomListen.StartProblem) -> String? {+ if p == .micBusy { return CastLink.available ? L("可以改听手机放出来的声音,接着出字幕。") : L("比如 X Space、电话") }guard case .model(let m) = p else { return nil }switch m.cause {case .offline: return L("网络连不上,连上后会自动继续")@@ -483,6 +492,7 @@ struct StartProblemCard: View {let settings = { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } }switch p {case .microphone: return (L("打开 iPhone 设置"), settings)+ case .micBusy where CastLink.available: return (L("改听手机里的声音"), { model.startListening(cast: true) })case .model(let m) where m.cause == .disk: return (L("打开 iPhone 设置"), settings)case .model(let m) where m.cause == .offline: return nildefault: return (L("再试一次"), { room.retry() })@@ -543,3 +553,77 @@ struct NotesStatusLine: View {}}}++struct CastCard: View {+ @EnvironmentObject var model: AppModel+ @EnvironmentObject var room: RoomListen++ var body: some View {+ Group {+ if room.isRunning, room.micBusy, !room.cast {+ card(icon: "mic.slash", title: L("别的 app 在用麦克风"), detail: L("比如 X Space、电话"),+ body: L("可以改听手机放出来的声音,接着出字幕。"),+ primary: (L("改听手机里的声音"), { room.switchToCast() }), secondary: (L("等它结束再听"), { room.dismissMicBusy() }),+ foot: L("听不到你自己说的话"), accent: true)+ } else if room.isRunning, room.cast, room.castState == .waiting {+ card(icon: "record.circle", title: L("点“开始直播”后开始听"), detail: L("顶部亮红色就是在听"), body: nil,+ primary: (L("打开直播"), { room.showPicker() }), secondary: nil, foot: nil, accent: true)+ } else if room.isRunning, room.cast, room.castSilent {+ card(icon: "speaker.slash", title: L("没录到声音"), detail: L("有些通话 app 不让别人录它的声音"),+ body: L("换一台手机或电脑放在旁边,用“会议室”听。"),+ primary: (L("结束"), { model.stopListening() }), secondary: (L("接着等"), { room.waitOutSilence() }),+ foot: nil, accent: false)+ } else if room.isRunning, room.cast, room.castState == .connected {+ HStack(spacing: 8) {+ Image(systemName: "info.circle").font(.footnote).foregroundStyle(Ink.secondary)+ Text("听不到你自己说的话 · 顶部红色结束后消失").font(.footnote).foregroundStyle(Ink.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ .padding(.horizontal, 4)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }+ .animation(.snappy(duration: 0.2), value: room.micBusy)+ .animation(.snappy(duration: 0.2), value: room.castState)+ .animation(.snappy(duration: 0.2), value: room.castSilent)+ }++ private func card(icon: String, title: String, detail: String, body: String?, primary: (String, () -> Void),+ secondary: (String, (() -> Void)?)?, foot: String?, accent: Bool) -> some View {+ VStack(alignment: .leading, spacing: 12) {+ HStack(spacing: 12) {+ Image(systemName: icon).font(.system(size: 19, weight: .semibold))+ .foregroundStyle(accent ? Ink.accentText : Ink.ink)+ .frame(width: 44, height: 44)+ .background(accent ? Ink.accentWash : Ink.ground, in: Circle())+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.headline).foregroundStyle(Ink.ink)+ Text(detail).font(.subheadline).foregroundStyle(Ink.secondary).fixedSize(horizontal: false, vertical: true)+ }+ Spacer(minLength: 0)+ }+ if let body { Text(body).font(.subheadline).foregroundStyle(Ink.ink).fixedSize(horizontal: false, vertical: true) }+ Button(action: primary.1) {+ Text(primary.0).font(.headline).foregroundStyle(.white)+ .frame(maxWidth: .infinity).frame(height: 50)+ .background(Ink.ink, in: Capsule())+ }+ .buttonStyle(.plain)+ if let secondary {+ Button { secondary.1?() } label: {+ Text(secondary.0).font(.subheadline.weight(.semibold)).foregroundStyle(Ink.ink)+ .frame(maxWidth: .infinity).frame(height: 44)+ .background(Ink.ground, in: Capsule())+ }+ .buttonStyle(.plain)+ }+ if let foot { Text(foot).font(.footnote).foregroundStyle(Ink.secondary) }+ }+ .padding(16)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.white, in: RoundedRectangle(cornerRadius: 20, style: .continuous))+ .overlay {+ RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(Ink.accent.opacity(accent ? 0.35 : 0), lineWidth: 1.5)+ }+ }+}diff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swiftindex e6c87d0..1d1ce5c 100644--- a/ios/Sources/Cicada/RoomListen.swift+++ b/ios/Sources/Cicada/RoomListen.swift@@ -22,17 +22,23 @@ final class RoomListen: ObservableObject {@Published private(set) var sessionID: String?@Published private(set) var speakerMode = false@Published private(set) var paused = false+ @Published private(set) var cast = false+ @Published private(set) var castState: CastLink.State?+ @Published private(set) var castSilent = false+ @Published private(set) var micBusy = falseprivate var userPaused = false+ var onWantsPicker: (() -> Void)?enum StartProblem: Equatable {case microphone+ case micBusycase model(ModelProblem)case other(String)}@Published private(set) var problem: StartProblem?@Published private(set) var downloading: (name: String, since: Date)?static var simulatedModelFailure: String?- private var lastStart: (source: String, target: String, voices: Bool, speaker: Bool)?+ private var lastStart: (source: String, target: String, voices: Bool, speaker: Bool, cast: Bool)?private let path = NWPathMonitor()private var online = true@@ -114,7 +120,7 @@ final class RoomListen: ObservableObject {func retry() {guard !isRunning, let s = lastStart else { return }debugLog("room: start again after \(String(describing: problem))")- start(source: s.source, target: s.target, voices: s.voices, speaker: s.speaker)+ start(source: s.source, target: s.target, voices: s.voices, speaker: s.speaker, cast: s.cast)}func dismissProblem() { problem = nil }@@ -128,11 +134,15 @@ 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, speaker: Bool = false) {+ func start(source: String, target: String, voices: Bool, speaker: Bool = false, cast: Bool = false) {guard !isRunning else { return }- lastStart = (source, target, voices, speaker)+ lastStart = (source, target, voices, speaker, cast)problem = nil- speakerMode = speaker+ speakerMode = speaker && !cast+ self.cast = cast+ castState = nil+ castSilent = false+ micBusy = falsepaused = falseuserPaused = falseauto = source == "auto"@@ -168,7 +178,8 @@ final class RoomListen: ObservableObject {onStateChange?()return}- guard await AVAudioApplication.requestRecordPermission() else {+ let allowed = cast ? true : await AVAudioApplication.requestRecordPermission()+ guard allowed else {problem = .microphonefail(L("请在设置里允许知了使用麦克风"))return@@ -195,15 +206,24 @@ final class RoomListen: ObservableObject {guard isRunning else { await stream.cancel(); return }self.stream = streamlet s = store.begin()- if !speakerMode { store.markLiveInRoom() }+ if !speakerMode && !cast { store.markLiveInRoom() }sessionID = s.idstartedAt = s.startedAtnotes.begin(s.id)audio.voices = voicesaudio.onInterruption = { [weak self] began in self?.interrupted(began) }+ audio.onCast = { [weak self] state in self?.castChanged(state) }let keep = UserDefaults.standard.bool(forKey: Pref.recordAudio)- try audio.start(recognizer: stream, recording: keep ? AudioFileWriter.partial(store.systemAudioURL(s.id)) : nil,- keep: !settled)+ do {+ try audio.start(recognizer: stream, recording: keep ? AudioFileWriter.partial(store.systemAudioURL(s.id)) : nil,+ keep: !settled, cast: cast)+ } catch where Self.micTaken(error) && !cast {+ debugLog("room: microphone taken by another app: \(error)")+ stop()+ problem = .micBusy+ status = L("别的 app 在用麦克风")+ return+ }heardVoice = falseaudio.onLevel = { [weak self] v inguard let self, !self.paused else { return }@@ -216,11 +236,12 @@ final class RoomListen: ObservableObject {}}read(stream)- status = ""+ status = cast ? L("点“开始直播”后开始听") : ""+ if cast { castState = .waiting; onWantsPicker?() }onMeeting?(true)if speakerMode { watchSilence(s.id) }if !settled { watchLanguage() }- debugLog("room: listening locale=\(lang.locale) target=\(target) speaker=\(speakerMode) format=\(stream.format) session=\(s.id)")+ debugLog("room: listening locale=\(lang.locale) target=\(target) speaker=\(speakerMode) cast=\(cast) format=\(stream.format) session=\(s.id)")onStateChange?()} catch let failure as ModelFailure {problem = .model(failure.problem)@@ -339,7 +360,8 @@ final class RoomListen: ObservableObject {}private func interrupted(_ began: Bool) {- guard isRunning else { return }+ guard isRunning, !cast else { return }+ micBusy = began && CastLink.availableif began {guard !paused else { return }paused = true@@ -408,6 +430,76 @@ final class RoomListen: ObservableObject {func debugInterrupt(_ began: Bool) { audio.debugInterrupt(began) }+ // MARK: 手机里的声音++ static func micTaken(_ error: Error) -> Bool {+ let code = (error as NSError).code+ return [AVAudioSession.ErrorCode.insufficientPriority.rawValue, AVAudioSession.ErrorCode.cannotStartRecording.rawValue,+ AVAudioSession.ErrorCode.isBusy.rawValue].contains(code)+ }++ func switchToCast() {+ guard isRunning, !cast, sessionID != nil else { return }+ do {+ try audio.switchToCast()+ } catch {+ debugLog("room: can't switch to the phone's sound: \(error)")+ status = L("没能开始听,再试一次")+ return+ }+ cast = true+ speakerMode = false+ micBusy = false+ paused = false+ userPaused = false+ resumeWhenActive = false+ castSilent = false+ castState = .waiting+ status = L("点“开始直播”后开始听")+ debugLog("room: switched to the phone's sound")+ onWantsPicker?()+ onStateChange?()+ }++ func showPicker() { onWantsPicker?() }++ func dismissMicBusy() { micBusy = false }++ func waitOutSilence() { castSilent = false; castWaited = true }++ private var castWaited = false++ private func castChanged(_ state: CastLink.State) {+ guard isRunning, cast else { return }+ castState = state+ switch state {+ case .connected:+ if status == L("点“开始直播”后开始听") { status = "" }+ castWaited = false+ watchCastSilence(sessionID)+ case .ended:+ debugLog("room: the broadcast stopped, ending")+ stop()+ case .waiting:+ break+ }+ onStateChange?()+ }++ private func watchCastSilence(_ id: String?) {+ Task { [weak self] in+ try? await Task.sleep(nanoseconds: 15_000_000_000)+ guard let self, self.isRunning, self.cast, self.sessionID == id, self.castState == .connected else { return }+ let heard = self.audio.castHeard+ debugLog("cast: after 15 s heard=\(heard)")+ if !heard && !self.castWaited && self.lines.isEmpty { self.castSilent = true }+ while !heard, self.isRunning, self.cast, self.sessionID == id {+ try? await Task.sleep(nanoseconds: 2_000_000_000)+ if self.audio.castHeard { self.castSilent = false; return }+ }+ }+ }+struct ModelFailure: Error { let problem: ModelProblem }private func fetch(_ lang: Lang) async throws {@@ -468,6 +560,9 @@ final class RoomListen: ObservableObject {isRunning = falsepaused = falseuserPaused = false+ micBusy = false+ castSilent = false+ castState = nilresumeWhenActive = falseif !Self.silent { audio.stop() }let stream = self.stream, reader = self.reader, recordTask = self.recordTask@@ -715,8 +810,13 @@ final class RoomAudio: @unchecked Sendable {var voices = truevar onLevel: (@MainActor (Float) -> Void)?var onInterruption: (@MainActor (Bool) -> Void)?+ var onCast: (@MainActor (CastLink.State) -> Void)?private var observers: [NSObjectProtocol] = []private var held = false+ private var link: CastLink?+ private var silence: AVAudioEngine?+ private var castHold = false+ private var castSound = falseprivate var engine = AVAudioEngine()private let queue = DispatchQueue(label: "com.indaloop.cicada.room", qos: .userInitiated)@@ -736,6 +836,8 @@ final class RoomAudio: @unchecked Sendable {private var keptFrames = 0var fedSeconds: Double { queue.sync { fed } }+ var casting: Bool { link != nil }+ var castHeard: Bool { queue.sync { castSound } }var keptSeconds: Double { queue.sync { Double(keptFrames) / 16_000 } }func keptClip(last seconds: Double) -> [AVAudioPCMBuffer] {@@ -774,11 +876,70 @@ final class RoomAudio: @unchecked Sendable {}}- func start(recognizer: RecognitionStream, recording: URL?, keep: Bool = false) throws {+ func start(recognizer: RecognitionStream, recording: URL?, keep: Bool = false, cast: Bool = false) throws {let session = AVAudioSession.sharedInstance()+ if cast {+ reset(recognizer: recognizer, recording: recording, keep: keep)+ try beginCast()+ observe(session)+ return+ }try session.setCategory(.playAndRecord, mode: .measurement, options: [.defaultToSpeaker, .mixWithOthers])try session.setActive(true)engine = AVAudioEngine()+ reset(recognizer: recognizer, recording: recording, keep: keep)+ try tapAndStart()+ observe(session)+ }++ func switchToCast() throws {+ guard link == nil else { return }+ engine.inputNode.removeTap(onBus: 0)+ engine.stop()+ held = false+ try beginCast()+ }++ private func beginCast() throws {+ queue.sync {+ castHold = false+ castSound = false+ toRecognizer = PCMConverter()+ }+ keepAwake()+ let link = CastLink()+ link.onAudio = { [weak self] b in+ guard let self else { return }+ self.queue.async {+ guard !self.castHold else { return }+ if !self.castSound, let p = b.floatChannelData?[0] {+ for i in 0..<Int(b.frameLength) where abs(p[i]) > 0.0001 { self.castSound = true; break }+ }+ self.feed(b)+ }+ }+ link.onState = onCast+ try link.start()+ self.link = link+ }++ private func keepAwake() {+ let session = AVAudioSession.sharedInstance()+ do {+ try session.setCategory(.playback, mode: .default, options: [.mixWithOthers])+ try session.setActive(true)+ let e = silence ?? AVAudioEngine()+ _ = e.mainMixerNode+ e.mainMixerNode.outputVolume = 0+ if !e.isRunning { try e.start() }+ silence = e+ debugLog("cast: keeping awake with a silent mixable output")+ } catch {+ debugLog("cast: keep awake failed: \(error)")+ }+ }++ private func reset(recognizer: RecognitionStream, recording: URL?, keep: Bool) {queue.sync {stream = recognizerrecordingURL = recording@@ -790,8 +951,6 @@ final class RoomAudio: @unchecked Sendable {kept = []keptFrames = 0}- try tapAndStart()- observe(session)}private func tapAndStart() throws {@@ -809,11 +968,13 @@ final class RoomAudio: @unchecked Sendable {func pause() {held = true+ if link != nil { queue.sync { castHold = true }; return }engine.pause()}func resume() throws {held = false+ if link != nil { queue.sync { castHold = false }; return }try AVAudioSession.sharedInstance().setActive(true)if !engine.isRunning { try tapAndStart() }}@@ -825,6 +986,11 @@ final class RoomAudio: @unchecked Sendable {guard let raw = n.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,let type = AVAudioSession.InterruptionType(rawValue: raw) else { return }let began = type == .began+ if let self, self.link != nil {+ debugLog("cast: own session interrupted=\(began)")+ if !began { self.keepAwake() }+ return+ }self?.held = beganif began { self?.engine.pause() }let cb = self?.onInterruption@@ -846,8 +1012,15 @@ final class RoomAudio: @unchecked Sendable {func stop() {observers.forEach(NotificationCenter.default.removeObserver)observers = []- engine.inputNode.removeTap(onBus: 0)- engine.stop()+ if let link {+ link.stop()+ self.link = nil+ silence?.stop()+ silence = nil+ } else {+ engine.inputNode.removeTap(onBus: 0)+ engine.stop()+ }queue.sync {stream = nilrecorder = nildiff --git a/ios/scripts/build.sh b/ios/scripts/build.shindex 7d9cd50..0f3760f 100755--- a/ios/scripts/build.sh+++ b/ios/scripts/build.sh@@ -80,10 +80,20 @@ intents_metadata CicadaLive "$APPEX" "$APPEX/CicadaLive" "${LIVE[@]}"cp ios/LiveActivity/Info.plist "$APPEX/Info.plist"cp "$APP/logo.png" "$APPEX/"for d in "$APP"/*.lproj; do cp -R "$d" "$APPEX/"; done+EXTS=("$APPEX")+if [[ "${BROADCAST:-1}" == 1 ]]; then+ CAST="$APP/PlugIns/CicadaBroadcast.appex"+ mkdir -p "$CAST"+ xcrun --sdk "$SDK" swiftc -O -swift-version 5 -parse-as-library -application-extension -module-name CicadaBroadcast \+ -target "$TARGET" -sdk "$SDKPATH" -Xlinker -e -Xlinker _NSExtensionMain ios/Broadcast/*.swift -o "$CAST/CicadaBroadcast"+ cp ios/Broadcast/Info.plist "$CAST/Info.plist"+ for d in "$APP"/*.lproj; do cp -R "$d" "$CAST/"; done+ EXTS+=("$CAST")+fiPLIST="$APP/Info.plist"BUILD=${BUILD_NUMBER:-$(git rev-list --count HEAD 2>/dev/null || echo 1)}-for p in "$PLIST" "$APPEX/Info.plist"; do+for p in "$PLIST" "${EXTS[@]/%//Info.plist}"; do/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $(tr -d '[:space:]' < VERSION)" \-c "Set :CFBundleVersion $BUILD" -c "Set :CFBundleSupportedPlatforms:0 $PLATFORM" "$p"done@@ -91,7 +101,7 @@ SDKVER=$(xcrun --sdk "$SDK" --show-sdk-version)SDKBUILD=$(xcrun --sdk "$SDK" --show-sdk-build-version)XCBUILD=$(xcodebuild -version | awk '/Build version/{print $3}')XCVER=$(xcodebuild -version | awk '/^Xcode/{split($2,v,"."); printf "%d%d%d0", v[1], v[2], v[3]}')-for p in "$PLIST" "$APPEX/Info.plist"; do+for p in "$PLIST" "${EXTS[@]/%//Info.plist}"; do/usr/libexec/PlistBuddy -c "Add :DTPlatformName string $SDK" -c "Add :DTPlatformVersion string $SDKVER" \-c "Add :DTPlatformBuild string $SDKBUILD" -c "Add :DTSDKName string $SDK$SDKVER" -c "Add :DTSDKBuild string $SDKBUILD" \-c "Add :DTXcode string $XCVER" -c "Add :DTXcodeBuild string $XCBUILD" \@@ -107,9 +117,10 @@ if [[ "${RELEASE:-}" != 1 ]]; then-c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string cicada-dev" \"$PLIST"/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.indaloop.cicada.dev.live" "$APPEX/Info.plist"+ [[ -n "${CAST:-}" ]] && /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.indaloop.cicada.dev.broadcast" "$CAST/Info.plist"fiif [[ "${DEVICE:-}" != 1 ]]; then- codesign --force --sign - "$APPEX" 2>/dev/null+ for e in "${EXTS[@]}"; do codesign --force --sign - "$e" 2>/dev/null; donecodesign --force --sign - "$APP" 2>/dev/nullelse: "${SIGN_IDENTITY:?DEVICE=1 needs SIGN_IDENTITY (and PROFILE, PROFILE_LIVE): see ios/scripts/provision.sh}"@@ -117,10 +128,19 @@ elsecp "$2" "$1/embedded.mobileprovision"security cms -D -i "$2" > "$WORK/profile.plist"/usr/libexec/PlistBuddy -x -c "Print :Entitlements" "$WORK/profile.plist" > "$WORK/entitlements.plist"+ if [[ -n "${CAST:-}" && $# -gt 2 ]]; then+ local team; team=$(/usr/libexec/PlistBuddy -c "Print :com.apple.developer.team-identifier" "$WORK/entitlements.plist")+ local groups="" i=0; for g in "${@:3}"; do groups+=" -c 'Add :keychain-access-groups:$i string $team.$g'"; i=$((i + 1)); done+ eval /usr/libexec/PlistBuddy -c "'Delete :keychain-access-groups'" -c "'Add :keychain-access-groups array'" $groups '"$WORK/entitlements.plist"' >/dev/null+ ficodesign --force --sign "$SIGN_IDENTITY" --entitlements "$WORK/entitlements.plist" --generate-entitlement-der "$1"}+ TEAM=$(security cms -D -i "${PROFILE:?}" | plutil -extract TeamIdentifier.0 raw -)+ [[ -n "${CAST:-}" ]] && for p in "$PLIST" "$CAST/Info.plist"; do /usr/libexec/PlistBuddy -c "Add :AppIdentifierPrefix string $TEAM." "$p"; donesign "$APPEX" "${PROFILE_LIVE:?}"- sign "$APP" "${PROFILE:?}"+ BUNDLE=$(/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$PLIST")+ [[ -n "${CAST:-}" ]] && sign "$CAST" "${PROFILE_BROADCAST:?BROADCAST=1 needs PROFILE_BROADCAST: rerun ios/tools/provision.py}" "$BUNDLE.cast"+ sign "$APP" "${PROFILE:?}" "$BUNDLE" "$BUNDLE.cast"codesign --verify --deep --strict "$APP"fiecho "Built $APP ($(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$PLIST") $(tr -d '[:space:]' < VERSION) ($BUILD))"diff --git a/ios/tools/provision.py b/ios/tools/provision.pyindex ffdc53b..bef69dd 100755--- a/ios/tools/provision.py+++ b/ios/tools/provision.py@@ -7,7 +7,8 @@ HOME = os.path.expanduser("~/.cicada-signing")KIND = sys.argv[1] if len(sys.argv) > 1 else "development"DEV = KIND == "development"APP_ID = "com.indaloop.cicada.dev" if DEV else "com.indaloop.cicada"-IDS = {APP_ID: "Cicada Dev" if DEV else "Cicada", APP_ID + ".live": "Cicada Dev Live" if DEV else "Cicada Live"}+IDS = {APP_ID: "Cicada Dev" if DEV else "Cicada", APP_ID + ".live": "Cicada Dev Live" if DEV else "Cicada Live",+ APP_ID + ".broadcast": "Cicada Dev Broadcast" if DEV else "Cicada Broadcast"}CERT_TYPE = "DEVELOPMENT" if DEV else "DISTRIBUTION"PROFILE_TYPE = "IOS_APP_DEVELOPMENT" if DEV else "IOS_APP_STORE"@@ -120,3 +121,4 @@ paths = {i: profile(i, b, cert, device_ids) for i, b in bundles.items()}print(f"export SIGN_IDENTITY={fingerprint}")print(f"export PROFILE='{paths[APP_ID]}'")print(f"export PROFILE_LIVE='{paths[APP_ID + '.live']}'")+print(f"export PROFILE_BROADCAST='{paths[APP_ID + '.broadcast']}'")diff --git a/scripts/strings.py b/scripts/strings.pyindex 7ffc246..a77f133 100755--- a/scripts/strings.py+++ b/scripts/strings.py@@ -34,7 +34,7 @@ def code_keys():PORTS = {"Windows": ["windows/src/**/*.cs"], "Android": ["android/app/src/**/*.kt", "android/core/src/**/*.kt"],- "Linux": ["linux/cicada/**/*.py"]}+ "Linux": ["linux/cicada/**/*.py"], "iOS broadcast": ["ios/Broadcast/*.swift"]}PORT_CALL = re.compile(r'\bLF?\("((?:[^"\\]|\\.)*)"')