Branchwell

PulseCanvas / app / Sources / PulseCanvas / AudioController.swift

1import Foundation
2import AVFoundation
3import Combine
4
5/// A single project soundtrack, with real PCM analysis for the preview.
6@MainActor
7final class AudioController: ObservableObject {
8 @Published private(set) var selectedURL: URL?
9 @Published private(set) var title = String(localized: "Add a soundtrack")
10 @Published private(set) var duration = 0.0
11 @Published private(set) var isPlaying = false
12 private(set) var progress = 0.0
13 private(set) var playbackSeconds = 0.0
14 @Published private(set) var status = String(localized: "Choose music to sync your visuals")
15 private(set) var spectrum = [Float](repeating: 0, count: 32)
16 private(set) var beatPulse: Float = 0
17 private(set) var trebleAttackTime: Double? = nil
18 private(set) var treblePulse: Float = 0
19 private(set) var momentum: Float = 0
20 private(set) var beatMotionTime: Double = 0
21 private(set) var envelopes = SIMD4<Float>(repeating: 0)
22 private(set) var swell: Float = 0
23 @Published private(set) var previewSectionStart: Double?
24 // High-rate audio data bypasses ObservableObject; only playback widgets observe it.
25 let visualizationUpdated = PassthroughSubject<Void, Never>()
26 private var visualizationEnabled = true
27 private var lastBackgroundProgressRefresh: TimeInterval = 0
28 /// Background listening keeps its playback clock and completion callbacks,
29 /// without spending CPU on audio features for an invisible renderer.
30 func setVisualizationEnabled(_ enabled: Bool) {
31 visualizationEnabled = enabled
32 if enabled { updateProgress() }
33 }
34 private var previewSectionEnd: Double?
35 @Published var loopEnabled = true
36 /// Radio owns full-song completion; bounded Studio previews still loop normally.
37 var onSoundtrackFinished: (() -> Void)?
38 @Published var volume: Float = 0.7 { didSet { engine.mainMixerNode.outputVolume = min(1, max(0, volume)) } }
39 private let engine = AVAudioEngine()
40 private let player = AVAudioPlayerNode()
41 private var file: AVAudioFile?
42 private var analyzer: SoundtrackAnalyzer?
43 private var segmentStart: AVAudioFramePosition = 0
44 private var generation = UUID()
45 private var timer: Timer?
46 private var attemptedDefaultSoundtrack = false
47 private var soundtrackAccess: SecurityScopedAccess?
48 private(set) var soundtrackBookmark: Data?
49
50 init() {
51 engine.attach(player)
52 engine.connect(player, to: engine.mainMixerNode, format: nil)
53 engine.mainMixerNode.outputVolume = volume
54 timer = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in
55 Task { @MainActor [weak self] in self?.updateProgress(fromTimer: true) }
56 }
57 RunLoop.main.add(timer!, forMode: .common)
58 }
59
60 @discardableResult
61 func loadDefaultSoundtrackIfNeeded() -> Bool {
62 guard !attemptedDefaultSoundtrack else { return selectedURL != nil }
63 attemptedDefaultSoundtrack = true
64 guard selectedURL == nil else { return true }
65 guard let url = BundledSoundtrack.url else { return false }
66 return load(url: url)
67 }
68
69 @discardableResult
70 func load(url: URL, bookmark: Data? = nil) -> Bool {
71 do {
72 let url = SecurityScopedAccess.resolve(bookmark: bookmark, fallback: url)
73 return install(try PreparedSoundtrack(url: url))
74 } catch { status = String(localized: "Cannot open soundtrack: \(error.localizedDescription)"); return false }
75 }
76
77 /// Prepared on a worker, then transferred exclusively to the playback actor.
78 @discardableResult
79 func install(_ prepared: PreparedSoundtrack, title displayTitle: String? = nil) -> Bool {
80 do {
81 let opened = prepared.file, url = prepared.url
82 stop()
83 analyzer = prepared.analyzer
84 file = opened
85 engine.disconnectNodeOutput(player)
86 engine.connect(player, to: engine.mainMixerNode, format: opened.processingFormat)
87 engine.prepare()
88 #if os(macOS)
89 try engine.start()
90 #endif
91 soundtrackAccess = prepared.access
92 soundtrackBookmark = BundledSoundtrack.identifier(for: url) == nil ? try? prepared.access.readOnlyBookmark() : nil
93 selectedURL = url
94 title = displayTitle ?? url.deletingPathExtension().lastPathComponent
95 duration = Double(opened.length) / opened.processingFormat.sampleRate
96 schedule(from: 0, playing: false)
97 analyze(frame: 0)
98 status = String(localized: "Soundtrack ready")
99 return true
100 } catch { status = String(localized: "Cannot open soundtrack: \(error.localizedDescription)"); return false }
101 }
102
103 /// Retain the already analyzed Studio song while Radio temporarily owns playback.
104 /// The snapshot is used on the same actor after Radio has stopped its player.
105 func retainedSoundtrack() -> PreparedSoundtrack? {
106 guard let url = selectedURL, let access = soundtrackAccess, let file, let analyzer else { return nil }
107 return PreparedSoundtrack(url: url, access: access, file: file, analyzer: analyzer)
108 }
109
110 func clear() {
111 stop(); file = nil; analyzer = nil; selectedURL = nil; title = String(localized: "Add a soundtrack"); duration = 0
112 soundtrackAccess = nil; soundtrackBookmark = nil
113 engine.stop(); status = String(localized: "Choose music to sync your visuals")
114 }
115
116 func segmentPlan(beatsPerSection: Int = 16) -> SongSegmentation? { analyzer?.segmentPlan(beatsPerSection: beatsPerSection) }
117
118 private func startPlaybackEngine() -> Bool {
119 do {
120 #if !os(macOS)
121 try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
122 try AVAudioSession.sharedInstance().setActive(true)
123 #endif
124 if !engine.isRunning { try engine.start() }
125 return true
126 } catch { status = String(localized: "Audio playback couldn't start: \(error.localizedDescription)"); return false }
127 }
128 func playPause() {
129 guard file != nil else { return }
130 if !isPlaying && !startPlaybackEngine() { return }
131 if isPlaying { updateProgress(); player.pause(); isPlaying = false; status = String(localized: "Paused") }
132 else {
133 if progress >= 0.9999 { schedule(from: 0, playing: true) }
134 else {
135 if previewSectionStart != nil { seek(fraction: progress) }
136 player.play(); isPlaying = true
137 }
138 status = String(localized: "Playing soundtrack")
139 }
140 }
141
142 /// Leave any bounded section preview and play the complete Studio timeline.
143 func playFullSoundtrack() {
144 guard file != nil else { return }
145 seek(fraction: progress >= 0.9999 ? 0 : progress)
146 if !isPlaying { playPause() }
147 }
148
149 func pause() { if isPlaying { playPause() } }
150
151 func stop() {
152 generation = UUID(); player.stop(); isPlaying = false; segmentStart = 0
153 previewSectionStart = nil; previewSectionEnd = nil
154 progress = 0; playbackSeconds = 0; spectrum = [Float](repeating: 0, count: 32); beatPulse = 0; momentum = 0; beatMotionTime = 0; envelopes = .zero; swell = 0; treblePulse = 0; trebleAttackTime = nil
155 visualizationUpdated.send()
156 }
157
158 /// Loop the selected section until paused or replaced; style controls restart it.
159 func playSection(start: Double, end: Double, restart: Bool = false) {
160 guard let file, start.isFinite, end.isFinite, start >= 0, end > start, end <= duration + 0.001 else { return }
161 if !restart && isPlaying && previewSectionStart == start { pause(); return }
162 let rate = file.processingFormat.sampleRate
163 let first = min(file.length - 1, AVAudioFramePosition(start == 0 ? 0 : ceil((start * rate).nextUp)))
164 let last = min(file.length, AVAudioFramePosition(end * rate))
165 guard last > first else { return }
166 previewSectionStart = start; previewSectionEnd = end
167 progress = Double(first) / Double(file.length); playbackSeconds = Double(first) / rate
168 analyze(frame: first)
169 schedule(from: first, playing: true, end: last)
170 status = String(localized: "Playing Studio section · Looping")
171 }
172
173 /// Selecting a card preserves playback: switch a running loop, or seek while paused.
174 func selectSection(start: Double, end: Double) {
175 guard file != nil, start.isFinite, end.isFinite, start >= 0, end > start, end <= duration + 0.001 else { return }
176 if isPlaying { playSection(start: start, end: end, restart: true) }
177 else { seekToSection(start: start) }
178 }
179
180 func seek(fraction: Double) {
181 guard let file else { return }
182 let fraction = min(1, max(0, fraction))
183 seek(frame: min(file.length - 1, AVAudioFramePosition(fraction * Double(file.length))))
184 }
185
186 func seekToSection(start: Double) {
187 guard let file, start.isFinite, start >= 0, start < duration else { return }
188 let rate = file.processingFormat.sampleRate
189 // Stay inside the selected section when its boundary lies between samples.
190 let first = start == 0 ? 0 : ceil((start * rate).nextUp)
191 seek(frame: min(file.length - 1, AVAudioFramePosition(first)))
192 }
193
194 private func seek(frame: AVAudioFramePosition) {
195 guard let file else { return }
196 previewSectionStart = nil; previewSectionEnd = nil
197 schedule(from: frame, playing: isPlaying)
198 progress = Double(frame) / Double(file.length)
199 playbackSeconds = Double(frame) / file.processingFormat.sampleRate
200 analyze(frame: frame)
201 }
202
203 func visualizationPCM(at time: Double) -> [Float] { (try? analyzer?.pcm(at: time)) ?? [] }
204
205 private func analyze(frame: AVAudioFramePosition) {
206 defer { visualizationUpdated.send() }
207 guard visualizationEnabled else { return }
208 guard let file, let analyzer else { return }
209 do {
210 let features = try analyzer.frame(at: Double(frame) / file.processingFormat.sampleRate,
211 clipStart: 0, clipEnd: duration)
212 spectrum = features.bands
213 beatPulse = features.pulse
214 momentum = features.momentum
215 beatMotionTime = features.beatMotionTime
216 envelopes = features.envelopes; swell = features.swell
217 trebleAttackTime = features.trebleAttackTime
218 treblePulse = features.treblePulse
219 } catch {
220 spectrum = [Float](repeating: 0, count: 32); beatPulse = 0; momentum = 0; beatMotionTime = 0; envelopes = .zero; swell = 0; treblePulse = 0; trebleAttackTime = nil
221 status = String(localized: "Audio analysis failed: \(error.localizedDescription)")
222 }
223 }
224
225 private func schedule(from start: AVAudioFramePosition, playing: Bool, end: AVAudioFramePosition? = nil) {
226 guard let file else { return }
227 if playing && !startPlaybackEngine() { return }
228 if end == nil { previewSectionStart = nil; previewSectionEnd = nil }
229 generation = UUID(); let token = generation
230 player.stop(); segmentStart = start
231 let remaining = AVAudioFrameCount(min(Int64(UInt32.max), (end ?? file.length) - start))
232 player.scheduleSegment(file, startingFrame: start, frameCount: remaining, at: nil, completionCallbackType: .dataPlayedBack) { [weak self] _ in
233 Task { @MainActor [weak self] in
234 guard let self, self.generation == token else { return }
235 if let end {
236 guard self.isPlaying else { return }
237 self.schedule(from: start, playing: true, end: end)
238 self.playbackSeconds = Double(start) / file.processingFormat.sampleRate
239 self.progress = self.playbackSeconds / self.duration
240 self.analyze(frame: start)
241 self.status = String(localized: "Playing Studio section · Looping")
242 return
243 }
244 let finished = self.isPlaying ? self.onSoundtrackFinished : nil
245 if self.isPlaying && self.loopEnabled && finished == nil {
246 self.schedule(from: 0, playing: true)
247 self.progress = 0; self.playbackSeconds = 0
248 self.analyze(frame: 0)
249 self.status = String(localized: "Playing soundtrack · Looping")
250 return
251 }
252 self.isPlaying = false; self.progress = 1; self.playbackSeconds = self.duration
253 self.beatPulse = 0; self.momentum = 0; self.envelopes = .zero; self.swell = 0; self.treblePulse = 0; self.trebleAttackTime = nil; self.spectrum = [Float](repeating: 0, count: 32)
254 self.visualizationUpdated.send()
255 self.status = String(localized: "End of soundtrack")
256 finished?()
257 }
258 }
259 if playing { player.play() }
260 isPlaying = playing
261 }
262
263 private func updateProgress(fromTimer: Bool = false) {
264 if fromTimer && !visualizationEnabled {
265 let now = ProcessInfo.processInfo.systemUptime
266 guard now - lastBackgroundProgressRefresh >= 1 else { return }
267 lastBackgroundProgressRefresh = now
268 }
269 guard isPlaying, let file, let time = player.lastRenderTime, let position = player.playerTime(forNodeTime: time) else { return }
270 playbackSeconds = min(previewSectionEnd.map { max(0, $0 - 1 / file.processingFormat.sampleRate) } ?? duration, max(0, Double(segmentStart) / file.processingFormat.sampleRate + max(0, Double(position.sampleTime) / file.processingFormat.sampleRate - player.outputPresentationLatency)))
271 progress = duration > 0 ? playbackSeconds / duration : 0
272 analyze(frame: AVAudioFramePosition(playbackSeconds * file.processingFormat.sampleRate))
273 }
274}
275
276/// The worker must relinquish this object before the main actor installs it.
277/// AVAudioFile and its analyzer are never accessed concurrently.
278final class PreparedSoundtrack: @unchecked Sendable {
279 let url: URL
280 let access: SecurityScopedAccess
281 let file: AVAudioFile
282 let analyzer: SoundtrackAnalyzer
283 fileprivate init(url: URL, access: SecurityScopedAccess, file: AVAudioFile, analyzer: SoundtrackAnalyzer) {
284 self.url = url; self.access = access; self.file = file; self.analyzer = analyzer
285 }
286 init(url: URL) throws {
287 self.url = url
288 access = SecurityScopedAccess(url: url)
289 file = try AVAudioFile(forReading: url)
290 guard file.length > 0 else { throw SoundtrackError.empty }
291 analyzer = try SoundtrackAnalyzer(url: url)
292 }
293}
294
295private enum SoundtrackError: LocalizedError {
296 case empty
297 var errorDescription: String? { String(localized: "This file has no audio samples.") }
298}