Branchwell

PulseCanvas / app · pulsecanvas.ai / mobile / MobileEditor.swift

Raw 16.5 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1import AVFoundation
2import Combine
3import Foundation
4#if DEBUG
5import CryptoKit
6#endif
7
8/// The iPhone/iPad UI uses the production Mac audio, Studio, Radio and export models.
9@MainActor final class MobileEditor: ObservableObject {
10 let render = RenderState()
11 let audio = AudioController()
12 let studio = StudioStore()
13 let radio: RadioController
14 let exporter = SocialExportController()
15 let library = ProjectMPresets.shared
16 @Published var loading = false
17 @Published var message: String?
18 @Published var presenting = false
19 @Published var selectedTab = 0
20 @Published var needsSoundtrack = false
21 private var pendingProject: CreatorProject?
22 private var observations = Set<AnyCancellable>()
23 private var started = false
24 private var foreground = true
25 private var playbackSession: MobilePlaybackSession?
26 private let documents: URL
27 private var autosave: URL { documents.appendingPathComponent("Studio-autosave.pulsecanvas") }
28
29 init() {
30 let base = UserDataStorage.documents
31 #if DEBUG
32 let qa = ProcessInfo.processInfo.arguments.contains("-PCMobileQA")
33 documents = qa
34 ? FileManager.default.temporaryDirectory.appendingPathComponent("Mobile-QA-\(UUID().uuidString)") : base
35 if qa {
36 ProjectMPresets.shared.setRandomizerGroup(.all)
37 let suite = "PulseCanvas.MobileRadio.QA"
38 let defaults = UserDefaults(suiteName: suite)!
39 defaults.removePersistentDomain(forName: suite)
40 radio = RadioController(defaults: defaults)
41 } else { radio = RadioController() }
42 #else
43 documents = base
44 radio = RadioController()
45 #endif
46 radio.attach(audio: audio)
47 playbackSession = MobilePlaybackSession(audio: audio, radio: radio)
48 studio.apply(to: render)
49 audio.visualizationUpdated.sink { [weak self] in self?.tick() }.store(in: &observations)
50 studio.$segments.dropFirst().debounce(for: .milliseconds(500), scheduler: RunLoop.main)
51 .sink { [weak self] _ in self?.saveSession() }.store(in: &observations)
52 studio.$presets.dropFirst().debounce(for: .milliseconds(500), scheduler: RunLoop.main)
53 .sink { [weak self] _ in self?.saveSession() }.store(in: &observations)
54 }
55 var currentRender: RenderState { selectedTab == 1 ? radio.visualizer : render }
56
57 func favoritePreviewVisualizer() -> Bool {
58 guard !loading, !exporter.isExporting else { return false }
59 return library.favorite(currentRender.scene, appearance: VisualPreset(render: currentRender))
60 }
61
62 /// Change only the current look. Audio and Studio scene boundaries stay intact.
63 func randomizePreviewVisualizer() {
64 guard !loading, !exporter.isExporting else { return }
65 if selectedTab == 1 { radio.randomizeCurrentVisualizer() }
66 else {
67 studio.randomizeScene(render)
68 saveSession()
69 }
70 }
71
72 func start() async {
73 guard !started else { return }; started = true
74 do { try await Task.detached {
75 let session = AVAudioSession.sharedInstance()
76 try session.setCategory(.playback, mode: .default)
77 }.value }
78 catch { message = String(localized: "Audio could not start: \(error.localizedDescription)") }
79 studio.isStudio = true
80 if let data = try? Data(contentsOf: autosave) {
81 await openProject(data); return
82 }
83 if let demo = BundledSoundtrack.url {
84 #if DEBUG
85 if ProcessInfo.processInfo.arguments.contains("-PCMobileQA") && !ProcessInfo.processInfo.arguments.contains("-PCMobileFullSoundtrackQA") {
86 do {
87 try FileManager.default.createDirectory(at: documents, withIntermediateDirectories: true)
88 let sample = documents.appendingPathComponent("Demo.m4a")
89 guard let export = AVAssetExportSession(asset: AVURLAsset(url: demo), presetName: AVAssetExportPresetAppleM4A) else { throw CocoaError(.fileReadCorruptFile) }
90 let radioQA = ProcessInfo.processInfo.arguments.contains("-PCMobileRadioQA")
91 let seconds = radioQA ? 30.0 : 8.0
92 export.timeRange = CMTimeRange(start: .zero, duration: CMTime(seconds: seconds, preferredTimescale: 600))
93 try await export.export(to: sample, as: .m4a)
94 await load(sample, copy: false)
95 if radioQA {
96 let data = try Data(contentsOf: sample)
97 let track = RadioTrack(id: "00000000-0000-4000-8000-000000000001", title: "Radio test soundtrack", genre: "Electronic", duration: seconds,
98 audio: sample.lastPathComponent, sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteCount: data.count)
99 let url = documents.appendingPathComponent("catalog.json")
100 let second = RadioTrack(id: "00000000-0000-4000-8000-000000000002", title: "Radio test soundtrack 2", genre: track.genre, duration: track.duration,
101 audio: track.audio, sha256: track.sha256, byteCount: track.byteCount)
102 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Test Radio", tracks: [track, second])).write(to: url)
103 if ProcessInfo.processInfo.arguments.contains("-PCMobileStationsQA") {
104 let genreURL = documents.appendingPathComponent("genre.json")
105 try JSONEncoder().encode(RadioCatalog(version: 1, title: "Test Electronic", tracks: [second])).write(to: genreURL)
106 let directoryURL = documents.appendingPathComponent("stations.json")
107 try JSONEncoder().encode(RadioStationDirectory(version: 1, stations: [
108 RadioStation(id: "all-music", title: "All music", description: "Test library", catalog: url.lastPathComponent),
109 RadioStation(id: "electronic", title: "Electronic", description: "Test station", catalog: genreURL.lastPathComponent)
110 ])).write(to: directoryURL)
111 radio.loadCatalog(at: directoryURL)
112 return
113 }
114 if ProcessInfo.processInfo.arguments.contains("-PCMobileFolderQA") {
115 selectedTab = 1
116 let album = documents.appendingPathComponent("My album")
117 try FileManager.default.createDirectory(at: album, withIntermediateDirectories: true)
118 try FileManager.default.copyItem(at: sample, to: album.appendingPathComponent("Personal song.m4a"))
119 radio.loadCatalog(at: url)
120 // Keep the real asynchronous import path; isolated QA preferences/storage only.
121 Task { @MainActor in
122 while radio.isCatalogLoading { try? await Task.sleep(for: .milliseconds(50)) }
123 radio.importMusicFolder(album, into: documents.appendingPathComponent("PersonalRadio"))
124 }
125 } else { radio.loadCatalog(at: url) }
126 }
127 return
128 } catch { message = error.localizedDescription; return }
129 }
130 #endif
131 await load(demo, copy: false)
132 }
133 }
134 func importAudio(_ url: URL) async {
135 radio.leave(); selectedTab = 0
136 await load(url, copy: true)
137 }
138 func importLibrarySong(_ url: URL, title: String) async throws {
139 guard !loading, !exporter.isExporting else { throw CocoaError(.userCancelled) }
140 loading = true
141 defer { loading = false }
142 let folder = documents.appendingPathComponent("StudioMusic", isDirectory: true)
143 let prepared = try await Task.detached(priority: .userInitiated) {
144 let copy = try StudioMusicStorage.copy(url, title: title, into: folder)
145 do { return try PreparedSoundtrack(url: copy) }
146 catch { try? FileManager.default.removeItem(at: copy.deletingLastPathComponent()); throw error }
147 }.value
148 do { try Task.checkCancellation() }
149 catch { try? FileManager.default.removeItem(at: prepared.url.deletingLastPathComponent()); throw error }
150 radio.leave()
151 guard audio.install(prepared, title: title) else { throw CocoaError(.fileReadCorruptFile) }
152 selectedTab = 0; pendingProject = nil; needsSoundtrack = false
153 studio.isStudio = true; studio.segments = []
154 if let plan = audio.segmentPlan() { studio.makeTimeline(plan, render: render) }
155 loading = false; tick(); saveSession()
156 }
157 private func load(_ url: URL, copy: Bool) async {
158 guard !loading else { return }; loading = true
159 defer { loading = false }
160 let lease = SecurityScopedAccess(url: url)
161 do {
162 try FileManager.default.createDirectory(at: documents, withIntermediateDirectories: true)
163 let destination = copy ? documents.appendingPathComponent(UUID().uuidString + "." + url.pathExtension) : url
164 let prepared = try await Task.detached(priority: .userInitiated) {
165 if copy { try FileManager.default.copyItem(at: url, to: destination) }
166 do { return try PreparedSoundtrack(url: destination) }
167 catch { if copy { try? FileManager.default.removeItem(at: destination) }; throw error }
168 }.value
169 let title = BundledSoundtrack.identifier(for: url) == nil ? url.deletingPathExtension().lastPathComponent : "PulseCanvas"
170 guard audio.install(prepared, title: title) else {
171 throw CocoaError(.fileReadCorruptFile)
172 }
173 if let project = pendingProject {
174 try apply(project); pendingProject = nil; needsSoundtrack = false
175 } else {
176 studio.segments = []
177 if let plan = audio.segmentPlan() { studio.makeTimeline(plan, render: render) }
178 }
179 tick(); saveSession()
180 } catch { message = error.localizedDescription }
181 withExtendedLifetime(lease) {}
182 }
183 func choose(_ scene: Int) {
184 guard library.eligibleScenes.contains(scene), !exporter.isExporting else { return }
185 radio.leave(); studio.selectScene(scene, render: render); saveSession()
186 }
187 func useAtPlayhead() {
188 if studio.segments.isEmpty, let plan = audio.segmentPlan() { studio.makeTimeline(plan, render: render) }
189 _ = studio.assignAtPlayhead(audio.playbackSeconds, render: render); saveSession()
190 }
191 func selectClip(_ index: Int, play: Bool = false) {
192 guard studio.segments.indices.contains(index) else { return }
193 radio.leave(); studio.isStudio = true; studio.selectedSegment = index
194 let clip = studio.segments[index]
195 if play { audio.playSection(start: clip.start, end: clip.end, restart: true) }
196 else { audio.selectSection(start: clip.start, end: clip.end) }
197 studio.follow(time: clip.start, render: render)
198 }
199 func setBars(_ value: Int, at index: Int) {
200 guard let grid = audio.segmentPlan(beatsPerSection: 4) else { return }
201 audio.pause(); _ = studio.setBars(value, at: index, grid: grid, render: render); saveSession()
202 }
203 func setForeground(_ active: Bool, inBackground: Bool = false) {
204 foreground = active
205 audio.setVisualizationEnabled(active)
206 if active { tick() }
207 else {
208 // iOS permits audio playback in the background, not Metal rendering.
209 render.paused = true; radio.visualizer.paused = true
210 if inBackground { exporter.cancel() }
211 saveSession()
212 }
213 }
214 private func tick() {
215 guard foreground else { return }
216 let target = currentRender
217 target.audioTrebleAttackTime = audio.trebleAttackTime
218 target.audioTreblePulse = audio.treblePulse; target.audioBeatMotionTime = audio.beatMotionTime
219 target.audioMomentum = audio.momentum; target.audioPulse = audio.beatPulse
220 target.audioBands = audio.spectrum; target.audioEnvelopes = audio.envelopes; target.audioSwell = audio.swell
221 target.playbackTime = audio.selectedURL == nil ? nil : audio.playbackSeconds; target.paused = !audio.isPlaying
222 if radio.isActive { radio.follow(time: audio.playbackSeconds) }
223 else if !exporter.isExporting { studio.follow(time: audio.playbackSeconds, render: render) }
224 }
225 func projectData() throws -> Data {
226 guard !radio.isActive || !radio.isPersonalMusic else { throw CocoaError(.userCancelled) }
227 studio.save(render)
228 let bundled = BundledSoundtrack.identifier(for: audio.selectedURL)
229 let project = CreatorProject(soundtrack: bundled == nil ? audio.selectedURL : nil, scene: render.scene,
230 appearance: studio.preset(render), aspect: exporter.aspect.rawValue, resolution: exporter.resolution, fps: exporter.fps,
231 timeline: studio.segments, studioEnabled: studio.isStudio, visualPresets: studio.presets,
232 barsPerSection: studio.barsPerSection,
233 effectIdentities: library.identities(for: Set(studio.presets.keys).union(studio.segments.map(\.scene)).union([render.scene])),
234 bundledSoundtrack: bundled, soundtrackBookmark: audio.soundtrackBookmark, loopPlayback: audio.loopEnabled,
235 cloudProjectID: studio.cloudProjectID)
236 return try JSONEncoder().encode(project)
237 }
238 func openProject(_ data: Data) async {
239 do {
240 guard data.count < 8_000_000 else { throw CocoaError(.fileReadCorruptFile) }
241 let project = try JSONDecoder().decode(CreatorProject.self, from: data).remapped(using: library)
242 guard project.version == 1, project.appearance.isValid,
243 project.visualPresets?.values.allSatisfy(\.isValid) ?? true,
244 StudioTimeline.valid(project.timeline ?? [], sceneCount: RenderState.sceneNames.count),
245 SocialAspect(rawValue: project.aspect) != nil, [720, 1080, 2160].contains(project.resolution),
246 SocialExportController.supportedFrameRates.contains(project.fps),
247 project.barsPerSection.map({ (1...64).contains($0) }) ?? true else { throw CocoaError(.fileReadCorruptFile) }
248 radio.leave(); selectedTab = 0; pendingProject = project
249 let reference = try BundledSoundtrack.resolve(identifier: project.bundledSoundtrack, externalURL: project.soundtrack)
250 if let reference {
251 let bookmarked = SecurityScopedAccess.resolve(bookmark: project.soundtrackBookmark, fallback: reference)
252 let local = documents.appendingPathComponent(reference.lastPathComponent)
253 let source = FileManager.default.fileExists(atPath: bookmarked.path) ? bookmarked : local
254 guard FileManager.default.fileExists(atPath: source.path) else { needsSoundtrack = true; return }
255 await load(source, copy: false)
256 } else { audio.clear(); try apply(project); pendingProject = nil }
257 if pendingProject == nil {
258 do { try UserBackup.rememberProject(data, name: "Imported-\(UserBackup.hash(data).prefix(16)).pulsecanvas") }
259 catch { message = String(localized: "Project opened, but its backup copy wasn't updated: \(error.localizedDescription)") }
260 }
261 } catch { message = String(localized: "Couldn't open this project: \(error.localizedDescription)") }
262 }
263 private func apply(_ project: CreatorProject) throws {
264 studio.cloudProjectID = project.cloudProjectID
265 guard (project.timeline?.last?.end ?? 0) <= audio.duration + 0.05 else { throw CocoaError(.fileReadCorruptFile) }
266 studio.presets = project.visualPresets ?? [:]; studio.segments = project.timeline ?? []
267 studio.isStudio = project.studioEnabled ?? false; studio.selectedSegment = 0
268 studio.barsPerSection = project.barsPerSection ?? 4
269 render.scene = project.scene; studio.apply(project.appearance, to: render)
270 exporter.aspect = SocialAspect(rawValue: project.aspect)!; exporter.resolution = project.resolution; exporter.fps = project.fps
271 audio.loopEnabled = project.loopPlayback ?? true
272 studio.detectedBPM = audio.segmentPlan()?.bpm
273 }
274 func saveSession() {
275 guard !loading, !radio.isActive, audio.selectedURL != nil else { return }
276 do { try projectData().write(to: autosave, options: .atomic) }
277 catch { message = String(localized: "Couldn't save this session: \(error.localizedDescription)") }
278 }
279}