Branchwell

PulseCanvas / app / visionOS / VisionStudio.swift

1import AVFoundation
2import Combine
3import Foundation
4
5@MainActor final class VisionTransport: ObservableObject {
6 @Published var seconds = 0.0
7 @Published var duration = 0.0
8 @Published var playing = false
9}
10
11/// Constructed off the main actor, then transferred once; analysis is read only on the main actor thereafter.
12private struct VisionAnalysis: @unchecked Sendable { let value: SoundtrackAnalyzer }
13
14@MainActor private final class VisionPlaybackCompletion: NSObject, AVAudioPlayerDelegate {
15 var finished: (() -> Void)?
16 nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
17 Task { @MainActor [weak self] in if flag { self?.finished?() } }
18 }
19}
20
21@MainActor final class VisionStudio: ObservableObject {
22 @Published private(set) var project = VisionProject() { didSet { timelineCache = nil } }
23 @Published var selected: UUID?
24 @Published private(set) var loading = false
25 @Published private(set) var needsSoundtrack = false
26 @Published var message: String?
27 @Published var immersiveActive = false
28 @Published var screenDistance: Float = 3
29 @Published var screenHeight: Float = 1.4
30 @Published var volume: Float = 0.7 { didSet { player?.volume = volume } }
31 let render = RenderState()
32 let transport = VisionTransport()
33 private var player: AVAudioPlayer?
34 private(set) var audioURL: URL?
35 private var analyzer: SoundtrackAnalyzer?
36 private var ticker: AnyCancellable?
37 private var poolObserver: AnyCancellable?
38 private var currentScene: Int?
39 private var revision = UUID()
40 private var loadingCount = 0
41 private var started = false
42 private var timelineCache: [StudioSegment]?
43 private let completion = VisionPlaybackCompletion()
44 var onPlaybackFinished: (() -> Void)?
45 var randomizesPlaybackLooks = false
46 private let library: ProjectMPresets
47 private let directory: URL
48 var selectedIndex: Int { project.clips.firstIndex { $0.id == selected } ?? 0 }
49 var selectedScene: Int { project.clips[selectedIndex].scene }
50 var look: VisionLook { project.looks[selectedScene] ?? VisionLook(scene: selectedScene) }
51 var segments: [StudioSegment] {
52 if let timelineCache { return timelineCache }
53 let result = project.segments(duration: transport.duration)
54 timelineCache = result
55 return result
56 }
57 var loopPlayback: Bool {
58 get { project.loopPlayback }
59 set {
60 project.loopPlayback = newValue
61 player?.numberOfLoops = audioLoopCount
62 save()
63 }
64 }
65 private var audioLoopCount: Int {
66 return project.loopPlayback ? -1 : 0
67 }
68
69 init(directory: URL? = nil, library: ProjectMPresets? = nil) {
70 self.library = library ?? .shared
71 self.directory = directory ?? UserDataStorage.documents
72 if let data = try? Data(contentsOf: self.directory.appendingPathComponent("Studio-autosave.json")),
73 let saved = try? JSONDecoder().decode(VisionProject.self, from: data).validated() { project = saved }
74 selected = project.clips.first?.id
75 completion.finished = { [weak self] in self?.onPlaybackFinished?() }
76 self.library.migrateFavoriteAppearances { self.project.looks[$0]?.preset ?? VisualPreset.defaults(for: $0) }
77 applyAppearance()
78 #if os(visionOS)
79 let tickInterval = 1.0 / 60
80 #else
81 let tickInterval = 1.0 / 30
82 #endif
83 poolObserver = self.library.$poolRevision.dropFirst().sink { [weak self] _ in
84 guard let self, self.randomizesPlaybackLooks else { return }
85 _ = self.randomizeTimeline()
86 }
87 ticker = Timer.publish(every: tickInterval, on: .main, in: .common).autoconnect().sink { [weak self] _ in self?.tick() }
88 }
89
90 func start(force: Bool = false) async {
91 guard force || !started else { return }; started = true
92 if let file = project.audioFile, FileManager.default.fileExists(atPath: directory.appendingPathComponent(file).path) {
93 await loadAudio(directory.appendingPathComponent(file), generateTimeline: false)
94 } else if project.externalAudioURL != nil || project.audioFile != nil {
95 player = nil; audioURL = nil
96 transport.duration = project.importedTimeline?.last?.end ?? project.barBoundaries?.last ?? project.beatBoundaries?.last ?? 0
97 transport.seconds = 0; timelineCache = nil; needsSoundtrack = true
98 } else if let bundled = Bundle.main.url(forResource: "PulseCanvas", withExtension: "mp3", subdirectory: "NativeAssets/Audio") {
99 let newSession = project.clips.count == 1 && project.barBoundaries == nil && project.beatBoundaries == nil
100 && project.importedTimeline == nil && project.macProject == nil
101 await loadAudio(bundled, generateTimeline: newSession)
102 }
103 }
104
105 @discardableResult func importAudio(_ url: URL, generateTimeline: Bool = true, title: String? = nil) async -> Bool {
106 let access = url.startAccessingSecurityScopedResource()
107 defer { if access { url.stopAccessingSecurityScopedResource() } }
108 do {
109 let name = UUID().uuidString + "." + url.pathExtension
110 let destination = directory.appendingPathComponent(name)
111 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
112 try FileManager.default.copyItem(at: url, to: destination)
113 guard await loadAudio(destination, generateTimeline: generateTimeline) else {
114 try? FileManager.default.removeItem(at: destination); return false
115 }
116 project.audioFile = name; project.audioTitle = title ?? url.deletingPathExtension().lastPathComponent
117 project.externalAudioURL = url; save()
118 return true
119 } catch { message = error.localizedDescription; return false }
120 }
121
122 @discardableResult private func loadAudio(_ url: URL, generateTimeline: Bool) async -> Bool {
123 let token = UUID(); revision = token; loadingCount += 1; loading = true
124 defer { loadingCount -= 1; loading = loadingCount > 0 }
125 do {
126 let prepared = try await Task.detached(priority: .userInitiated) { VisionAnalysis(value: try SoundtrackAnalyzer(url: url)) }.value
127 try Task.checkCancellation()
128 guard revision == token else { return false }
129 let next = try AVAudioPlayer(contentsOf: url)
130 guard next.duration.isFinite, next.duration > 0 else { throw CocoaError(.fileReadCorruptFile) }
131 if !generateTimeline, let end = project.importedTimeline?.last?.end, next.duration + 0.05 < end {
132 throw ProjectMError("This soundtrack is shorter than the saved timeline. Locate the original song, or import new audio to start a new timeline.")
133 }
134 next.numberOfLoops = audioLoopCount
135 next.delegate = completion
136 next.prepareToPlay(); next.volume = volume
137 player?.stop(); player = next; analyzer = prepared.value; audioURL = url; needsSoundtrack = false
138 transport.duration = next.duration; timelineCache = nil; transport.seconds = 0; transport.playing = false
139 let plan = prepared.value.segmentPlan()
140 let barPlan = prepared.value.segmentPlan(beatsPerSection: 4)
141 project.barBoundaries = barPlan.boundaries
142 project.beatBoundaries = nil
143 project.bpm = min(300, max(20, barPlan.bpm ?? 120))
144 let choices = self.library.pool.enabled ? self.library.eligibleScenes : NativeEffects.timelineOrder
145 if generateTimeline {
146 let sequence = choices.isEmpty ? [selectedScene] : choices
147 project.importedTimeline = nil
148 project.externalAudioURL = nil
149 project.clips = plan.boundaries.dropLast().enumerated().map {
150 VisionClip(scene: sequence[$0.offset % sequence.count])
151 }
152 if project.clips.isEmpty { project.clips = [VisionClip(scene: NativeEffects.defaultScene)] }
153 for scene in Set(project.clips.map(\.scene)) where project.looks[scene] == nil {
154 project.looks[scene] = VisionLook(library.appearanceForSelection(scene))
155 }
156 selected = project.clips.first?.id
157 }
158 if project.importedTimeline == nil { project.fitTimeline(duration: next.duration) }
159 applyAppearance(); save(); tick(); return true
160 } catch { if revision == token { message = error.localizedDescription }; return false }
161 }
162
163 /// Radio owns its verified cache; do not duplicate each download into Documents.
164 @discardableResult func loadRadioAudio(_ url: URL, title: String) async -> Bool {
165 guard await loadAudio(url, generateTimeline: true) else { return false }
166 project.audioFile = nil; project.audioTitle = title; save(); return true
167 }
168
169 func togglePlayback() {
170 guard !loading, let player else { return }
171 if player.isPlaying { player.pause() } else {
172 do {
173 #if os(visionOS)
174 try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
175 try AVAudioSession.sharedInstance().setActive(true)
176 #endif
177 if player.currentTime >= player.duration - 0.05 { player.currentTime = 0 }
178 player.play()
179 } catch { message = String(localized: "Audio playback couldn't start: \(error.localizedDescription)") }
180 }
181 transport.playing = player.isPlaying; render.paused = !player.isPlaying
182 }
183 func seek(_ seconds: Double) {
184 guard seconds.isFinite else { return }
185 player?.currentTime = min(transport.duration, max(0, seconds)); transport.seconds = player?.currentTime ?? 0; tick()
186 }
187 func select(_ clip: VisionClip) {
188 selected = clip.id
189 let index = selectedIndex
190 if segments.indices.contains(index) { seek(segments[index].start) }
191 applyAppearance()
192 }
193 func assign(_ scene: Int) {
194 assign(scene, to: project.clips[selectedIndex].id)
195 }
196 /// Picker edits target a stable clip ID even after playback follows a later section.
197 func assign(_ scene: Int, to clipID: UUID) {
198 guard library.eligibleScenes.contains(scene), let index = project.clips.firstIndex(where: { $0.id == clipID }) else { return }
199 project.looks[scene] = VisionLook(library.appearanceForSelection(scene))
200 project.clips[index].scene = scene
201 if scene == selectedScene { applyAppearance() }
202 save()
203 }
204 func look(for clipID: UUID) -> VisionLook? {
205 guard let scene = project.clips.first(where: { $0.id == clipID })?.scene else { return nil }
206 return project.looks[scene] ?? VisionLook(scene: scene)
207 }
208 private func targetScene(for clipID: UUID?) -> Int? {
209 if let clipID { return project.clips.first(where: { $0.id == clipID })?.scene }
210 return selectedScene
211 }
212 /// New choices get fresh looks; favorites restore their saved appearance.
213 @discardableResult func randomizeVisualizer(for clipID: UUID? = nil) -> Bool {
214 guard let scene = targetScene(for: clipID) else { return false }
215 let eligible = library.eligibleScenes
216 let different = eligible.filter { $0 != scene }
217 guard let next = (different.isEmpty ? eligible : different).randomElement() else { return false }
218 assign(next, to: clipID ?? project.clips[selectedIndex].id)
219 return true
220 }
221 /// The Mac's scene dealer handles the shared category/favorites pool and repeat policy.
222 /// Commit both choices together; failures leave timing, selection and saved appearances intact.
223 @discardableResult func randomizeTimeline(visualizers: Bool = true, barLengths: Bool = false,
224 chooseLength: () -> Int = { Int.random(in: 1...8) }) -> Bool {
225 guard !loading, !needsSoundtrack, transport.duration > 0,
226 !project.clips.isEmpty, visualizers || barLengths else { return false }
227 var next = project
228 if barLengths, !next.randomizeBars(duration: transport.duration, chooseLength: chooseLength) { return false }
229 if visualizers {
230 guard let scenes = StudioTimeline.randomizedScenes(current: next.clips.map(\.scene),
231 favorites: [], available: library.eligibleScenes, allowRepeats: library.pool.enabled) else { return false }
232 for scene in Set(scenes) { next.looks[scene] = VisionLook(library.appearanceForSelection(scene)) }
233 for index in next.clips.indices { next.clips[index].scene = scenes[index] }
234 }
235 project = next
236 followTimingChange(); applyAppearance(); save()
237 return true
238 }
239 func randomizeLook(for clipID: UUID? = nil) {
240 updateLook(for: clipID) { $0 = VisionLook(.randomized(strobeEnabled: $0.strobeEnabled)) }
241 }
242
243 func updateLook(for clipID: UUID? = nil, _ body: (inout VisionLook) -> Void) {
244 guard let scene = targetScene(for: clipID) else { return }
245 var value = project.looks[scene] ?? VisionLook(scene: scene); body(&value)
246 guard value.isValid else { return }
247 project.looks[scene] = value
248 if scene == selectedScene { applyAppearance() }
249 save()
250 }
251 func resetLook(for clipID: UUID? = nil) {
252 guard let scene = targetScene(for: clipID) else { return }
253 project.looks[scene] = VisionLook(scene: scene)
254 if scene == selectedScene { applyAppearance() }
255 save()
256 }
257 func bars(_ value: Int, clip: UUID) {
258 guard let i = project.clips.firstIndex(where: { $0.id == clip }), (1...64).contains(value) else { return }
259 project.importedTimeline = nil
260 project.clips[i].bars = value; project.fitTimeline(duration: transport.duration)
261 followTimingChange(); save()
262 }
263 func applyCommonSettings(_ settings: VisionCommonSettings) {
264 guard settings.isValid else { return }
265 var next = project
266 if let bars = settings.bars {
267 next.importedTimeline = nil
268 for index in next.clips.indices { next.clips[index].bars = bars }
269 next.fitTimeline(duration: transport.duration)
270 }
271 for scene in NativeEffects.activeIDs {
272 var look = next.looks[scene] ?? VisionLook(scene: scene)
273 if let value = settings.chaos { look.chaos = value }
274 if let value = settings.zoomSpeed { look.zoomSpeed = value }
275 if let value = settings.motionSpeed { look.speed = value }
276 if let value = settings.strobeEnabled { look.strobeEnabled = value }
277 if let value = settings.strobeSensitivity { look.strobeSensitivity = value }
278 if let value = settings.strobeStrength { look.strobeStrength = value }
279 if look != (next.looks[scene] ?? VisionLook(scene: scene)) { next.looks[scene] = look }
280 }
281 project = next; followTimingChange(); applyAppearance(); save()
282 }
283 private func followTimingChange() {
284 if let index = StudioTimeline.index(at: transport.seconds, in: segments), project.clips.indices.contains(index) {
285 selected = project.clips[index].id; applyAppearance()
286 }
287 }
288 func addClip() {
289 guard project.clips.count < 10_000 else { return }
290 guard let next = self.library.eligibleScenes.first(where: { $0 != selectedScene }) ?? self.library.eligibleScenes.first else { return }
291 project.looks[next] = VisionLook(library.appearanceForSelection(next))
292 let clip = VisionClip(scene: next); project.clips.insert(clip, at: selectedIndex + 1); selected = clip.id
293 project.importedTimeline = nil
294 applyAppearance(); save()
295 }
296 func removeClip() {
297 guard project.clips.count > 1 else { return }
298 let index = selectedIndex; project.clips.remove(at: index)
299 project.importedTimeline = nil
300 selected = project.clips[min(index, project.clips.count - 1)].id; applyAppearance(); save()
301 }
302 func moveClip(_ offset: Int) {
303 let i = selectedIndex, next = i + offset
304 guard project.clips.indices.contains(next) else { return }
305 project.clips.swapAt(i, next); save()
306 }
307 func replaceProject(_ value: VisionProject) async {
308 do { let validated = try value.validated(); suspend(); project = validated; selected = project.clips.first?.id; applyAppearance(); save(); await start(force: true) }
309 catch { message = error.localizedDescription }
310 }
311 func suspend() { player?.pause(); transport.playing = false; render.paused = true }
312 func saveExportFormat(aspect: String, resolution: Int, fps: Int) {
313 guard [720, 1080, 2160].contains(resolution), [24, 30, 60].contains(fps) else { return }
314 project.exportAspect = aspect; project.exportResolution = resolution; project.exportFPS = fps; save()
315 }
316
317 private func applyAppearance() {
318 let look = self.look
319 render.scene = selectedScene; currentScene = selectedScene
320 render.speed = look.speed; render.zoomSpeed = look.zoomSpeed; render.chaos = look.chaos
321 render.brightness = look.brightness; render.particleSize = look.size; render.liquidDetail = look.detail
322 render.fog = look.fog; render.zoom = look.zoom; render.palette = look.palette
323 render.strobeEnabled = look.strobeEnabled; render.strobeSensitivity = look.strobeSensitivity
324 render.strobeStrength = look.strobeStrength
325 render.rotation = look.rotation; render.motionBlur = look.motionBlur; render.haloCount = look.haloCount
326 }
327 private func tick() {
328 guard let player else { return }
329 let time = player.currentTime
330 if abs(time - transport.seconds) >= 0.1 { transport.seconds = time }
331 if transport.playing != player.isPlaying { transport.playing = player.isPlaying }
332 render.paused = !player.isPlaying; render.playbackTime = time
333 if player.isPlaying, let index = StudioTimeline.index(at: time, in: segments), project.clips.indices.contains(index) {
334 let clip = project.clips[index]
335 if selected != clip.id { selected = clip.id }
336 if currentScene != clip.scene {
337 if randomizesPlaybackLooks { project.looks[clip.scene] = VisionLook(library.appearanceForSelection(clip.scene)) }
338 applyAppearance()
339 }
340 }
341 if let features = try? analyzer?.frame(at: time, clipStart: 0, clipEnd: player.duration) {
342 render.audioBands = features.bands; render.audioPulse = features.pulse; render.audioSwell = features.swell
343 render.audioEnvelopes = features.envelopes; render.audioMomentum = features.momentum
344 render.audioBeatMotionTime = features.beatMotionTime; render.audioTreblePulse = features.treblePulse
345 render.audioTrebleAttackTime = features.trebleAttackTime
346 }
347 }
348 func prepareProjectIdentity() {
349 if project.cloudProjectID == nil { project.cloudProjectID = UUID().uuidString; save() }
350 }
351 private func save() {
352 do {
353 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
354 try JSONEncoder().encode(project).write(to: directory.appendingPathComponent("Studio-autosave.json"), options: .atomic)
355 if directory.standardizedFileURL == UserDataStorage.documents.standardizedFileURL {
356 publishCloudLooks()
357 }
358 } catch { message = String(localized: "Couldn't save this Studio session: \(error.localizedDescription)") }
359 }
360 func publishCloudLooks() {
361 let looks = Dictionary(uniqueKeysWithValues: project.looks.map { ("native:\($0.key)", $0.value.preset) })
362 if let data = try? JSONEncoder().encode(looks) {
363 UserDefaults.standard.set(data, forKey: "PulseCanvas.cloudLooks.v1")
364 NotificationCenter.default.post(name: .pulseCanvasUserDataChanged, object: nil)
365 }
366 }
367 func reloadCloudLooks() {
368 guard let data = UserDefaults.standard.data(forKey: "PulseCanvas.cloudLooks.v1"),
369 let values = try? JSONDecoder().decode([String: VisualPreset].self, from: data) else { return }
370 var updated = project.looks.filter { !NativeEffects.activeIDs.contains($0.key) || values["native:\($0.key)"] != nil }
371 for (key, value) in values where key.hasPrefix("native:") && value.isValid {
372 guard let scene = Int(key.dropFirst(7)), NativeEffects.activeIDs.contains(scene) else { continue }
373 updated[scene] = VisionLook(value)
374 }
375 if updated != project.looks {
376 project.looks = updated
377 if !transport.playing { applyAppearance() }
378 save()
379 }
380 }
381}