PulseCanvas / app · pulsecanvas.ai / scripts / NativeReel.swift
| 1 | import AppKit |
| 2 | @preconcurrency import AVFoundation |
| 3 | import Foundation |
| 4 | |
| 5 | /// Exports a labeled-ready motion reel through the real Studio exporter: one section per |
| 6 | /// design over a continuous excerpt of the bundled soundtrack. |
| 7 | /// native-reel.sh --scenes 31-99 --seconds 3 --start 20 --aspect wide --resolution 720 --fps 30 --out reel.mp4 [--chaos 0] |
| 8 | @main struct NativeReel { |
| 9 | @MainActor static func main() async { |
| 10 | NSApplication.shared.setActivationPolicy(.accessory) |
| 11 | do { try await run(CommandLine.arguments) } catch { print("FAIL: \(error.localizedDescription)"); exit(1) } |
| 12 | } |
| 13 | |
| 14 | /// Writes a looping excerpt; the file is closed when this returns, finalizing its header. |
| 15 | static func writeExcerpt(from source: URL, start: Double, duration: Double, to target: URL) throws { |
| 16 | let input = try AVAudioFile(forReading: source) |
| 17 | let rate = input.processingFormat.sampleRate |
| 18 | let songLength = Double(input.length) / rate |
| 19 | var settings = input.processingFormat.settings |
| 20 | settings[AVLinearPCMIsNonInterleaved] = false |
| 21 | let writer = try AVAudioFile(forWriting: target, settings: settings) |
| 22 | var remaining = duration, position = start |
| 23 | while remaining > 0.001 { |
| 24 | let chunk = min(remaining, songLength - position) |
| 25 | input.framePosition = AVAudioFramePosition(position * rate) |
| 26 | let count = AVAudioFrameCount(chunk * rate) |
| 27 | let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: count)! |
| 28 | try input.read(into: buffer, frameCount: count) |
| 29 | try writer.write(from: buffer) |
| 30 | remaining -= chunk; position = 0 |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | @MainActor static func run(_ arguments: [String]) async throws { |
| 35 | var scenes: [Int] = [], seconds = 3.0, start = 20.0, resolution = 720, fps = 30 |
| 36 | var aspect = SocialAspect.wide, output = ".build/reels/reel.mp4" |
| 37 | var chaos: Float? = nil, zoomSpeed: Float? = nil |
| 38 | var variedOrder = false |
| 39 | var index = 1 |
| 40 | while index + 1 < arguments.count { |
| 41 | let key = arguments[index], value = arguments[index + 1] |
| 42 | switch key { |
| 43 | case "--scenes": |
| 44 | scenes = value.split(separator: ",").flatMap { part -> [Int] in |
| 45 | let bounds = part.split(separator: "-").compactMap { Int($0) } |
| 46 | return bounds.count == 2 ? Array(bounds[0]...bounds[1]) : bounds |
| 47 | }.filter { !NativeEffects.isRetired($0) } |
| 48 | case "--seconds": seconds = Double(value) ?? seconds |
| 49 | case "--start": start = Double(value) ?? start |
| 50 | case "--resolution": resolution = Int(value) ?? resolution |
| 51 | case "--fps": fps = Int(value) ?? fps |
| 52 | case "--aspect": aspect = ["wide": .wide, "landscape": .landscape, "portrait": .portrait, "phone": .phone, "square": .square][value] ?? .wide |
| 53 | case "--order": variedOrder = value == "varied" |
| 54 | case "--chaos": chaos = Float(value) |
| 55 | case "--zoom-speed": zoomSpeed = Float(value) |
| 56 | case "--out": output = value |
| 57 | default: throw ExportError("Unknown option \(key)") |
| 58 | } |
| 59 | index += 2 |
| 60 | } |
| 61 | if scenes.isEmpty { scenes = NativeEffects.activeIDs } |
| 62 | if variedOrder { |
| 63 | // Reorder the demonstration only; render every effect's real defaults. |
| 64 | var pending = scenes, ordered: [Int] = [], previous = -1 |
| 65 | while !pending.isEmpty { |
| 66 | let index = pending.firstIndex { VisualPreset.defaults(for: $0).palette != previous } ?? 0 |
| 67 | let scene = pending.remove(at: index) |
| 68 | ordered.append(scene); previous = VisualPreset.defaults(for: scene).palette |
| 69 | } |
| 70 | scenes = ordered |
| 71 | } |
| 72 | let destination = URL(fileURLWithPath: output) |
| 73 | try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 74 | let duration = seconds * Double(scenes.count) |
| 75 | let audio = destination.deletingPathExtension().appendingPathExtension("wav") |
| 76 | try writeExcerpt(from: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"), start: start, duration: duration, to: audio) |
| 77 | let segments = scenes.enumerated().map { StudioSegment(start: Double($0.offset) * seconds, end: Double($0.offset + 1) * seconds, scene: $0.element) } |
| 78 | var appearances: [Int: VisualPreset] = [:] |
| 79 | for scene in scenes { |
| 80 | var look = VisualPreset.defaults(for: scene) |
| 81 | if let chaos { look.chaos = chaos } |
| 82 | if let zoomSpeed { look.zoomSpeed = zoomSpeed } |
| 83 | appearances[scene] = look |
| 84 | } |
| 85 | let preferencesKey = "PulseCanvas.videoFormat.v1" |
| 86 | let savedFormat = UserDefaults.standard.data(forKey: preferencesKey) |
| 87 | defer { |
| 88 | if let savedFormat { UserDefaults.standard.set(savedFormat, forKey: preferencesKey) } |
| 89 | else { UserDefaults.standard.removeObject(forKey: preferencesKey) } |
| 90 | } |
| 91 | let exporter = SocialExportController() |
| 92 | exporter.aspect = aspect; exporter.resolution = resolution; exporter.fps = fps |
| 93 | let began = ProcessInfo.processInfo.systemUptime |
| 94 | await exporter.export(audioURL: audio, render: RenderState(), to: destination, segments: segments, appearances: appearances) |
| 95 | guard exporter.exportedURL == destination else { throw ExportError(exporter.status) } |
| 96 | let labels: [[String: Any]] = segments.map { |
| 97 | let look = appearances[$0.scene]! |
| 98 | return ["start": $0.start, "end": $0.end, "scene": $0.scene, |
| 99 | "palette": VisualPalette(rawValue: look.palette)!.title, "chaos": look.chaos, |
| 100 | "zoomSpeed": look.zoomSpeed, "speed": look.speed] |
| 101 | } |
| 102 | try JSONSerialization.data(withJSONObject: ["names": RenderState.nativeSceneNames, "segments": labels]).write(to: destination.deletingPathExtension().appendingPathExtension("json")) |
| 103 | try? FileManager.default.removeItem(at: audio) |
| 104 | print(String(format: "REEL %@: %d sections, %.0f s, %@ %dp %d fps, exported in %.1f s", destination.lastPathComponent, scenes.count, duration, aspect.rawValue, resolution, fps, ProcessInfo.processInfo.systemUptime - began)) |
| 105 | } |
| 106 | } |