@mentra/bluetooth-sdk 3.4.0-dev.1169 → 3.4.0-dev.1170
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/android/build.gradle +6 -36
- package/android/settings.gradle +1 -4
- package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +61 -3
- package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +89 -104
- package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +5 -5
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
- package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
- package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
- package/build/BluetoothSdk.types.d.ts +49 -0
- package/build/BluetoothSdk.types.d.ts.map +1 -1
- package/build/BluetoothSdk.types.js.map +1 -1
- package/build/_private/BluetoothSdkModule.d.ts +31 -4
- package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
- package/build/_private/BluetoothSdkModule.js.map +1 -1
- package/build/generated/releaseMetadata.js +5 -5
- package/build/generated/releaseMetadata.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +5 -0
- package/build/index.js.map +1 -1
- package/ios/BluetoothSdkModule.swift +58 -8
- package/ios/MentraBluetoothSDK.podspec +4 -0
- package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
- package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
- package/ios/Source/BluetoothSdkDefaults.swift +1 -1
- package/ios/Source/DeviceManager.swift +30 -12
- package/ios/Source/GeneratedReleaseMetadata.swift +5 -5
- package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
- package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
- package/ios/Source/audio/SpeechActivity.swift +277 -0
- package/ios/Source/stt/STTTools.swift +13 -31
- package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
- package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
- package/ios/Source/stt/WakeWordDetector.swift +145 -0
- package/ios/Source/utils/BoundedWait.swift +44 -0
- package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
- package/ios/Source/utils/SttModelTraits.swift +62 -0
- package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
- package/ios/Tests/PcmStreamTests.swift +299 -0
- package/ios/Tests/SpeechActivityTests.swift +238 -0
- package/ios/Tests/SttModelTraitsTests.swift +62 -0
- package/package.json +2 -2
- package/plugin/build/withAndroid.js +7 -11
- package/src/BluetoothSdk.types.ts +49 -0
- package/src/_private/BluetoothSdkModule.ts +33 -4
- package/src/generated/releaseMetadata.ts +5 -5
- package/src/index.ts +7 -0
- package/android/silero/LICENSE.md +0 -17
- package/android/silero/build.gradle +0 -50
- package/android/silero/proguard-rules.pro +0 -24
- package/android/silero/src/androidTest/assets/hello.wav +0 -0
- package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
- package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
- package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
- package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
- package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
- package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
- package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
- /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
- /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
|
@@ -2,9 +2,11 @@ import AVFoundation
|
|
|
2
2
|
import Foundation
|
|
3
3
|
import os
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
enum PcmStreamError: LocalizedError, Equatable {
|
|
6
6
|
case invalidArgument(String)
|
|
7
7
|
case closed
|
|
8
|
+
case notOpen(String)
|
|
9
|
+
case aborted
|
|
8
10
|
case native(String)
|
|
9
11
|
|
|
10
12
|
var errorDescription: String? {
|
|
@@ -13,10 +15,67 @@ private enum PcmStreamError: LocalizedError {
|
|
|
13
15
|
return message
|
|
14
16
|
case .closed:
|
|
15
17
|
return "PCM stream is closed"
|
|
18
|
+
case let .notOpen(streamId):
|
|
19
|
+
return "pcm stream \(streamId) is not open"
|
|
20
|
+
case .aborted:
|
|
21
|
+
return "aborted"
|
|
16
22
|
}
|
|
17
23
|
}
|
|
18
24
|
}
|
|
19
25
|
|
|
26
|
+
/// When a stream starts playing: once `jitterMs` of audio is queued, or when it is closed with
|
|
27
|
+
/// less than that, so a sound shorter than the cushion still plays. Same range as Android.
|
|
28
|
+
struct PcmJitterGate: Equatable {
|
|
29
|
+
static let defaultJitterMs = 500
|
|
30
|
+
static let minimumJitterMs = 80
|
|
31
|
+
|
|
32
|
+
let jitterMs: Int
|
|
33
|
+
let startFrames: Int64
|
|
34
|
+
|
|
35
|
+
init(jitterMs requested: Int?, sampleRate: Int) {
|
|
36
|
+
let jitterMs = min(max(requested ?? Self.defaultJitterMs, Self.minimumJitterMs), Self.defaultJitterMs)
|
|
37
|
+
self.jitterMs = jitterMs
|
|
38
|
+
startFrames = max(1, Int64(sampleRate) * Int64(jitterMs) / 1000)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
func shouldStart(queuedFrames: Int64, closing: Bool) -> Bool {
|
|
42
|
+
guard queuedFrames > 0 else { return false }
|
|
43
|
+
return closing || queuedFrames >= startFrames
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// Holds back an odd trailing byte so every chunk handed on is whole 16-bit samples.
|
|
48
|
+
struct PcmByteCarry {
|
|
49
|
+
private var pending: UInt8?
|
|
50
|
+
|
|
51
|
+
var hasPendingByte: Bool {
|
|
52
|
+
pending != nil
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
mutating func align(_ chunk: Data) -> Data {
|
|
56
|
+
var bytes = Data()
|
|
57
|
+
bytes.reserveCapacity(chunk.count + 1)
|
|
58
|
+
if let pending {
|
|
59
|
+
bytes.append(pending)
|
|
60
|
+
self.pending = nil
|
|
61
|
+
}
|
|
62
|
+
bytes.append(chunk)
|
|
63
|
+
if !bytes.count.isMultiple(of: 2) {
|
|
64
|
+
pending = bytes.removeLast()
|
|
65
|
+
}
|
|
66
|
+
return bytes
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Destination for PCM fetched by `PcmUrlLoader`.
|
|
71
|
+
protocol PcmStreamSink: AnyObject {
|
|
72
|
+
/// Queue whole s16le samples; suspends while the backlog is above the backpressure ceiling.
|
|
73
|
+
func write(data: Data) async throws -> Int64
|
|
74
|
+
/// Play out what is queued, then end. Returns the played duration in ms.
|
|
75
|
+
func close() async throws -> Int64
|
|
76
|
+
func abort() async
|
|
77
|
+
}
|
|
78
|
+
|
|
20
79
|
/// Low-latency, bounded live PCM playback for `speaker.createStream()`.
|
|
21
80
|
///
|
|
22
81
|
/// Input is signed 16-bit little-endian mono PCM. Chunks are converted to the
|
|
@@ -25,30 +84,45 @@ private enum PcmStreamError: LocalizedError {
|
|
|
25
84
|
/// serial state queue keeps writes, completion callbacks, interruption
|
|
26
85
|
/// recovery, close, and abort deterministic without blocking Expo's module
|
|
27
86
|
/// queue.
|
|
28
|
-
|
|
87
|
+
///
|
|
88
|
+
/// Nothing starts until `jitterMs` of audio is queued or the stream is closed,
|
|
89
|
+
/// so a prewarmed stream holds no output route. A stream that hasn't received
|
|
90
|
+
/// audio when the audio output changes or the session is interrupted is
|
|
91
|
+
/// abandoned: it may point at a stale output, and its next write fails with
|
|
92
|
+
/// "not open" so the caller reopens on the current route.
|
|
93
|
+
final class PcmStreamPlayer: PcmStreamSink, @unchecked Sendable {
|
|
29
94
|
private let logger = Logger(subsystem: "com.mentra.pcm-stream", category: "playback")
|
|
30
95
|
private static let backpressureCeilingMs: Int64 = 2000
|
|
31
96
|
private static let maximumBacklogMs: Int64 = 10000
|
|
32
97
|
|
|
33
98
|
private let streamId: String
|
|
34
99
|
private let sampleRate: Int
|
|
100
|
+
private let gate: PcmJitterGate
|
|
35
101
|
private let stateQueue: DispatchQueue
|
|
36
102
|
private let engine = AVAudioEngine()
|
|
37
103
|
private let player = AVAudioPlayerNode()
|
|
38
104
|
private let format: AVAudioFormat
|
|
39
105
|
|
|
106
|
+
/// Called once, on the state queue, when the stream abandons itself after a route change or
|
|
107
|
+
/// interruption before any audio arrived. State queue only.
|
|
108
|
+
private var onAbandoned: (() -> Void)?
|
|
109
|
+
|
|
40
110
|
private var queuedFrames: Int64 = 0
|
|
41
111
|
private var playedFrames: Int64 = 0
|
|
42
112
|
private var writtenFrames: Int64 = 0
|
|
113
|
+
private var playbackStarted = false
|
|
114
|
+
/// Buffers written before playback starts; scheduled together when it does.
|
|
115
|
+
private var heldBuffers: [(buffer: AVAudioPCMBuffer, frames: Int)] = []
|
|
43
116
|
private var closing = false
|
|
44
117
|
private var aborted = false
|
|
118
|
+
private var abandoned = false
|
|
45
119
|
private var finished = false
|
|
46
120
|
private var terminalError: Error?
|
|
47
121
|
private var writeWaiters: [CheckedContinuation<Int64, Error>] = []
|
|
48
122
|
private var closeWaiters: [CheckedContinuation<Int64, Error>] = []
|
|
49
123
|
private var observers: [NSObjectProtocol] = []
|
|
50
124
|
|
|
51
|
-
init(streamId: String, sampleRate: Int, channels: Int, volume: Float) throws {
|
|
125
|
+
init(streamId: String, sampleRate: Int, channels: Int, volume: Float, jitterMs: Int? = nil) throws {
|
|
52
126
|
guard !streamId.isEmpty else {
|
|
53
127
|
throw PcmStreamError.invalidArgument("streamId is required")
|
|
54
128
|
}
|
|
@@ -70,14 +144,14 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
70
144
|
self.streamId = streamId
|
|
71
145
|
self.sampleRate = sampleRate
|
|
72
146
|
self.format = format
|
|
147
|
+
gate = PcmJitterGate(jitterMs: jitterMs, sampleRate: sampleRate)
|
|
73
148
|
stateQueue = DispatchQueue(label: "com.mentra.pcm-stream.\(streamId)")
|
|
74
149
|
|
|
75
150
|
engine.attach(player)
|
|
76
151
|
engine.connect(player, to: engine.mainMixerNode, format: format)
|
|
77
152
|
player.volume = min(max(volume, 0), 1)
|
|
78
153
|
engine.prepare()
|
|
79
|
-
|
|
80
|
-
player.play()
|
|
154
|
+
// An empty prewarmed stream must not start playback or microphone gating.
|
|
81
155
|
installAudioSessionObservers()
|
|
82
156
|
}
|
|
83
157
|
|
|
@@ -85,10 +159,22 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
85
159
|
observers.forEach(NotificationCenter.default.removeObserver)
|
|
86
160
|
}
|
|
87
161
|
|
|
162
|
+
/// Set the handler `onAbandoned` calls. Must not be called from the state queue.
|
|
163
|
+
func setAbandonHandler(_ handler: @escaping () -> Void) {
|
|
164
|
+
stateQueue.sync { onAbandoned = handler }
|
|
165
|
+
}
|
|
166
|
+
|
|
88
167
|
func write(base64: String) async throws -> Int64 {
|
|
89
168
|
guard let data = Data(base64Encoded: base64), !data.isEmpty else {
|
|
90
169
|
throw PcmStreamError.invalidArgument("PCM chunk is empty or invalid base64")
|
|
91
170
|
}
|
|
171
|
+
return try await write(data: data)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
func write(data: Data) async throws -> Int64 {
|
|
175
|
+
guard !data.isEmpty else {
|
|
176
|
+
throw PcmStreamError.invalidArgument("PCM chunk is empty")
|
|
177
|
+
}
|
|
92
178
|
guard data.count.isMultiple(of: 2) else {
|
|
93
179
|
throw PcmStreamError.invalidArgument(
|
|
94
180
|
"PCM chunk length \(data.count) is not aligned to a 2-byte frame"
|
|
@@ -98,6 +184,7 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
98
184
|
return try await withCheckedThrowingContinuation { continuation in
|
|
99
185
|
stateQueue.async { [self] in
|
|
100
186
|
do {
|
|
187
|
+
if abandoned { throw PcmStreamError.notOpen(streamId) }
|
|
101
188
|
if let terminalError { throw terminalError }
|
|
102
189
|
guard !closing && !aborted else { throw PcmStreamError.closed }
|
|
103
190
|
|
|
@@ -111,19 +198,17 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
111
198
|
|
|
112
199
|
let buffer = try makeBuffer(data: data, frameCount: frameCount)
|
|
113
200
|
if writtenFrames == 0 {
|
|
114
|
-
logger.info("PCM_PLAYBACK first_write frames=\(frameCount) sampleRate=\(self.sampleRate)
|
|
201
|
+
logger.info("PCM_PLAYBACK first_write frames=\(frameCount) sampleRate=\(self.sampleRate) jitterMs=\(self.gate.jitterMs)")
|
|
115
202
|
}
|
|
116
203
|
writtenFrames += Int64(frameCount)
|
|
117
204
|
queuedFrames += Int64(frameCount)
|
|
118
|
-
|
|
119
|
-
buffer,
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
205
|
+
if playbackStarted {
|
|
206
|
+
schedule(buffer, frames: frameCount)
|
|
207
|
+
resumePlaybackIfNeeded()
|
|
208
|
+
} else {
|
|
209
|
+
heldBuffers.append((buffer, frameCount))
|
|
210
|
+
startPlaybackIfReady()
|
|
125
211
|
}
|
|
126
|
-
resumePlaybackIfNeeded()
|
|
127
212
|
if let terminalError { throw terminalError }
|
|
128
213
|
|
|
129
214
|
let current = bufferedMs(frames: queuedFrames)
|
|
@@ -155,6 +240,8 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
155
240
|
finishClose(extra: continuation)
|
|
156
241
|
} else {
|
|
157
242
|
closeWaiters.append(continuation)
|
|
243
|
+
// Audio shorter than the jitter cushion starts now.
|
|
244
|
+
startPlaybackIfReady()
|
|
158
245
|
}
|
|
159
246
|
}
|
|
160
247
|
}
|
|
@@ -163,25 +250,42 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
163
250
|
func abort() async {
|
|
164
251
|
await withCheckedContinuation { continuation in
|
|
165
252
|
stateQueue.async { [self] in
|
|
166
|
-
|
|
167
|
-
logger.info("PCM_PLAYBACK abort writtenFrames=\(self.writtenFrames) playedFrames=\(self.playedFrames) queuedFrames=\(self.queuedFrames)")
|
|
168
|
-
aborted = true
|
|
169
|
-
finished = true
|
|
170
|
-
player.stop()
|
|
171
|
-
engine.stop()
|
|
172
|
-
queuedFrames = 0
|
|
173
|
-
let error = PcmStreamError.closed
|
|
174
|
-
writeWaiters.forEach { $0.resume(throwing: error) }
|
|
175
|
-
writeWaiters.removeAll()
|
|
176
|
-
closeWaiters.forEach { $0.resume(returning: durationMs) }
|
|
177
|
-
closeWaiters.removeAll()
|
|
178
|
-
removeAudioSessionObservers()
|
|
179
|
-
}
|
|
253
|
+
abortOnStateQueue()
|
|
180
254
|
continuation.resume()
|
|
181
255
|
}
|
|
182
256
|
}
|
|
183
257
|
}
|
|
184
258
|
|
|
259
|
+
private func abortOnStateQueue() {
|
|
260
|
+
guard !aborted else { return }
|
|
261
|
+
logger.info("PCM_PLAYBACK abort writtenFrames=\(self.writtenFrames) playedFrames=\(self.playedFrames) queuedFrames=\(self.queuedFrames)")
|
|
262
|
+
aborted = true
|
|
263
|
+
finished = true
|
|
264
|
+
player.stop()
|
|
265
|
+
engine.stop()
|
|
266
|
+
heldBuffers.removeAll()
|
|
267
|
+
queuedFrames = 0
|
|
268
|
+
let error: PcmStreamError = abandoned ? .notOpen(streamId) : .closed
|
|
269
|
+
writeWaiters.forEach { $0.resume(throwing: error) }
|
|
270
|
+
writeWaiters.removeAll()
|
|
271
|
+
closeWaiters.forEach { $0.resume(returning: durationMs) }
|
|
272
|
+
closeWaiters.removeAll()
|
|
273
|
+
removeAudioSessionObservers()
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/// A stream that never received audio must not survive a route change: it would play on
|
|
277
|
+
/// the old route. Returns true when the stream was abandoned.
|
|
278
|
+
private func abandonIfUnwritten(reason: String) -> Bool {
|
|
279
|
+
guard writtenFrames == 0, !aborted, !finished else { return false }
|
|
280
|
+
logger.info("PCM_PLAYBACK abandon_unwritten reason=\(reason)")
|
|
281
|
+
abandoned = true
|
|
282
|
+
abortOnStateQueue()
|
|
283
|
+
let callback = onAbandoned
|
|
284
|
+
onAbandoned = nil
|
|
285
|
+
callback?()
|
|
286
|
+
return true
|
|
287
|
+
}
|
|
288
|
+
|
|
185
289
|
private var durationMs: Int64 {
|
|
186
290
|
bufferedMs(frames: playedFrames)
|
|
187
291
|
}
|
|
@@ -198,15 +302,50 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
198
302
|
throw PcmStreamError.native("failed to allocate PCM audio buffer")
|
|
199
303
|
}
|
|
200
304
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
305
|
+
data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
|
|
306
|
+
for index in 0 ..< frameCount {
|
|
307
|
+
let bits = UInt16(bytes[index * 2]) | (UInt16(bytes[index * 2 + 1]) << 8)
|
|
308
|
+
channel[index] = Float(Int16(bitPattern: bits)) / 32768.0
|
|
309
|
+
}
|
|
205
310
|
}
|
|
206
311
|
buffer.frameLength = AVAudioFrameCount(frameCount)
|
|
207
312
|
return buffer
|
|
208
313
|
}
|
|
209
314
|
|
|
315
|
+
private func schedule(_ buffer: AVAudioPCMBuffer, frames frameCount: Int) {
|
|
316
|
+
player.scheduleBuffer(
|
|
317
|
+
buffer,
|
|
318
|
+
completionCallbackType: .dataPlayedBack
|
|
319
|
+
) { [weak self] _ in
|
|
320
|
+
self?.stateQueue.async {
|
|
321
|
+
self?.didPlay(frameCount: frameCount)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// Start once the jitter cushion is queued, or on close with whatever is queued.
|
|
327
|
+
private func startPlaybackIfReady() {
|
|
328
|
+
guard !playbackStarted, !finished, terminalError == nil,
|
|
329
|
+
gate.shouldStart(queuedFrames: queuedFrames, closing: closing)
|
|
330
|
+
else { return }
|
|
331
|
+
do {
|
|
332
|
+
if !engine.isRunning {
|
|
333
|
+
try engine.start()
|
|
334
|
+
}
|
|
335
|
+
} catch {
|
|
336
|
+
fail(PcmStreamError.native("PCM playback start failed: \(error.localizedDescription)"))
|
|
337
|
+
return
|
|
338
|
+
}
|
|
339
|
+
playbackStarted = true
|
|
340
|
+
logger.info("PCM_PLAYBACK start queuedMs=\(self.bufferedMs(frames: self.queuedFrames)) closing=\(self.closing)")
|
|
341
|
+
let held = heldBuffers
|
|
342
|
+
heldBuffers.removeAll()
|
|
343
|
+
for entry in held {
|
|
344
|
+
schedule(entry.buffer, frames: entry.frames)
|
|
345
|
+
}
|
|
346
|
+
player.play()
|
|
347
|
+
}
|
|
348
|
+
|
|
210
349
|
private func didPlay(frameCount: Int) {
|
|
211
350
|
guard !aborted, terminalError == nil else { return }
|
|
212
351
|
if playedFrames == 0 {
|
|
@@ -243,8 +382,10 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
243
382
|
extra?.resume(returning: result)
|
|
244
383
|
}
|
|
245
384
|
|
|
385
|
+
/// Restart output that already started, e.g. after an interruption or route change.
|
|
386
|
+
/// Never starts a stream that hasn't started; the jitter gate does that.
|
|
246
387
|
private func resumePlaybackIfNeeded() {
|
|
247
|
-
guard !finished, terminalError == nil else { return }
|
|
388
|
+
guard playbackStarted, !finished, terminalError == nil else { return }
|
|
248
389
|
do {
|
|
249
390
|
if !engine.isRunning {
|
|
250
391
|
try engine.start()
|
|
@@ -263,6 +404,7 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
263
404
|
finished = true
|
|
264
405
|
player.stop()
|
|
265
406
|
engine.stop()
|
|
407
|
+
heldBuffers.removeAll()
|
|
266
408
|
queuedFrames = 0
|
|
267
409
|
writeWaiters.forEach { $0.resume(throwing: error) }
|
|
268
410
|
writeWaiters.removeAll()
|
|
@@ -278,9 +420,10 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
278
420
|
forName: .AVAudioEngineConfigurationChange, object: engine, queue: nil
|
|
279
421
|
) { [weak self] _ in
|
|
280
422
|
self?.stateQueue.async {
|
|
423
|
+
guard let self, !self.abandonIfUnwritten(reason: "configuration_change") else { return }
|
|
281
424
|
// A device change invalidates scheduled buffers. Reject pending writes/close
|
|
282
425
|
// instead of leaving callers waiting for callbacks that cannot arrive.
|
|
283
|
-
self
|
|
426
|
+
self.fail(PcmStreamError.native("Audio device changed; reopen the PCM stream"))
|
|
284
427
|
}
|
|
285
428
|
})
|
|
286
429
|
#else
|
|
@@ -300,9 +443,14 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
300
443
|
forName: AVAudioSession.routeChangeNotification,
|
|
301
444
|
object: nil,
|
|
302
445
|
queue: nil
|
|
303
|
-
) { [weak self]
|
|
304
|
-
|
|
305
|
-
|
|
446
|
+
) { [weak self] notification in
|
|
447
|
+
let outputChanged = Self.outputsChanged(notification)
|
|
448
|
+
self?.stateQueue.async {
|
|
449
|
+
guard let self else { return }
|
|
450
|
+
if outputChanged, self.abandonIfUnwritten(reason: "route_change") { return }
|
|
451
|
+
self.stateQueue.asyncAfter(deadline: .now() + 0.1) {
|
|
452
|
+
self.resumePlaybackIfNeeded()
|
|
453
|
+
}
|
|
306
454
|
}
|
|
307
455
|
}
|
|
308
456
|
)
|
|
@@ -326,12 +474,26 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
326
474
|
}
|
|
327
475
|
|
|
328
476
|
#if !os(macOS)
|
|
477
|
+
/// Whether a route change moved the output. The engine resets the session category before
|
|
478
|
+
/// every playback, which posts a route change that leaves the output where it was; a
|
|
479
|
+
/// prewarmed stream must survive that.
|
|
480
|
+
private static func outputsChanged(_ notification: Notification) -> Bool {
|
|
481
|
+
guard let previous = notification.userInfo?[AVAudioSessionRouteChangePreviousRouteKey]
|
|
482
|
+
as? AVAudioSessionRouteDescription
|
|
483
|
+
else { return true }
|
|
484
|
+
let signature = { (route: AVAudioSessionRouteDescription) in
|
|
485
|
+
route.outputs.map { "\($0.portType.rawValue)#\($0.uid)" }
|
|
486
|
+
}
|
|
487
|
+
return signature(previous) != signature(AVAudioSession.sharedInstance().currentRoute)
|
|
488
|
+
}
|
|
489
|
+
|
|
329
490
|
private func handleInterruption(_ notification: Notification) {
|
|
330
491
|
guard
|
|
331
492
|
let raw = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
|
|
332
493
|
let type = AVAudioSession.InterruptionType(rawValue: raw)
|
|
333
494
|
else { return }
|
|
334
495
|
|
|
496
|
+
if abandonIfUnwritten(reason: "interruption") { return }
|
|
335
497
|
switch type {
|
|
336
498
|
case .began:
|
|
337
499
|
player.pause()
|
|
@@ -353,25 +515,36 @@ final class PcmStreamPlayer: @unchecked Sendable {
|
|
|
353
515
|
enum PcmStreamManager {
|
|
354
516
|
private static let lock = NSLock()
|
|
355
517
|
private static var players: [String: PcmStreamPlayer] = [:]
|
|
518
|
+
private static var urlPlaybacks: [String: PcmUrlPlayback] = [:]
|
|
356
519
|
|
|
520
|
+
@discardableResult
|
|
357
521
|
static func open(
|
|
358
522
|
streamId: String,
|
|
359
523
|
sampleRate: Int,
|
|
360
524
|
channels: Int,
|
|
361
|
-
volume: Float
|
|
362
|
-
|
|
525
|
+
volume: Float,
|
|
526
|
+
jitterMs: Int? = nil
|
|
527
|
+
) throws -> PcmStreamPlayer {
|
|
363
528
|
let player = try PcmStreamPlayer(
|
|
364
529
|
streamId: streamId,
|
|
365
530
|
sampleRate: sampleRate,
|
|
366
531
|
channels: channels,
|
|
367
|
-
volume: volume
|
|
532
|
+
volume: volume,
|
|
533
|
+
jitterMs: jitterMs
|
|
368
534
|
)
|
|
535
|
+
player.setAbandonHandler { [weak player] in
|
|
536
|
+
guard let player else { return }
|
|
537
|
+
removeIfCurrent(streamId: streamId, player: player)
|
|
538
|
+
}
|
|
369
539
|
lock.lock()
|
|
370
540
|
let previous = players.updateValue(player, forKey: streamId)
|
|
541
|
+
let previousPlayback = urlPlaybacks.removeValue(forKey: streamId)
|
|
371
542
|
lock.unlock()
|
|
543
|
+
previousPlayback?.cancel()
|
|
372
544
|
if let previous {
|
|
373
545
|
Task { await previous.abort() }
|
|
374
546
|
}
|
|
547
|
+
return player
|
|
375
548
|
}
|
|
376
549
|
|
|
377
550
|
static func write(streamId: String, base64: String) async throws -> Int64 {
|
|
@@ -391,46 +564,106 @@ enum PcmStreamManager {
|
|
|
391
564
|
}
|
|
392
565
|
}
|
|
393
566
|
|
|
567
|
+
/// Open `streamId` and play the raw s16le mono body of `url` as it downloads. Resolves with
|
|
568
|
+
/// the played duration once the whole body has played.
|
|
569
|
+
static func playUrl(
|
|
570
|
+
streamId: String,
|
|
571
|
+
url rawUrl: String,
|
|
572
|
+
sampleRate: Int,
|
|
573
|
+
volume: Float,
|
|
574
|
+
jitterMs: Int?
|
|
575
|
+
) async throws -> Int64 {
|
|
576
|
+
guard let url = URL(string: rawUrl), let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http" else {
|
|
577
|
+
throw PcmStreamError.invalidArgument("PCM stream URL must be http(s)")
|
|
578
|
+
}
|
|
579
|
+
let player = try open(
|
|
580
|
+
streamId: streamId,
|
|
581
|
+
sampleRate: sampleRate,
|
|
582
|
+
channels: 1,
|
|
583
|
+
volume: volume,
|
|
584
|
+
jitterMs: jitterMs
|
|
585
|
+
)
|
|
586
|
+
let playback = PcmUrlLoader.shared.start(url: url, sink: player)
|
|
587
|
+
if !register(playback, streamId: streamId, player: player) {
|
|
588
|
+
playback.cancel()
|
|
589
|
+
}
|
|
590
|
+
do {
|
|
591
|
+
let duration = try await playback.wait()
|
|
592
|
+
removeUrlPlaybackIfCurrent(streamId: streamId, playback: playback)
|
|
593
|
+
removeIfCurrent(streamId: streamId, player: player)
|
|
594
|
+
return duration
|
|
595
|
+
} catch {
|
|
596
|
+
removeUrlPlaybackIfCurrent(streamId: streamId, playback: playback)
|
|
597
|
+
if removeIfCurrent(streamId: streamId, player: player) {
|
|
598
|
+
await player.abort()
|
|
599
|
+
}
|
|
600
|
+
throw error
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
394
604
|
static func abort(streamId: String) async {
|
|
395
|
-
|
|
396
|
-
|
|
605
|
+
let (playback, player) = take(streamId: streamId)
|
|
606
|
+
// Cancel first so a URL playback rejects with "aborted", not a write error.
|
|
607
|
+
playback?.cancel()
|
|
608
|
+
await player?.abort()
|
|
397
609
|
}
|
|
398
610
|
|
|
399
611
|
static func abortAll() async {
|
|
400
|
-
let active = takeAll()
|
|
612
|
+
let (playbacks, active) = takeAll()
|
|
613
|
+
playbacks.forEach { $0.cancel() }
|
|
401
614
|
for player in active {
|
|
402
615
|
await player.abort()
|
|
403
616
|
}
|
|
404
617
|
}
|
|
405
618
|
|
|
406
|
-
|
|
619
|
+
/// `open` cleared any earlier playback for this id; only a racing open can have replaced
|
|
620
|
+
/// the player since, and that one owns the id now.
|
|
621
|
+
private static func register(_ playback: PcmUrlPlayback, streamId: String, player: PcmStreamPlayer) -> Bool {
|
|
407
622
|
lock.lock()
|
|
408
623
|
defer { lock.unlock() }
|
|
409
|
-
guard
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
return player
|
|
624
|
+
guard players[streamId] === player else { return false }
|
|
625
|
+
urlPlaybacks[streamId] = playback
|
|
626
|
+
return true
|
|
413
627
|
}
|
|
414
628
|
|
|
415
|
-
private static func
|
|
629
|
+
private static func take(streamId: String) -> (PcmUrlPlayback?, PcmStreamPlayer?) {
|
|
416
630
|
lock.lock()
|
|
417
631
|
defer { lock.unlock() }
|
|
418
|
-
return players.removeValue(forKey: streamId)
|
|
632
|
+
return (urlPlaybacks.removeValue(forKey: streamId), players.removeValue(forKey: streamId))
|
|
419
633
|
}
|
|
420
634
|
|
|
421
|
-
private static func
|
|
635
|
+
private static func takeAll() -> ([PcmUrlPlayback], [PcmStreamPlayer]) {
|
|
422
636
|
lock.lock()
|
|
423
637
|
defer { lock.unlock() }
|
|
424
|
-
|
|
425
|
-
|
|
638
|
+
let result = (Array(urlPlaybacks.values), Array(players.values))
|
|
639
|
+
urlPlaybacks.removeAll()
|
|
640
|
+
players.removeAll()
|
|
641
|
+
return result
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
private static func lookup(streamId: String) throws -> PcmStreamPlayer {
|
|
645
|
+
lock.lock()
|
|
646
|
+
defer { lock.unlock() }
|
|
647
|
+
guard let player = players[streamId] else {
|
|
648
|
+
throw PcmStreamError.notOpen(streamId)
|
|
426
649
|
}
|
|
650
|
+
return player
|
|
427
651
|
}
|
|
428
652
|
|
|
429
|
-
|
|
653
|
+
@discardableResult
|
|
654
|
+
private static func removeIfCurrent(streamId: String, player: PcmStreamPlayer) -> Bool {
|
|
430
655
|
lock.lock()
|
|
431
656
|
defer { lock.unlock() }
|
|
432
|
-
|
|
433
|
-
players.
|
|
434
|
-
return
|
|
657
|
+
guard players[streamId] === player else { return false }
|
|
658
|
+
players.removeValue(forKey: streamId)
|
|
659
|
+
return true
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private static func removeUrlPlaybackIfCurrent(streamId: String, playback: PcmUrlPlayback) {
|
|
663
|
+
lock.lock()
|
|
664
|
+
defer { lock.unlock() }
|
|
665
|
+
if urlPlaybacks[streamId] === playback {
|
|
666
|
+
urlPlaybacks.removeValue(forKey: streamId)
|
|
667
|
+
}
|
|
435
668
|
}
|
|
436
669
|
}
|