forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeviceAudioStreamController.swift
More file actions
185 lines (165 loc) · 5.17 KB
/
Copy pathDeviceAudioStreamController.swift
File metadata and controls
185 lines (165 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import Foundation
/// Owns the device-side lifetime behind a multicast audio stream.
///
/// The first subscriber starts the physical recording session. Every subscriber
/// receives every active-session frame; setup and teardown frames are dropped.
/// The last subscriber leaving cancels and joins in-flight setup before the stop
/// action runs. This closes the race where a consumer could disappear during
/// setup and recording would start afterward without an owner.
@MainActor
final class DeviceAudioStreamController {
typealias Continuation = AsyncThrowingStream<Data, Error>.Continuation
typealias StartAction = @MainActor @Sendable () async throws -> Void
typealias StopAction = @MainActor @Sendable () async throws -> Void
private enum Phase: Equatable {
case idle
case starting(UInt64)
case active(UInt64)
case stopping(UInt64)
}
private let startAction: StartAction
private let stopAction: StopAction
private var phase = Phase.idle
private var generation: UInt64 = 0
private var subscribers: [UUID: Continuation] = [:]
private var setupTask: Task<Void, Never>?
private var cleanupTask: Task<Void, Never>?
private var isClosed = false
private var terminalError: Error?
init(
start: @escaping StartAction,
stop: @escaping StopAction
) {
self.startAction = start
self.stopAction = stop
}
func makeStream() -> AsyncThrowingStream<Data, Error> {
guard !isClosed else {
return AsyncThrowingStream { continuation in
if let terminalError {
continuation.finish(throwing: terminalError)
} else {
continuation.finish()
}
}
}
let subscriberID = UUID()
return AsyncThrowingStream { continuation in
subscribers[subscriberID] = continuation
continuation.onTermination = { @Sendable [weak self] _ in
Task { @MainActor [weak self] in
self?.removeSubscriber(subscriberID)
}
}
startIfNeeded()
}
}
func yield(_ data: Data) {
guard case .active = phase else { return }
var terminatedSubscribers: [UUID] = []
for (subscriberID, continuation) in subscribers {
if case .terminated = continuation.yield(data) {
terminatedSubscribers.append(subscriberID)
}
}
for subscriberID in terminatedSubscribers {
removeSubscriber(subscriberID)
}
}
func finish(throwing error: Error? = nil) async {
if !isClosed {
isClosed = true
terminalError = error
finishSubscribers(throwing: error)
}
let cleanup = stopIfNeeded()
await cleanup?.value
}
private func startIfNeeded() {
guard !isClosed, !subscribers.isEmpty, phase == .idle else { return }
generation &+= 1
let setupGeneration = generation
phase = .starting(setupGeneration)
let task = Task { @MainActor [weak self] in
guard let self else { return }
do {
try Task.checkCancellation()
try await self.startAction()
self.completeStart(generation: setupGeneration, error: nil)
} catch {
self.completeStart(generation: setupGeneration, error: error)
}
}
setupTask = task
}
private func completeStart(generation setupGeneration: UInt64, error: Error?) {
guard phase == .starting(setupGeneration) else { return }
setupTask = nil
if let error {
// Setup may have completed some physical steps before failing.
// Treat it as active until the stop action has unwound them.
phase = .active(setupGeneration)
finishSubscribers(throwing: error)
_ = stopIfNeeded()
return
}
phase = .active(setupGeneration)
}
private func removeSubscriber(_ subscriberID: UUID) {
subscribers.removeValue(forKey: subscriberID)
if subscribers.isEmpty {
_ = stopIfNeeded()
}
}
@discardableResult
private func stopIfNeeded() -> Task<Void, Never>? {
switch phase {
case .idle:
return cleanupTask
case .stopping:
return cleanupTask
case .starting, .active:
generation &+= 1
let cleanupGeneration = generation
phase = .stopping(cleanupGeneration)
let setup = setupTask
setupTask = nil
setup?.cancel()
let task = Task { @MainActor [weak self] in
await setup?.value
guard let self else { return }
do {
try await self.stopAction()
self.completeStop(generation: cleanupGeneration, error: nil)
} catch {
self.completeStop(generation: cleanupGeneration, error: error)
}
}
cleanupTask = task
return task
}
}
private func completeStop(generation cleanupGeneration: UInt64, error: Error?) {
guard phase == .stopping(cleanupGeneration) else { return }
cleanupTask = nil
phase = .idle
if let error {
terminalError = error
isClosed = true
finishSubscribers(throwing: error)
return
}
startIfNeeded()
}
private func finishSubscribers(throwing error: Error?) {
let currentSubscribers = Array(subscribers.values)
subscribers.removeAll()
for continuation in currentSubscribers {
if let error {
continuation.finish(throwing: error)
} else {
continuation.finish()
}
}
}
}