Skip to content

Commit 1573a4f

Browse files
Lee Seongjooclaude
andcommitted
Paragraph-chunked synthesis + queued playback; non-stealing HUD; mirror input
Long selections were unstable as a single request and the cache was whole-text exact-match only. Now: - TextSplitter: split a selection into paragraphs (newline breaks); a paragraph over maxChars is split by a CHARACTER budget at word boundaries (not sentence boundaries) so requests stay bounded and uniform. - Each chunk is the cache + request unit (paragraph-level cache hits). Cache hit → reuse file; miss → synthesize + cache. Chunks are enqueued into a QueuePlayer (AVQueuePlayer) and played back-to-back; playback starts on the first chunk while the rest stream in. Overlay shows "문단 i/n" + overall progress. - HUD overlay no longer steals focus: NonKeyPanel can't become key/main, and synthesis never activates the app — the source window stays frontmost. - Selected text (even from the Services menu) is mirrored into AppState.inputText so it shows in the Generate tab; the window is not brought forward. - Settings: configurable "문단 최대 글자수" (maxChunkChars). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a4da5c4 commit 1573a4f

9 files changed

Lines changed: 240 additions & 86 deletions

‎Sources/App/AppState.swift‎

Lines changed: 63 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,19 @@ final class AppState: ObservableObject {
2929
// Runtime
3030
enum Phase: Equatable { case idle, synthesizing, playing, paused }
3131
@Published var phase: Phase = .idle
32-
@Published var progress: Double = 0 // 0…1 playback position
32+
@Published var progress: Double = 0 // 0…1 across all chunks
3333
@Published var currentText = "" // text being spoken (overlay label)
34+
@Published var inputText = "" // mirrored into the Generate tab
35+
@Published var chunkIndex = 0 // 1-based chunk being played
36+
@Published var chunkCount = 0
3437
@Published var statusText = ""
38+
@Published var maxChunkChars = TextSplitter.defaultMaxChars
3539
@Published private(set) var history: [HistoryEntry] = []
3640

3741
var isBusy: Bool { phase != .idle }
3842

3943
private let cache = CacheStore()
40-
private let player = AudioPlayer()
44+
private let player = QueuePlayer()
4145
private var task: Task<Void, Never>?
4246
private var timer: Timer?
4347

@@ -49,18 +53,7 @@ final class AppState: ObservableObject {
4953

5054
private func finish() {
5155
stopTimer()
52-
phase = .idle; progress = 0; statusText = ""
53-
}
54-
55-
/// Begin playback of ready audio and enter the .playing phase.
56-
private func startPlayback(_ data: Data, status: String) {
57-
do {
58-
try player.play(data)
59-
statusText = status; phase = .playing
60-
startTimer()
61-
} catch {
62-
statusText = "재생 실패"; phase = .idle
63-
}
56+
phase = .idle; progress = 0; statusText = ""; chunkIndex = 0; chunkCount = 0
6457
}
6558

6659
// MARK: - Transport (overlay controls)
@@ -81,8 +74,8 @@ final class AppState: ObservableObject {
8174
}
8275
private func stopTimer() { timer?.invalidate(); timer = nil }
8376
private func tick() {
84-
let d = player.duration
85-
progress = d > 0 ? min(1, player.currentTime / d) : 0
77+
progress = player.progress
78+
chunkIndex = min(max(1, player.finishedCount + 1), max(1, chunkCount))
8679
}
8780

8881
var backendIdentity: String { backendKind == .elevenlabs ? "elevenlabs" : "qwen3-local" }
@@ -100,38 +93,63 @@ final class AppState: ObservableObject {
10093
}
10194
}
10295

103-
// MARK: - Synthesize (cache-first)
96+
// MARK: - Synthesize (paragraph chunks, cache-first, queued playback)
10497

10598
func synthesize(_ text: String) {
10699
let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
107100
guard !t.isEmpty else { return }
108-
task?.cancel(); player.stop()
101+
let chunks = TextSplitter.paragraphs(t, maxChars: maxChunkChars)
102+
guard !chunks.isEmpty else { return }
109103

110-
let key = CacheStore.key(text: t, backend: backendIdentity,
111-
voiceId: voiceId, modelId: modelId, settingsHash: settingsHash)
104+
task?.cancel(); player.stop()
105+
inputText = t // mirror into the Generate tab (req: show source text)
112106
currentText = t
113-
if useCache, let data = cache.data(forKey: key) {
114-
cache.touch(key); history = cache.entries
115-
startPlayback(data, status: "캐시에서 재생")
116-
return
117-
}
118-
guard let backend = makeBackend() else { statusText = "키/백엔드 미설정"; return }
119107
phase = .synthesizing; statusText = "합성 중…"; progress = 0
120-
let voice = VoiceConfig(voiceId: voiceId, modelId: modelId, settingsHash: settingsHash)
121-
let vName = voiceName, ident = backendIdentity, ext = audioExt
108+
player.start(expected: chunks.count)
109+
chunkCount = chunks.count; chunkIndex = 0
110+
111+
let ident = backendIdentity, vid = voiceId, mid = modelId, sHash = settingsHash
112+
let vName = voiceName, ext = audioExt
113+
let voice = VoiceConfig(voiceId: vid, modelId: mid, settingsHash: sHash)
114+
122115
task = Task { [weak self] in
123116
guard let self else { return }
117+
var backend: TTSBackend?
124118
do {
125-
var data = Data()
126-
for try await chunk in backend.stream(segment: t, voice: voice) {
127-
try Task.checkCancellation(); data.append(chunk)
128-
}
129-
if self.useCache {
130-
self.cache.save(key: key, text: t, backend: ident, voiceId: self.voiceId,
131-
voiceName: vName, modelId: self.modelId, ext: ext, data: data)
132-
self.history = self.cache.entries
119+
for chunk in chunks {
120+
try Task.checkCancellation()
121+
let key = CacheStore.key(text: chunk, backend: ident,
122+
voiceId: vid, modelId: mid, settingsHash: sHash)
123+
var url: URL?
124+
if self.useCache, let u = self.cache.fileURL(forKey: key) {
125+
self.cache.touch(key); url = u
126+
} else {
127+
if backend == nil { backend = self.makeBackend() }
128+
guard let b = backend else {
129+
self.phase = .idle; self.statusText = "키/백엔드 미설정"; return
130+
}
131+
var data = Data()
132+
for try await c in b.stream(segment: chunk, voice: voice) {
133+
try Task.checkCancellation(); data.append(c)
134+
}
135+
if self.useCache {
136+
let e = self.cache.save(key: key, text: chunk, backend: ident, voiceId: vid,
137+
voiceName: vName, modelId: mid, ext: ext, data: data)
138+
url = self.cache.audioURL(e)
139+
} else {
140+
let tmp = FileManager.default.temporaryDirectory
141+
.appendingPathComponent("\(key).\(ext)")
142+
try? data.write(to: tmp); url = tmp
143+
}
144+
}
145+
if let url {
146+
self.player.enqueue(url)
147+
if self.phase == .synthesizing {
148+
self.phase = .playing; self.statusText = "재생 중…"; self.startTimer()
149+
}
150+
}
133151
}
134-
self.startPlayback(data, status: "재생 중…")
152+
self.history = self.cache.entries
135153
} catch is CancellationError {
136154
self.finish()
137155
} catch {
@@ -143,10 +161,13 @@ final class AppState: ObservableObject {
143161

144162
func replay(_ e: HistoryEntry) {
145163
task?.cancel(); player.stop()
146-
guard let data = cache.data(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
164+
guard let url = cache.fileURL(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
147165
cache.touch(e.id); history = cache.entries
148-
currentText = e.text
149-
startPlayback(data, status: "캐시에서 재생")
166+
inputText = e.text; currentText = e.text
167+
chunkCount = 1; chunkIndex = 1; progress = 0
168+
player.start(expected: 1)
169+
player.enqueue(url)
170+
phase = .playing; statusText = "캐시에서 재생"; startTimer()
150171
}
151172

152173
func stop() { task?.cancel(); player.stop(); finish() }
@@ -193,6 +214,7 @@ final class AppState: ObservableObject {
193214
let dict: [String: Any] = [
194215
"voiceId": voiceId, "voiceName": voiceName, "modelId": modelId,
195216
"backend": backendKind.rawValue, "useCache": useCache, "localBaseURL": localBaseURL,
217+
"maxChunkChars": maxChunkChars,
196218
"stability": voiceSettings.stability, "similarity": voiceSettings.similarityBoost,
197219
"style": voiceSettings.style, "speakerBoost": voiceSettings.useSpeakerBoost,
198220
]
@@ -210,6 +232,7 @@ final class AppState: ObservableObject {
210232
backendKind = BackendKind(rawValue: o["backend"] as? String ?? "") ?? backendKind
211233
useCache = o["useCache"] as? Bool ?? useCache
212234
localBaseURL = o["localBaseURL"] as? String ?? localBaseURL
235+
maxChunkChars = o["maxChunkChars"] as? Int ?? maxChunkChars
213236
voiceSettings.stability = o["stability"] as? Double ?? voiceSettings.stability
214237
voiceSettings.similarityBoost = o["similarity"] as? Double ?? voiceSettings.similarityBoost
215238
voiceSettings.style = o["style"] as? Double ?? voiceSettings.style

‎Sources/Core/AudioPlayer.swift‎

Lines changed: 0 additions & 33 deletions
This file was deleted.

‎Sources/Core/CacheStore.swift‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ final class CacheStore {
4848
return try? Data(contentsOf: audioURL(e))
4949
}
5050

51+
/// File URL for a cached key, only if the audio file actually exists.
52+
func fileURL(forKey key: String) -> URL? {
53+
guard let e = entry(forKey: key) else { return nil }
54+
let url = audioURL(e)
55+
return FileManager.default.fileExists(atPath: url.path) ? url : nil
56+
}
57+
5158
@discardableResult
5259
func save(key: String, text: String, backend: String, voiceId: String,
5360
voiceName: String, modelId: String, ext: String, data: Data) -> HistoryEntry {

‎Sources/Core/QueuePlayer.swift‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import AVFoundation
2+
3+
/// Plays a sequence of audio files back-to-back via AVQueuePlayer. Chunks
4+
/// (paragraphs) are enqueued as they become ready (cache hit = immediately,
5+
/// miss = after synthesis), so playback starts on the first chunk and the rest
6+
/// stream in. pause()/resume() keep position; small gaps between items fall on
7+
/// paragraph boundaries (natural pauses).
8+
final class QueuePlayer {
9+
private let player = AVQueuePlayer()
10+
var onFinish: (() -> Void)?
11+
12+
private var expected = 0
13+
private var finished = 0
14+
private var observers: [NSObjectProtocol] = []
15+
16+
init() { player.actionAtItemEnd = .advance }
17+
18+
var isPlaying: Bool { player.rate != 0 }
19+
var finishedCount: Int { finished }
20+
var expectedCount: Int { expected }
21+
22+
/// Begin a new sequence of `expected` chunks.
23+
func start(expected: Int) {
24+
stop()
25+
self.expected = expected
26+
self.finished = 0
27+
}
28+
29+
func enqueue(_ url: URL) {
30+
let item = AVPlayerItem(url: url)
31+
let obs = NotificationCenter.default.addObserver(
32+
forName: .AVPlayerItemDidPlayToEndTime, object: item, queue: .main
33+
) { [weak self] _ in self?.itemFinished() }
34+
observers.append(obs)
35+
player.insert(item, after: nil)
36+
if player.rate == 0 { player.play() }
37+
}
38+
39+
private func itemFinished() {
40+
finished += 1
41+
if finished >= expected, expected > 0 { onFinish?() }
42+
}
43+
44+
func pause() { player.pause() }
45+
func resume() { player.play() }
46+
47+
func stop() {
48+
player.pause()
49+
player.removeAllItems()
50+
observers.forEach { NotificationCenter.default.removeObserver($0) }
51+
observers.removeAll()
52+
expected = 0
53+
finished = 0
54+
}
55+
56+
/// Overall progress across the whole sequence (0…1).
57+
var progress: Double {
58+
guard expected > 0 else { return 0 }
59+
return min(1, (Double(finished) + currentItemFraction) / Double(expected))
60+
}
61+
62+
private var currentItemFraction: Double {
63+
guard let item = player.currentItem else { return 0 }
64+
let dur = item.duration.seconds
65+
guard dur.isFinite, dur > 0 else { return 0 }
66+
return min(1, item.currentTime().seconds / dur)
67+
}
68+
}

‎Sources/Core/TextSplitter.swift‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import Foundation
2+
3+
/// Splits a selection into paragraph-sized chunks. Paragraphs are the cache +
4+
/// request unit: long single-shot requests are unstable, and paragraph-level
5+
/// cache hits are stable (sentence-level is too fine). A paragraph longer than
6+
/// `maxChars` is split by a character budget (NOT sentence boundaries) so each
7+
/// backend request stays bounded and chunk sizes are uniform; the cut lands on
8+
/// the nearest preceding whitespace to avoid breaking a word.
9+
enum TextSplitter {
10+
static let defaultMaxChars = 700
11+
12+
static func paragraphs(_ text: String, maxChars: Int = defaultMaxChars) -> [String] {
13+
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
14+
guard !trimmed.isEmpty else { return [] }
15+
16+
// Newline(s) delimit paragraphs.
17+
let paras = trimmed
18+
.components(separatedBy: .newlines)
19+
.map { $0.trimmingCharacters(in: .whitespaces) }
20+
.filter { !$0.isEmpty }
21+
22+
var out: [String] = []
23+
for p in paras {
24+
if p.count <= maxChars {
25+
out.append(p)
26+
} else {
27+
out.append(contentsOf: splitByChars(p, maxChars: maxChars))
28+
}
29+
}
30+
return out
31+
}
32+
33+
/// Split a long paragraph into <= maxChars windows, cutting at the last
34+
/// whitespace at/before the limit (hard cut if a token is longer than the
35+
/// window).
36+
private static func splitByChars(_ p: String, maxChars: Int) -> [String] {
37+
var chunks: [String] = []
38+
var s = Substring(p)
39+
while s.count > maxChars {
40+
let limit = s.index(s.startIndex, offsetBy: maxChars)
41+
var cut = limit
42+
var idx = limit
43+
var found = false
44+
while idx > s.startIndex {
45+
let prev = s.index(before: idx)
46+
if s[prev].isWhitespace { cut = prev; found = true; break }
47+
idx = prev
48+
}
49+
if !found { cut = limit } // no space: hard cut
50+
let piece = s[s.startIndex..<cut].trimmingCharacters(in: .whitespaces)
51+
if !piece.isEmpty { chunks.append(piece) }
52+
var next = cut
53+
while next < s.endIndex, s[next].isWhitespace { next = s.index(after: next) }
54+
s = s[next...]
55+
}
56+
let tail = s.trimmingCharacters(in: .whitespaces)
57+
if !tail.isEmpty { chunks.append(tail) }
58+
return chunks
59+
}
60+
}

0 commit comments

Comments
 (0)