-
Notifications
You must be signed in to change notification settings - Fork 265
Expand file tree
/
Copy pathTTSService.swift
More file actions
334 lines (294 loc) · 11.3 KB
/
TTSService.swift
File metadata and controls
334 lines (294 loc) · 11.3 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//
// TTSService.swift
// osaurus
//
// PocketTTS (FluidAudio) text-to-speech service. Streams 80 ms audio frames
// from the model into an AVAudioEngine player node for real-time playback.
//
import AVFoundation
import Combine
@preconcurrency import FluidAudio
import Foundation
/// Errors mapped onto tool error envelopes by the `speak` tool.
public enum TTSPlaybackError: Error {
case modelNotReady
}
/// Model-readiness state for PocketTTS.
public enum TTSModelState: Equatable {
case notReady
/// `fraction` is in [0, 1]. `nil` means indeterminate (e.g. compile phase).
case downloading(fraction: Double?)
case ready
case failed(String)
}
/// Singleton that owns the PocketTTS manager, audio engine, and playback lifecycle.
@MainActor
public final class TTSService: ObservableObject {
public static let shared = TTSService()
// MARK: - Published state
/// ID of the message currently being spoken. `nil` when idle.
@Published public private(set) var playingMessageId: UUID? {
didSet {
if oldValue != playingMessageId {
// Clear the tool-call binding when playback ends so
// the row's spinner stops alongside the audio.
if playingMessageId == nil { activeSpeakCallId = nil }
NotificationCenter.default.post(name: .ttsPlaybackStateChanged, object: nil)
}
}
}
/// Tracks whether the PocketTTS model is initialized and usable.
@Published public private(set) var modelState: TTSModelState = .notReady
/// Tool-call id driving the current playback (`nil` for the manual
/// speaker button or when idle). The inline tool card watches this
/// to swap its check for a spinner while audio is still playing.
@Published public private(set) var activeSpeakCallId: String? {
didSet {
if oldValue != activeSpeakCallId {
NotificationCenter.default.post(name: .ttsPlaybackStateChanged, object: nil)
}
}
}
// MARK: - Private state
private var manager: PocketTtsManager?
private var playbackTask: Task<Void, Never>?
private var initTask: Task<Void, Never>?
private let audioEngine = AVAudioEngine()
private let playerNode = AVAudioPlayerNode()
private let sourceFormat: AVAudioFormat = {
AVAudioFormat(
commonFormat: .pcmFormatFloat32,
sampleRate: 24_000,
channels: 1,
interleaved: false
)!
}()
private var engineConfigured = false
private var pendingBufferCount = 0
private var streamFinished = false
private init() {}
// MARK: - Public API
/// True when the model is fully loaded and ready to synthesize.
public var isModelReady: Bool {
if case .ready = modelState { return true }
return false
}
/// Toggle speech for a given message. Tapping the currently-playing
/// message stops playback; tapping a different message switches to it.
/// If the model isn't downloaded yet, posts `.openTTSSettingsRequested`.
public func toggleSpeak(text: String, messageId: UUID) {
if playingMessageId == messageId {
stop()
return
}
guard isModelReady else {
if Self.pocketTtsModelsExistOnDisk() {
// Models already downloaded; just load them into memory.
ensureModelLoaded()
} else {
NotificationCenter.default.post(name: .openTTSSettingsRequested, object: nil)
}
return
}
let plain = MarkdownStripper.plainText(from: text)
guard !plain.isEmpty else { return }
stop()
playingMessageId = messageId
startPlayback(text: plain, messageId: messageId)
}
/// Fire-and-forget playback for the `speak` tool. Sets
/// `activeSpeakCallId` so the row spinner runs until audio drains
public func startToolPlayback(text: String, messageId: UUID, callId: String) throws {
guard isModelReady else {
if Self.pocketTtsModelsExistOnDisk() {
ensureModelLoaded()
} else {
NotificationCenter.default.post(name: .openTTSSettingsRequested, object: nil)
}
throw TTSPlaybackError.modelNotReady
}
let plain = MarkdownStripper.plainText(from: text)
guard !plain.isEmpty else { return }
stop()
playingMessageId = messageId
activeSpeakCallId = callId
startPlayback(text: plain, messageId: messageId)
}
/// Stop any in-flight synthesis and clear playback state.
public func stop() {
playbackTask?.cancel()
playbackTask = nil
streamFinished = true
pendingBufferCount = 0
if engineConfigured {
playerNode.stop()
playerNode.reset()
}
playingMessageId = nil
}
/// Begin a background download/initialize. Safe to call multiple times.
public func ensureModelLoaded() {
if case .ready = modelState { return }
if initTask != nil { return }
modelState = .downloading(fraction: nil)
let voice = TTSConfigurationStore.load().voice
initTask = Task { [weak self] in
do {
// Let FluidAudio pick its default language pack so this call
// stays compatible across the workspace-pinned and package
// resolved PocketTTS APIs.
let mgr = PocketTtsManager(defaultVoice: voice)
try await mgr.initialize()
await MainActor.run {
guard let self else { return }
self.manager = mgr
self.modelState = .ready
self.initTask = nil
}
} catch {
await MainActor.run {
guard let self else { return }
self.modelState = .failed(error.localizedDescription)
self.initTask = nil
}
}
}
}
/// Refresh `modelState` by checking the PocketTTS cache on disk.
/// Call this on app launch and when returning to the settings tab.
/// If models are already present, transitions to `.ready` after a fast local load.
public func refreshModelState() {
if case .ready = modelState { return }
if initTask != nil { return }
if Self.pocketTtsModelsExistOnDisk() {
ensureModelLoaded()
} else {
modelState = .notReady
}
}
private static func pocketTtsModelsExistOnDisk() -> Bool {
let home = FileManager.default.homeDirectoryForCurrentUser
let repoDir =
home
.appendingPathComponent(".cache", isDirectory: true)
.appendingPathComponent("fluidaudio", isDirectory: true)
.appendingPathComponent("Models", isDirectory: true)
.appendingPathComponent("pocket-tts", isDirectory: true)
let candidateDirs = [
repoDir,
repoDir
.appendingPathComponent("v2", isDirectory: true)
.appendingPathComponent("english", isDirectory: true)
]
let required = ModelNames.PocketTTS.requiredModels
let fm = FileManager.default
return candidateDirs.contains { directory in
required.allSatisfy { fm.fileExists(atPath: directory.appendingPathComponent($0).path) }
}
}
// MARK: - Playback
private func startPlayback(text: String, messageId: UUID) {
do {
try configureEngineIfNeeded()
} catch {
modelState = .failed(error.localizedDescription)
playingMessageId = nil
return
}
guard let manager else {
playingMessageId = nil
return
}
streamFinished = false
pendingBufferCount = 0
playerNode.play()
let config = TTSConfigurationStore.load()
let voice = config.voice
let temperature = Float(config.temperature)
playbackTask = Task { [weak self] in
do {
let stream = try await manager.synthesizeStreaming(
text: text,
voice: voice,
temperature: temperature
)
for try await frame in stream {
if Task.isCancelled { break }
self?.schedule(samples: frame.samples)
}
self?.markStreamFinished(for: messageId)
} catch is CancellationError {
// stop() already cleared state
} catch {
self?.handleStreamError(error, for: messageId)
}
}
}
private func schedule(samples: [Float]) {
guard let buffer = makeBuffer(from: samples) else { return }
pendingBufferCount += 1
playerNode.scheduleBuffer(buffer) { [weak self] in
Task { @MainActor [weak self] in
self?.bufferDidFinish()
}
}
}
private func bufferDidFinish() {
pendingBufferCount = max(0, pendingBufferCount - 1)
if streamFinished, pendingBufferCount == 0 {
playingMessageId = nil
playerNode.stop()
}
}
private func markStreamFinished(for messageId: UUID) {
guard playingMessageId == messageId else { return }
streamFinished = true
if pendingBufferCount == 0 {
playingMessageId = nil
playerNode.stop()
}
}
private func handleStreamError(_ error: Error, for messageId: UUID) {
print("[TTSService] synthesis error: \(error)")
if playingMessageId == messageId {
stop()
}
}
private func makeBuffer(from samples: [Float]) -> AVAudioPCMBuffer? {
guard !samples.isEmpty else { return nil }
guard
let buffer = AVAudioPCMBuffer(
pcmFormat: sourceFormat,
frameCapacity: AVAudioFrameCount(samples.count)
)
else {
return nil
}
buffer.frameLength = AVAudioFrameCount(samples.count)
if let ptr = buffer.floatChannelData?[0] {
samples.withUnsafeBufferPointer { src in
ptr.update(from: src.baseAddress!, count: samples.count)
}
}
return buffer
}
private func configureEngineIfNeeded() throws {
if engineConfigured, audioEngine.isRunning { return }
if !engineConfigured {
audioEngine.attach(playerNode)
audioEngine.connect(playerNode, to: audioEngine.mainMixerNode, format: sourceFormat)
engineConfigured = true
}
if !audioEngine.isRunning {
try audioEngine.start()
}
}
}
extension Notification.Name {
/// Posted when the user taps a speaker button but the TTS model isn't ready.
/// The app should surface the TTS settings tab so they can download the model.
public static let openTTSSettingsRequested = Notification.Name("osaurus.openTTSSettingsRequested")
/// Posted whenever `TTSService.playingMessageId` changes.
/// AppKit views that can't observe `@Published` use this to refresh their speaker button icon.
public static let ttsPlaybackStateChanged = Notification.Name("osaurus.ttsPlaybackStateChanged")
}