Skip to content

Commit 40ff8fc

Browse files
Lee Seongjooclaude
andcommitted
perf: keep the 10Hz playback tick from re-rendering the whole window
The tick updated progress/chunkProgress/chunkSeconds on AppState 10x/sec via @published, firing objectWillChange and re-rendering every view that observes AppState (all main-window tabs) — janking text input, and piling up SwiftUI observation-tracking allocations that stayed reachable (~250MB, never released). - Move the continuous playback values onto a separate PlaybackTelemetry ObservableObject that only PlayerOverlay observes; the main window no longer re-renders on ticks. chunkIndex stays on AppState but is assigned only when the paragraph actually turns. - Memoize the subtitle sentence split and compute the current-line id once per frame instead of re-splitting the whole subtitle per line — the crawl was running TextSplitter.sentences (N+2) times per frame, stuttering on long text. - Fix a latent leak: a mid-playback synthesis error left phase=.idle but never stopped the timer, so it ticked forever and grew memory while idle. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 0dbbdea commit 40ff8fc

4 files changed

Lines changed: 70 additions & 18 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@ final class AppState: ObservableObject {
151151
// Runtime
152152
enum Phase: Equatable { case idle, synthesizing, playing, paused }
153153
@Published var phase: Phase = .idle
154-
@Published var progress: Double = 0 // 0…1 across all chunks
154+
/// High-frequency playback values (progress/chunkProgress/chunkSeconds) live on
155+
/// a SEPARATE ObservableObject so the 10 Hz tick doesn't invalidate every view
156+
/// observing AppState. Only PlayerOverlay observes this. See PlaybackTelemetry.
157+
let telemetry = PlaybackTelemetry()
155158

156159
/// What the current playback is — shown in the HUD instead of the script text.
157160
enum PlaybackMode { case tts, explain
@@ -174,8 +177,6 @@ final class AppState: ObservableObject {
174177
var hudPositions: [CGDirectDisplayID: CGPoint] = [:] // bottom-left offset within each screen's visibleFrame
175178
@Published var spokenChunks: [String] = [] // the spoken (대본) paragraph chunks — drives crawlFraction
176179
@Published var subtitleText = "" // the human-readable subtitle source (원본/해설), shown as the crawl
177-
@Published var chunkProgress: Double = 0 // 0…1 within the current paragraph
178-
@Published var chunkSeconds: Double = 0 // seconds into the current paragraph
179180
@Published var chunkSentenceTimes: [[Double]] = [] // exact sentence start times per chunk (ElevenLabs); [] = estimate
180181
var showSubtitle: Bool { playbackMode == .tts ? subtitleTTS : subtitleExplain }
181182

@@ -189,15 +190,30 @@ final class AppState: ObservableObject {
189190
let text: String
190191
}
191192

193+
/// Memoized sentence split of the current subtitle. `TextSplitter.sentences`
194+
/// is an O(N) char scan; the crawl reads it every 0.1s frame (and used to
195+
/// re-split once PER line for the current-line test), so recomputing it per
196+
/// frame stalls the main thread and janks the subtitle + typing. Recompute
197+
/// only when `subtitleText` actually changes.
198+
private var sentenceCacheKey: String?
199+
private var sentenceCache: [String] = []
200+
private var subtitleSentences: [String] {
201+
if sentenceCacheKey != subtitleText {
202+
sentenceCacheKey = subtitleText
203+
sentenceCache = TextSplitter.sentences(subtitleText)
204+
}
205+
return sentenceCache
206+
}
207+
192208
/// The full subtitle text split into sentences, flattened in reading order.
193209
var crawlLines: [CrawlLine] {
194-
TextSplitter.sentences(subtitleText).enumerated().map { CrawlLine(id: $0.offset, text: $0.element) }
210+
subtitleSentences.enumerated().map { CrawlLine(id: $0.offset, text: $0.element) }
195211
}
196212

197213
/// Which subtitle sentence is being read now — overall audio progress
198214
/// (`crawlFraction`) mapped onto the subtitle text by length.
199215
var currentCrawlLineID: Int {
200-
TextSplitter.sentenceIndex(at: crawlFraction, in: TextSplitter.sentences(subtitleText))
216+
TextSplitter.sentenceIndex(at: crawlFraction, in: subtitleSentences)
201217
}
202218
func isCurrentLine(_ line: CrawlLine) -> Bool { line.id == currentCrawlLineID }
203219

@@ -206,7 +222,7 @@ final class AppState: ObservableObject {
206222
/// QueuePlayer.progress is chunk-equal-weighted, which lurches per paragraph.
207223
var crawlFraction: Double {
208224
CrawlLayout.fraction(chunkLengths: spokenChunks.map { Double(max(1, $0.count)) },
209-
chunkIndex: chunkIndex, chunkProgress: chunkProgress)
225+
chunkIndex: chunkIndex, chunkProgress: telemetry.chunkProgress)
210226
}
211227

212228
/// Map ElevenLabs per-character start times to one start time per sentence
@@ -292,7 +308,7 @@ final class AppState: ObservableObject {
292308

293309
private func finish() {
294310
stopTimer()
295-
phase = .idle; progress = 0; statusText = ""; chunkIndex = 0; chunkCount = 0
311+
phase = .idle; telemetry.reset(); statusText = ""; chunkIndex = 0; chunkCount = 0
296312
}
297313

298314
// MARK: - Transport (overlay controls)
@@ -313,10 +329,14 @@ final class AppState: ObservableObject {
313329
}
314330
private func stopTimer() { timer?.invalidate(); timer = nil }
315331
private func tick() {
316-
progress = player.progress
317-
chunkProgress = player.chunkFraction
318-
chunkSeconds = player.chunkSeconds
319-
chunkIndex = min(max(1, player.finishedCount + 1), max(1, chunkCount))
332+
telemetry.progress = player.progress
333+
telemetry.chunkProgress = player.chunkFraction
334+
telemetry.chunkSeconds = player.chunkSeconds
335+
// Only assign chunkIndex when the paragraph actually turns — it lives on
336+
// AppState (read by GenerateView/overlay), so a 10 Hz same-value write would
337+
// needlessly fire AppState.objectWillChange and re-render the whole window.
338+
let ci = min(max(1, player.finishedCount + 1), max(1, chunkCount))
339+
if ci != chunkIndex { chunkIndex = ci }
320340
}
321341

322342
var backendIdentity: String { backendKind == .elevenlabs ? "elevenlabs" : "qwen3-local" }
@@ -357,7 +377,7 @@ final class AppState: ObservableObject {
357377
// reformatted paragraphs (web-selected math, etc.).
358378
subtitleText = TextSplitter.cleanInput(displayText ?? t)
359379
chunkSentenceTimes = Array(repeating: [], count: chunks.count)
360-
progress = 0
380+
telemetry.reset()
361381
player.start(expected: chunks.count)
362382
chunkCount = chunks.count; chunkIndex = 0
363383

@@ -423,7 +443,13 @@ final class AppState: ObservableObject {
423443
} catch is CancellationError {
424444
self.finish()
425445
} catch {
426-
self.phase = .idle
446+
// Tear playback down like finish() (stop the timer + player) but keep
447+
// the error message. Without stopTimer() a mid-playback synthesis
448+
// error left the 10 Hz timer running forever, growing memory at idle.
449+
self.stopTimer()
450+
self.player.stop()
451+
self.phase = .idle; self.telemetry.reset()
452+
self.chunkIndex = 0; self.chunkCount = 0
427453
self.statusText = "오류: \(error.localizedDescription)"
428454
}
429455
}
@@ -1003,8 +1029,9 @@ final class AppState: ObservableObject {
10031029
guard let url = cache.fileURL(forKey: e.id) else { statusText = "오디오 파일 없음"; return }
10041030
cache.touch(e.id); historyRevision += 1
10051031
inputText = e.text; currentText = e.text; spokenChunks = [e.text]
1006-
chunkSentenceTimes = [cache.times(forKey: e.id) ?? []]; chunkSeconds = 0
1007-
chunkCount = 1; chunkIndex = 1; progress = 0
1032+
chunkSentenceTimes = [cache.times(forKey: e.id) ?? []]
1033+
telemetry.reset()
1034+
chunkCount = 1; chunkIndex = 1
10081035
player.start(expected: 1)
10091036
player.enqueue(url)
10101037
phase = .playing; statusText = "캐시에서 재생"; startTimer()
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import Foundation
2+
import Combine
3+
4+
/// High-frequency playback telemetry (updated ~10×/s by `AppState.tick`). Split
5+
/// out of `AppState` on purpose: if these ticking values were `@Published` on
6+
/// AppState, every 0.1s write would fire `AppState.objectWillChange`, invalidating
7+
/// EVERY main-window view that observes AppState via `@EnvironmentObject` and
8+
/// piling up SwiftUI observation-tracking allocations that stay reachable and
9+
/// never release (measured: ~250 MB of live `ObservationTracking` dictionaries).
10+
/// Only `PlayerOverlay` observes this object, so the 10 Hz churn is confined to
11+
/// the HUD that actually renders it.
12+
@MainActor
13+
final class PlaybackTelemetry: ObservableObject {
14+
@Published var progress: Double = 0 // 0…1 across all chunks
15+
@Published var chunkProgress: Double = 0 // 0…1 within the current paragraph
16+
@Published var chunkSeconds: Double = 0 // seconds into the current paragraph
17+
18+
/// Reset to the pre-playback state (start of a new sequence / stop / finish).
19+
func reset() { progress = 0; chunkProgress = 0; chunkSeconds = 0 }
20+
}

‎Sources/UI/OverlayWindow.swift‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ final class OverlayWindow {
5151

5252
private func ensurePanel() {
5353
guard panel == nil else { return }
54-
let h = NSHostingView(rootView: PlayerOverlay(app: app))
54+
let h = NSHostingView(rootView: PlayerOverlay(app: app, telemetry: app.telemetry))
5555
let p = NonKeyPanel(contentRect: NSRect(x: 0, y: 0, width: 360, height: 80),
5656
styleMask: [.nonactivatingPanel, .borderless],
5757
backing: .buffered, defer: false)

‎Sources/UI/PlayerOverlay.swift‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import SwiftUI
55
/// navigation.
66
struct PlayerOverlay: View {
77
@ObservedObject var app: AppState
8+
/// The 10 Hz playback values (progress / crawl position) — observed here ONLY,
9+
/// so ticking doesn't re-render the whole app. crawlFraction on `app` reads
10+
/// telemetry.chunkProgress, so observing telemetry keeps the crawl live.
11+
@ObservedObject var telemetry: PlaybackTelemetry
812

913
/// Measured natural height of the full subtitle column (for the crawl mapping).
1014
@State private var contentHeight: CGFloat = 0
@@ -96,9 +100,10 @@ struct PlayerOverlay: View {
96100
// The WHOLE script is one column that scrolls continuously in step
97101
// with playback (paragraphs flow into each other), keeping the
98102
// current sentence centered.
103+
let currentLineID = app.currentCrawlLineID // compute once per frame, not per line
99104
VStack(alignment: .leading, spacing: 4) {
100105
ForEach(app.crawlLines) { line in
101-
let cur = app.isCurrentLine(line)
106+
let cur = line.id == currentLineID
102107
Text(line.text)
103108
.font(.system(size: app.subtitleFontSize))
104109
// distinguish the current line by brightness only (no weight
@@ -139,7 +144,7 @@ struct PlayerOverlay: View {
139144
Button { app.skipNext() } label: { Image(systemName: "forward.fill") }
140145
.disabled(!app.canSkipNext)
141146

142-
ProgressView(value: app.progress).progressViewStyle(.linear)
147+
ProgressView(value: telemetry.progress).progressViewStyle(.linear)
143148
.frame(width: 140)
144149

145150
Button { app.stop() } label: { Image(systemName: "stop.fill") }

0 commit comments

Comments
 (0)