Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / SocialExportController.swift

Raw 24.7 KB on 1cf89eeacc946d122aba3a62ada6cb1600fbf757
1@preconcurrency import AVFoundation
2import Combine
3import CoreVideo
4import Foundation
5import CoreGraphics
6@preconcurrency import Metal
7import VideoToolbox
8
9enum SocialAspect: String, CaseIterable, Identifiable {
10 case wide = "16:9 · Wide"
11 case landscape = "4:3 · Landscape"
12 case portrait = "3:4 · Portrait"
13 case phone = "9:16 · Phone"
14 case square = "1:1 · Square"
15 var id: String { rawValue }
16 var title: String {
17 switch self {
18 case .wide: String(localized: "16:9 · Wide")
19 case .landscape: String(localized: "4:3 · Landscape")
20 case .portrait: String(localized: "3:4 · Portrait")
21 case .phone: String(localized: "9:16 · Phone")
22 case .square: String(localized: "1:1 · Square")
23 }
24 }
25 var aspectRatio: Double {
26 switch self {
27 case .wide: return 16.0 / 9
28 case .landscape: return 4.0 / 3
29 case .portrait: return 3.0 / 4
30 case .phone: return 9.0 / 16
31 case .square: return 1
32 }
33 }
34 /// Resolution is the shorter edge; every H.264 dimension is even.
35 func dimensions(resolution: Int) -> (width: Int, height: Int) {
36 let edge = [720, 1080, 2160].contains(resolution) ? resolution : 1080
37 if aspectRatio >= 1 { return (Int((Double(edge) * aspectRatio / 2).rounded()) * 2, edge) }
38 return (edge, Int((Double(edge) / aspectRatio / 2).rounded()) * 2)
39 }
40}
41
42@MainActor
43final class SocialExportController: ObservableObject {
44 #if os(visionOS) || os(iOS)
45 static let supportedFrameRates = [24, 30, 60]
46 static let supportedResolutions = [720, 1080, 2160]
47 #else
48 static let supportedFrameRates = [24, 30, 60, 120]
49 static let supportedResolutions = [720, 1080, 2160]
50 #endif
51 @Published var aspect: SocialAspect = .wide { didSet { persistSettings() } }
52 @Published var resolution = 1080 { didSet { persistSettings() } }
53 @Published var fps = 30 { didSet { persistSettings() } }
54 @Published private(set) var isExporting = false
55 @Published private(set) var progress = 0.0
56 enum Phase: String { case preparing, rendering, muxing, validating }
57 private(set) var phase = Phase.preparing
58 private(set) var error: Error?
59 private(set) var didFail = false
60 // Constructed on a worker and transferred once to the export actor.
61 private struct PreparedSpectrum: @unchecked Sendable {
62 let analyzer: SoundtrackAnalyzer
63 }
64
65 struct OfflineOptions {
66 let aspect: SocialAspect
67 let resolution: Int
68 let fps: Int
69 let scratchDirectory: URL
70 let previewSeconds: Double?
71 }
72 @Published private(set) var status = String(localized: "Ready to export")
73 @Published private(set) var exportedURL: URL?
74 @Published private(set) var successfulSaveID: UUID?
75 @Published private(set) var renderedFrames = 0
76 @Published private(set) var totalFrames = 0
77 @Published private(set) var framePreview: CGImage?
78 @Published private(set) var framesPerSecond = 0.0
79 @Published private(set) var estimatedSecondsRemaining: Double?
80 private(set) var cancellationRequested = false
81
82 private struct FormatSettings: Codable { var aspect: String; var resolution: Int; var fps: Int }
83 private let preferencesKey = "PulseCanvas.videoFormat.v1"
84 private let scratchDirectory: URL
85 /// Offline test tools can keep intermediate video files on their render drive.
86 /// The app defaults to its sandbox temporary area, as required by NSSavePanel access.
87 init(scratchDirectory: URL = FileManager.default.temporaryDirectory) {
88 self.scratchDirectory = scratchDirectory
89 if let data = UserDefaults.standard.data(forKey: preferencesKey), let saved = try? JSONDecoder().decode(FormatSettings.self, from: data), let aspect = SocialAspect(rawValue: saved.aspect), Self.supportedResolutions.contains(saved.resolution), Self.supportedFrameRates.contains(saved.fps) {
90 self.aspect = aspect; self.resolution = saved.resolution; self.fps = saved.fps
91 }
92 }
93 private func persistSettings() {
94 if let data = try? JSONEncoder().encode(FormatSettings(aspect: aspect.rawValue, resolution: resolution, fps: fps)) { UserDefaults.standard.set(data, forKey: preferencesKey) }
95 }
96
97 func cancel() { if isExporting { cancellationRequested = true; status = String(localized: "Cancelling…") } }
98
99 /// Offline export has its own scene snapshot, sample clock, and GPU renderer.
100 /// Preview playback and machine speed cannot skip or change output frames.
101 func export(audioURL: URL?, render: RenderState, to destination: URL, segments: [StudioSegment] = [], appearances: [Int: VisualPreset] = [:],
102 offline: OfflineOptions? = nil) async {
103 guard !isExporting else { return }
104 isExporting = true
105 didFail = false
106 error = nil
107 phase = .preparing
108 cancellationRequested = false
109 progress = 0
110 exportedURL = nil
111 renderedFrames = 0
112 totalFrames = 0
113 framePreview = nil
114 framesPerSecond = 0
115 estimatedSecondsRemaining = nil
116 status = String(localized: "Preparing export…")
117 defer { isExporting = false; estimatedSecondsRemaining = nil }
118 let outputResolution = offline?.resolution ?? resolution
119 let dimensions = (offline?.aspect ?? aspect).dimensions(resolution: outputResolution)
120 let frameRate = offline?.fps ?? fps
121 let scene = snapshot(render)
122 scene.projectMFramesPerSecond = frameRate
123 var scratch: URL?
124 let destinationAccess = SecurityScopedAccess(url: destination)
125 let audioAccess = audioURL.map { SecurityScopedAccess(url: $0) }
126 defer { withExtendedLifetime((destinationAccess, audioAccess)) {} }
127 do {
128 await Task.yield()
129 guard StudioTimeline.valid(segments, sceneCount: RenderState.sceneNames.count) else { throw ExportError(String(localized: "Studio timeline is invalid")) }
130 guard Self.supportedFrameRates.contains(frameRate), Self.supportedResolutions.contains(outputResolution) else {
131 #if os(visionOS) || os(iOS)
132 throw ExportError(String(localized: "Choose 720p, 1080p, or 4K and 24, 30, or 60 fps"))
133 #else
134 throw ExportError(String(localized: "Choose 720p, 1080p, or 4K and 24, 30, 60, or 120 fps (Experimental)"))
135 #endif
136 }
137 guard audioURL?.standardizedFileURL != destination.standardizedFileURL else {
138 throw ExportError(String(localized: "The output file must differ from the soundtrack"))
139 }
140 let spectrum: SoundtrackAnalyzer?
141 if offline != nil, let audioURL {
142 let preparation = Task.detached(priority: .userInitiated) {
143 PreparedSpectrum(analyzer: try SoundtrackAnalyzer(url: audioURL))
144 }
145 spectrum = try await withTaskCancellationHandler {
146 try await preparation.value.analyzer
147 } onCancel: { preparation.cancel() }
148 } else {
149 spectrum = try audioURL.map { try SoundtrackAnalyzer(url: $0) }
150 }
151 let audioAsset = audioURL.map { AVURLAsset(url: $0) }
152 let sourceDuration: Double
153 if let audioAsset {
154 sourceDuration = try await audioAsset.load(.duration).seconds
155 guard sourceDuration.isFinite && sourceDuration > 0 else { throw ExportError(String(localized: "Soundtrack duration is unavailable")) }
156 } else { sourceDuration = 15 }
157 let start = 0.0
158 let duration = min(offline?.previewSeconds ?? sourceDuration, sourceDuration)
159 guard duration > 0, duration <= 24 * 60 * 60 else { throw ExportError(String(localized: "Soundtrack must be shorter than 24 hours")) }
160 try checkCancellation()
161 // NSSavePanel grants the output file, not arbitrary siblings in
162 // its parent folder. Render in the app's sandbox temporary area.
163 let work = (offline?.scratchDirectory ?? scratchDirectory).appendingPathComponent("PulseCanvas-export-\(UUID().uuidString)", isDirectory: true)
164 try FileManager.default.createDirectory(at: work, withIntermediateDirectories: false)
165 scratch = work
166 defer { try? FileManager.default.removeItem(at: work) }
167 let video = work.appendingPathComponent("frames.mp4")
168 let renderer = VisualizerRenderer(state: scene)
169 try renderer.prepareOffscreen(width: dimensions.width, height: dimensions.height)
170 phase = .rendering
171 try await encodeFrames(renderer: renderer, spectrum: spectrum, start: start,
172 duration: duration, dimensions: dimensions, fps: frameRate, to: video, segments: segments, appearances: appearances)
173 let result: URL
174 if let audioAsset {
175 phase = .muxing
176 status = String(localized: "Adding soundtrack…")
177 result = work.appendingPathComponent("complete.mp4")
178 try await muxSoundtrack(asset: audioAsset, start: start, duration: duration, video: video, to: result)
179 } else { result = video }
180 try checkCancellation()
181 phase = .validating
182 if offline == nil && FileManager.default.fileExists(atPath: destination.path) {
183 _ = try FileManager.default.replaceItemAt(destination, withItemAt: result)
184 } else { try FileManager.default.moveItem(at: result, to: destination) }
185 progress = 1
186 exportedURL = destination
187 if offline == nil { successfulSaveID = UUID() }
188 status = String(localized: "Saved \(destination.lastPathComponent)")
189 } catch is CancellationError {
190 status = String(localized: "Export cancelled")
191 } catch {
192 self.error = error
193 didFail = true
194 status = String(localized: "Export failed: \(error.localizedDescription)")
195 }
196 if let scratch { try? FileManager.default.removeItem(at: scratch) }
197 }
198
199 private func snapshot(_ source: RenderState) -> RenderState {
200 let copy = RenderState()
201 copy.scene = source.scene; copy.speed = source.speed; copy.chaos = source.chaos; copy.brightness = source.brightness
202 copy.liquidDetail = source.liquidDetail
203 copy.zoomSpeed = source.zoomSpeed
204 copy.haloCount = source.haloCount
205 copy.particleSize = source.particleSize; copy.palette = source.palette; copy.fog = source.fog
206 copy.rotation = source.rotation; copy.zoom = source.zoom; copy.motionBlur = source.motionBlur
207 copy.strobeEnabled = source.strobeEnabled
208 copy.strobeSensitivity = source.strobeSensitivity
209 copy.strobeStrength = source.strobeStrength
210 return copy
211 }
212
213 private func checkCancellation() throws {
214 if cancellationRequested || Task.isCancelled { throw CancellationError() }
215 }
216
217 private func encodeFrames(renderer: VisualizerRenderer, spectrum: SoundtrackAnalyzer?, start: Double,
218 duration: Double, dimensions: (width: Int, height: Int), fps: Int, to url: URL, segments: [StudioSegment], appearances: [Int: VisualPreset]) async throws {
219 let writer = try AVAssetWriter(outputURL: url, fileType: .mp4)
220 let bitrate = min(24_000_000, max(4_000_000, dimensions.width * dimensions.height * fps / 7))
221 var settings: [String: Any] = [
222 AVVideoCodecKey: AVVideoCodecType.h264,
223 AVVideoWidthKey: dimensions.width, AVVideoHeightKey: dimensions.height,
224 AVVideoCompressionPropertiesKey: [AVVideoAverageBitRateKey: bitrate,
225 AVVideoExpectedSourceFrameRateKey: fps,
226 AVVideoMaxKeyFrameIntervalKey: fps * 2,
227 AVVideoProfileLevelKey: AVVideoProfileLevelH264HighAutoLevel]
228 ]
229 #if os(macOS)
230 settings[AVVideoEncoderSpecificationKey] = [kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder as String: true]
231 #endif
232 // visionOS selects its encoder internally; the macOS specification key is unavailable there.
233 let input = AVAssetWriterInput(mediaType: .video, outputSettings: settings)
234 input.expectsMediaDataInRealTime = false
235 let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [
236 kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
237 kCVPixelBufferWidthKey as String: dimensions.width,
238 kCVPixelBufferHeightKey as String: dimensions.height,
239 kCVPixelBufferMetalCompatibilityKey as String: true,
240 kCVPixelBufferIOSurfacePropertiesKey as String: [:]
241 ])
242 guard writer.canAdd(input) else { throw ExportError(String(localized: "Cannot create H.264 encoder")) }
243 writer.add(input)
244 guard writer.startWriting() else { throw writer.error ?? ExportError(String(localized: "Cannot start H.264 encoder")) }
245 writer.startSession(atSourceTime: .zero)
246 var completed = false
247 defer { if !completed { writer.cancelWriting() } }
248 let count = Int(ceil(duration * Double(fps) - 0.00000001))
249 totalFrames = count
250 guard let device = renderer.offscreenDevice else { throw ExportError(String(localized: "Metal device is unavailable")) }
251 var cache: CVMetalTextureCache?
252 guard CVMetalTextureCacheCreate(nil, nil, device, nil, &cache) == kCVReturnSuccess, let cache else {
253 throw ExportError(String(localized: "Cannot share GPU frames with the video encoder"))
254 }
255 var rateTime = ProcessInfo.processInfo.systemUptime
256 var rateFrames = 0
257 var lastPreview = -Double.infinity
258 var activeStudioScene: Int? = nil
259 for frame in 0..<count {
260 try checkCancellation()
261 let deadline = Date().addingTimeInterval(30)
262 while !input.isReadyForMoreMediaData {
263 try checkCancellation()
264 guard writer.status == .writing else { throw writer.error ?? ExportError(String(localized: "Video encoder stopped")) }
265 guard deadline.timeIntervalSinceNow > 0 else { throw ExportError(String(localized: "Video encoder timed out")) }
266 try await Task.sleep(for: .milliseconds(2))
267 }
268 let sourceTime = start + Double(frame) / Double(fps)
269 if let index = StudioTimeline.index(at: sourceTime, in: segments) {
270 let scene = segments[index].scene
271 if activeStudioScene != scene {
272 activeStudioScene = scene
273 renderer.state.scene = scene
274 let appearance = appearances[scene] ?? VisualPreset.defaults(for: scene)
275 appearance.apply(to: renderer.state)
276 }
277 }
278 if renderer.state.scene >= RenderState.nativeSceneNames.count { renderer.state.audioPCM = try spectrum?.pcm(at: sourceTime) ?? [] }
279 let features = try spectrum?.frame(at: sourceTime, clipStart: start, clipEnd: start + duration) ?? .silence
280 guard let pool = adaptor.pixelBufferPool else { throw ExportError(String(localized: "Encoder pixel buffer pool is unavailable")) }
281 var pixelBuffer: CVPixelBuffer?
282 guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &pixelBuffer) == kCVReturnSuccess,
283 let pixelBuffer else { throw ExportError(String(localized: "Cannot allocate an export frame")) }
284 var surface: CVMetalTexture?
285 guard CVMetalTextureCacheCreateTextureFromImage(nil, cache, pixelBuffer, nil, .bgra8Unorm,
286 dimensions.width, dimensions.height, 0, &surface) == kCVReturnSuccess,
287 let surface, let texture = CVMetalTextureGetTexture(surface) else {
288 throw ExportError(String(localized: "Cannot map an encoder frame to the GPU"))
289 }
290 try await renderer.renderOffscreen(into: texture, time: sourceTime, audioBands: features.bands, audioPulse: features.pulse, audioMomentum: features.momentum, audioBeatMotionTime: features.beatMotionTime, audioTreblePulse: features.treblePulse, audioTrebleAttackTime: features.trebleAttackTime, audioEnvelopes: features.envelopes, audioSwell: features.swell)
291 // Keep the Core Video texture wrapper alive through GPU completion.
292 withExtendedLifetime(surface) {}
293 try checkCancellation()
294 guard adaptor.append(pixelBuffer, withPresentationTime: CMTime(value: Int64(frame), timescale: Int32(fps))) else {
295 throw writer.error ?? ExportError(String(localized: "Cannot append export frame \(frame)"))
296 }
297 progress = 0.85 * Double(frame + 1) / Double(count)
298 renderedFrames = frame + 1
299 status = String(localized: "Rendering frame \(frame + 1) of \(count)")
300 let now = ProcessInfo.processInfo.systemUptime
301 let rateElapsed = now - rateTime
302 if rateElapsed >= 0.5 {
303 let rate = Double(frame + 1 - rateFrames) / rateElapsed
304 framesPerSecond = framesPerSecond == 0 ? rate : framesPerSecond * 0.65 + rate * 0.35
305 rateTime = now; rateFrames = frame + 1
306 }
307 if framesPerSecond > 0 && frame + 1 < count {
308 estimatedSecondsRemaining = Double(count - frame - 1) / framesPerSecond
309 }
310 if now - lastPreview >= 0.2 || frame == count - 1 {
311 updatePreview(pixelBuffer)
312 lastPreview = now
313 }
314 await Task.yield()
315 }
316 writer.endSession(atSourceTime: CMTime(seconds: duration, preferredTimescale: 60_000))
317 input.markAsFinished()
318 estimatedSecondsRemaining = nil
319 status = String(localized: "Finishing video…")
320 await writer.finishWriting()
321 try checkCancellation()
322 guard writer.status == .completed else { throw writer.error ?? ExportError(String(localized: "Video encoding failed")) }
323 completed = true
324 }
325
326 private func updatePreview(_ buffer: CVPixelBuffer) {
327 var image: CGImage?
328 guard VTCreateCGImageFromCVPixelBuffer(buffer, options: nil, imageOut: &image) == noErr, let image else { return }
329 let scale = min(1, 480 / Double(max(image.width, image.height)))
330 let width = max(1, Int(Double(image.width) * scale)), height = max(1, Int(Double(image.height) * scale))
331 guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8,
332 bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return }
333 context.interpolationQuality = .low
334 context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
335 framePreview = context.makeImage()
336 }
337
338 /// Copy the already encoded H.264 samples; encode only the trimmed soundtrack
339 /// to AAC. Both composition tracks begin at zero and use the same clip length.
340 private func muxSoundtrack(asset: AVURLAsset, start: Double, duration: Double, video: URL, to url: URL) async throws {
341 let videoAsset = AVURLAsset(url: video)
342 guard let videoSource = try await videoAsset.loadTracks(withMediaType: .video).first,
343 let audioSource = try await asset.loadTracks(withMediaType: .audio).first else {
344 throw ExportError(String(localized: "The soundtrack or rendered video track is missing"))
345 }
346 let formats = try await videoSource.load(.formatDescriptions)
347 guard let videoFormat = formats.first else { throw ExportError(String(localized: "Video format is unavailable")) }
348 let composition = AVMutableComposition()
349 guard let videoTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid),
350 let audioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
351 throw ExportError(String(localized: "Cannot prepare soundtrack composition"))
352 }
353 let length = CMTime(seconds: duration, preferredTimescale: 60_000)
354 try videoTrack.insertTimeRange(CMTimeRange(start: .zero, duration: length), of: videoSource, at: .zero)
355 try audioTrack.insertTimeRange(CMTimeRange(start: CMTime(seconds: start, preferredTimescale: 60_000), duration: length), of: audioSource, at: .zero)
356 let reader = try AVAssetReader(asset: composition)
357 reader.timeRange = CMTimeRange(start: .zero, duration: length)
358 let videoOutput = AVAssetReaderTrackOutput(track: videoTrack, outputSettings: nil)
359 let audioOutput = AVAssetReaderTrackOutput(track: audioTrack, outputSettings: [
360 AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44_100,
361 AVNumberOfChannelsKey: 2, AVLinearPCMBitDepthKey: 16,
362 AVLinearPCMIsFloatKey: false, AVLinearPCMIsNonInterleaved: false
363 ])
364 videoOutput.alwaysCopiesSampleData = false
365 audioOutput.alwaysCopiesSampleData = false
366 guard reader.canAdd(videoOutput), reader.canAdd(audioOutput) else { throw ExportError(String(localized: "Cannot decode soundtrack composition")) }
367 reader.add(videoOutput); reader.add(audioOutput)
368 let writer = try AVAssetWriter(outputURL: url, fileType: .mp4)
369 writer.shouldOptimizeForNetworkUse = true
370 let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: nil, sourceFormatHint: videoFormat)
371 let audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: [
372 AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 44_100,
373 AVNumberOfChannelsKey: 2, AVEncoderBitRateKey: 192_000
374 ])
375 videoInput.expectsMediaDataInRealTime = false; audioInput.expectsMediaDataInRealTime = false
376 guard writer.canAdd(videoInput), writer.canAdd(audioInput) else { throw ExportError(String(localized: "Cannot create MP4 soundtrack writer")) }
377 writer.add(videoInput); writer.add(audioInput)
378 guard writer.startWriting(), reader.startReading() else { throw writer.error ?? reader.error ?? ExportError(String(localized: "Cannot start soundtrack writer")) }
379 writer.startSession(atSourceTime: .zero)
380 var completed = false
381 defer { if !completed { reader.cancelReading(); writer.cancelWriting() } }
382 var videoFinished = false, audioFinished = false
383 var batchCount = 0
384 var lastProgressUpdate = ProcessInfo.processInfo.systemUptime
385 var deadline = Date().addingTimeInterval(30)
386 while !videoFinished || !audioFinished {
387 try checkCancellation()
388 guard writer.status == .writing, reader.status != .failed else {
389 throw writer.error ?? reader.error ?? ExportError(String(localized: "Soundtrack writer stopped"))
390 }
391 var advanced = false
392 for (output, input, isVideo) in [(videoOutput, videoInput, true), (audioOutput, audioInput, false)] {
393 if (isVideo ? videoFinished : audioFinished) || !input.isReadyForMoreMediaData { continue }
394 if let sample = output.copyNextSampleBuffer() {
395 guard input.append(sample) else { throw writer.error ?? ExportError(String(localized: "Cannot append soundtrack sample")) }
396 let time = CMSampleBufferGetPresentationTimeStamp(sample).seconds
397 let now = ProcessInfo.processInfo.systemUptime
398 if time.isFinite && now - lastProgressUpdate >= 0.1 {
399 progress = max(progress, min(0.99, 0.85 + 0.14 * time / duration))
400 lastProgressUpdate = now
401 }
402 } else {
403 input.markAsFinished()
404 if isVideo { videoFinished = true } else { audioFinished = true }
405 }
406 advanced = true
407 }
408 if advanced {
409 deadline = Date().addingTimeInterval(30)
410 batchCount += 1
411 if batchCount >= 32 { batchCount = 0; await Task.yield() }
412 }
413 else {
414 guard deadline.timeIntervalSinceNow > 0 else { throw ExportError(String(localized: "Soundtrack encoding timed out")) }
415 try await Task.sleep(for: .milliseconds(2))
416 }
417 }
418 writer.endSession(atSourceTime: length)
419 await writer.finishWriting()
420 try checkCancellation()
421 guard writer.status == .completed, reader.status == .completed else {
422 throw writer.error ?? reader.error ?? ExportError(String(localized: "Soundtrack encoding failed"))
423 }
424 completed = true
425 }
426}
427
428struct ExportError: LocalizedError {
429 let message: String
430 init(_ message: String) { self.message = message }
431 var errorDescription: String? { message }
432}