Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / NativeExpansionSmoke.swift

Raw 14.8 KB on 1cf89eeacc946d122aba3a62ada6cb1600fbf757
1import AppKit
2@preconcurrency import AVFoundation
3import Foundation
4@preconcurrency import Metal
5
6/// Native catalog: coverage in every canvas shape, distinct designs, Chaos-isolated music
7/// response, timing, Studio switching and decoded exports with the real soundtrack.
8@main struct NativeExpansionSmoke {
9 static func require(_ condition: Bool, _ message: String) throws {
10 if !condition { throw ExportError(message) }
11 }
12 static func pixels(_ texture: MTLTexture) -> [UInt8] {
13 var bytes = [UInt8](repeating: 0, count: texture.width * texture.height * 4)
14 bytes.withUnsafeMutableBytes {
15 texture.getBytes($0.baseAddress!, bytesPerRow: texture.width * 4,
16 from: MTLRegionMake2D(0, 0, texture.width, texture.height), mipmapLevel: 0)
17 }
18 return bytes
19 }
20 static func png(_ bytes: [UInt8], width: Int, height: Int, to url: URL) throws {
21 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height,
22 bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
23 colorSpaceName: .deviceRGB, bytesPerRow: width * 4, bitsPerPixel: 32)!
24 for pixel in stride(from: 0, to: bytes.count, by: 4) {
25 bitmap.bitmapData![pixel] = bytes[pixel + 2]
26 bitmap.bitmapData![pixel + 1] = bytes[pixel + 1]
27 bitmap.bitmapData![pixel + 2] = bytes[pixel]
28 bitmap.bitmapData![pixel + 3] = 255
29 }
30 try bitmap.representation(using: .png, properties: [:])!.write(to: url)
31 }
32 static func excerpt(_ source: URL, start: Double, duration: Double, to target: URL) throws {
33 let input = try AVAudioFile(forReading: source)
34 let rate = input.processingFormat.sampleRate
35 var settings = input.processingFormat.settings
36 settings[AVLinearPCMIsNonInterleaved] = false
37 let writer = try AVAudioFile(forWriting: target, settings: settings)
38 var remaining = AVAudioFramePosition((duration * rate).rounded())
39 var position = AVAudioFramePosition((start * rate).rounded()) % input.length
40 while remaining > 0 {
41 input.framePosition = position
42 let count = AVAudioFrameCount(min(remaining, input.length - position))
43 let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: count)!
44 try input.read(into: buffer, frameCount: count)
45 try writer.write(from: buffer)
46 remaining -= AVAudioFramePosition(buffer.frameLength); position = 0
47 }
48 }
49 static func verifyVideo(_ url: URL, width: Int, height: Int, fps: Int, duration: Double) async throws {
50 let asset = AVURLAsset(url: url)
51 let track = try await asset.loadTracks(withMediaType: .video).first!
52 let size = try await track.load(.naturalSize)
53 let rate = try await track.load(.nominalFrameRate)
54 let seconds = try await asset.load(.duration).seconds
55 try require(size.width == Double(width) && size.height == Double(height), "Wrong video dimensions \(size)")
56 try require(abs(rate-Float(fps)) < 0.01 && abs(seconds-duration) < 0.04, "Wrong video timing \(rate) fps \(seconds) s")
57 let audioTracks = try await asset.loadTracks(withMediaType: .audio)
58 try require(!audioTracks.isEmpty, "Real soundtrack must be included")
59 let reader = try AVAssetReader(asset: asset)
60 let output = AVAssetReaderTrackOutput(track: track, outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA])
61 reader.add(output); try require(reader.startReading(), "Decoder did not start")
62 var count = 0, minimumMean = 255.0
63 while let sample = output.copyNextSampleBuffer() {
64 guard let buffer = CMSampleBufferGetImageBuffer(sample) else { throw ExportError("Decoded frame missing") }
65 CVPixelBufferLockBaseAddress(buffer, .readOnly)
66 let data = CVPixelBufferGetBaseAddress(buffer)!.assumingMemoryBound(to: UInt8.self)
67 let stride = CVPixelBufferGetBytesPerRow(buffer)
68 var sum = 0.0, samples = 0
69 for y in Swift.stride(from: 0, to: height, by: 16) {
70 for x in Swift.stride(from: 0, to: width, by: 16) {
71 let index = y * stride + x * 4
72 sum += Double(data[index]) + Double(data[index+1]) + Double(data[index+2]); samples += 3
73 }
74 }
75 CVPixelBufferUnlockBaseAddress(buffer, .readOnly)
76 minimumMean = min(minimumMean, sum / Double(samples)); count += 1
77 }
78 try require(reader.status == .completed && count == Int((duration * Double(fps)).rounded()), "Missing decoded video frames: \(count)")
79 try require(minimumMean > 1, "Black frame in exported video, minimum RGB \(minimumMean)")
80 print("PASS decoded \(url.lastPathComponent): \(count) frames, \(width)x\(height), \(fps) fps, soundtrack present, minimum RGB \(String(format: "%.1f", minimumMean))")
81 }
82 @MainActor static func main() async {
83 NSApplication.shared.setActivationPolicy(.accessory)
84 do { try await run() } catch { print("FAIL: \(error.localizedDescription)"); exit(1) }
85 }
86 @MainActor static func render(_ renderer: VisualizerRenderer, _ analyzer: SoundtrackAnalyzer, at time: Double) throws -> [UInt8] {
87 let features = try analyzer.frame(at: time, clipStart: 0, clipEnd: 10_000)
88 return pixels(try renderer.renderOffscreen(time: time, audioBands: features.bands, audioPulse: features.pulse,
89 audioMomentum: features.momentum, audioBeatMotionTime: features.beatMotionTime,
90 audioEnvelopes: features.envelopes, audioSwell: features.swell))
91 }
92 @MainActor static func run() async throws {
93 let root = URL(fileURLWithPath: ".build/native-expansion", isDirectory: true)
94 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
95 let source = URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3")
96 let analyzer = try SoundtrackAnalyzer(url: source)
97 let state = RenderState(), renderer = VisualizerRenderer(state: state)
98 let names = RenderState.nativeSceneNames
99 let active = NativeEffects.activeIDs
100 try require(Set(active.map { names[$0] }).count == active.count, "Expected uniquely named native designs")
101 try require(active.allSatisfy { NativeEffects.effect(NativeEffects.resolved($0)) != nil } && NativeEffects.all.indices.allSatisfy { !NativeEffects.isRetired(NativeEffects.resolved($0)) },
102 "Every retired design must resolve to an active design")
103 let scenes = active.filter { $0 >= NativeEffects.legacyCount }
104 try require(scenes.allSatisfy { NativeEffects.all[$0].shader != nil && NativeEffects.shaderFiles.contains(NativeEffects.all[$0].file ?? "") }, "Every new design must use a registered native Metal pass")
105 try require(Set(scenes.compactMap { NativeEffects.all[$0].shader }).count == scenes.count, "Every new design needs its own shader")
106 try require(NativeEffects.timelineOrder.count == active.count && Set(NativeEffects.timelineOrder) == Set(active), "Studio's automatic order must use every active design once")
107 print("PASS catalog: \(active.count) active designs, \(names.count - active.count) retired IDs reserved for migration")
108
109 let paletteCounts = Dictionary(grouping: active, by: { VisualPreset.defaults(for: $0).palette }).mapValues(\.count)
110 try require(paletteCounts.count == VisualPalette.allCases.count && (paletteCounts[0] ?? 0) < active.count / 3,
111 "Default looks must cover every palette without a violet majority")
112 try require(active.allSatisfy { VisualPreset.defaults(for: $0).palette == NativeEffects.all[$0].look.palette },
113 "Editor, reset and Studio must use the registered palette defaults")
114 print("PASS default palettes: \(paletteCounts.sorted { $0.key < $1.key })")
115
116 // Coverage in every canvas shape with the real soundtrack, at each design's defaults.
117 let shapes: [(Int, Int, String)] = [(640,360,"wide"),(480,360,"landscape"),(360,480,"portrait"),(360,640,"phone"),(480,480,"square")]
118 for (width, height, tag) in shapes {
119 try renderer.prepareOffscreen(width: width, height: height)
120 var weakest = (scene: 0, lit: 1.0)
121 for scene in active {
122 state.scene = scene
123 VisualPreset.defaults(for: scene).apply(to: state)
124 state.motionBlur = 0; state.strobeEnabled = false
125 for time in [12.3, 47.1, 96.4] {
126 let bytes = try render(renderer, analyzer, at: time)
127 var cells = Set<Int>(), lit = 0
128 for i in Swift.stride(from: 0, to: bytes.count, by: 4) {
129 if bytes[i] != bytes[i + 1] || bytes[i] != bytes[i + 2] {
130 throw ExportError("Color leaked into \(names[scene]) \(tag) at \(time)s")
131 }
132 guard bytes[i] > 20 else { continue }
133 lit += 1
134 cells.insert(((i/4) / width * 4 / height) * 4 + (i/4) % width * 4 / width)
135 }
136 let fraction = Double(lit) / Double(width * height)
137 // The Mercury Ribbon study is intentionally an isolated object against black.
138 let requiredCells = NativeEffects.effect(scene)?.shader == "mercuryFold" ? 4 : 14
139 try require(cells.count >= requiredCells && fraction > 0.05, "Sparse canvas: \(names[scene]) \(tag) at \(time)s, \(cells.count) cells, \(Int(fraction * 100))% lit")
140 if fraction < weakest.lit { weakest = (scene, fraction) }
141 if time == 12.3 && scene >= NativeEffects.legacyCount { try png(bytes, width: width, height: height, to: root.appendingPathComponent(String(format: "%03d-%@.png", scene, tag))) }
142 }
143 }
144 print("PASS \(tag) \(width)x\(height): all \(active.count) designs meet coverage at three song positions; least lit \(names[weakest.scene]) \(Int(weakest.lit * 100))%")
145 }
146
147 // Distinct designs: same palette and controls, compared at low resolution.
148 try renderer.prepareOffscreen(width: 160, height: 90)
149 var frames: [[UInt8]] = []
150 for scene in active {
151 state.scene = scene
152 VisualPreset().apply(to: state)
153 state.zoomSpeed = 1; state.chaos = 0.6
154 frames.append(try render(renderer, analyzer, at: 40))
155 }
156 var closest = (a: 0, b: 0, difference: 255.0)
157 for a in frames.indices {
158 for b in frames.indices where b > a {
159 var total = 0
160 for i in Swift.stride(from: 0, to: frames[a].count, by: 4) {
161 total += abs(Int(frames[a][i]) - Int(frames[b][i])) + abs(Int(frames[a][i+1]) - Int(frames[b][i+1])) + abs(Int(frames[a][i+2]) - Int(frames[b][i+2]))
162 }
163 let difference = Double(total) / Double(frames[a].count / 4 * 3)
164 if difference < closest.difference { closest = (active[a], active[b], difference) }
165 }
166 }
167 try require(closest.difference > 4, "Indistinguishable designs: \(names[closest.a]) and \(names[closest.b]) (\(closest.difference))")
168 print(String(format: "PASS distinct outputs for all %d pairs with one palette; closest pair %@ / %@ differs by %.1f/255", active.count * (active.count - 1) / 2, names[closest.a], names[closest.b], closest.difference))
169
170 // Timing: sequential completed GPU frames.
171 for (width, height) in [(1920,1080),(3840,2160)] {
172 try renderer.prepareOffscreen(width: width, height: height)
173 var slowest = (scene: 0, ms: 0.0), total = 0.0
174 for scene in active {
175 state.scene = scene
176 VisualPreset.defaults(for: scene).apply(to: state)
177 _ = try render(renderer, analyzer, at: 12)
178 let start = ProcessInfo.processInfo.systemUptime
179 for frame in 0..<6 { _ = try render(renderer, analyzer, at: 12 + Double(frame) / 60) }
180 let ms = (ProcessInfo.processInfo.systemUptime - start) * 1000 / 6
181 total += ms
182 if ms > slowest.ms { slowest = (scene, ms) }
183 print(String(format: "TIMING %3d %-22@ %dx%d %7.2f ms", scene, names[scene] as NSString, width, height, ms))
184 }
185 print(String(format: "SUMMARY %dx%d: mean %.2f ms, slowest %@ %.2f ms", width, height, total / Double(active.count), names[slowest.scene], slowest.ms))
186 }
187
188 // Studio switching through every new design, exported and decoded in two shapes.
189 let duration = Double(scenes.count)
190 let excerptURL = root.appendingPathComponent("soundtrack-excerpt.wav")
191 try excerpt(source, start: 0, duration: duration, to: excerptURL)
192 let segments = scenes.enumerated().map { StudioSegment(start: Double($0.offset), end: Double($0.offset + 1), scene: $0.element) }
193 let preferencesKey = "PulseCanvas.videoFormat.v1"
194 let savedFormat = UserDefaults.standard.data(forKey: preferencesKey)
195 defer {
196 if let savedFormat { UserDefaults.standard.set(savedFormat, forKey: preferencesKey) }
197 else { UserDefaults.standard.removeObject(forKey: preferencesKey) }
198 }
199 let exporter = SocialExportController()
200 exporter.fps = 30; exporter.resolution = 720
201 for aspect in [SocialAspect.wide, .phone, .square] {
202 exporter.aspect = aspect
203 let video = root.appendingPathComponent("native-expansion-\(aspect == .wide ? "wide" : aspect == .phone ? "phone" : "square").mp4")
204 await exporter.export(audioURL: excerptURL, render: state, to: video, segments: segments)
205 try require(exporter.exportedURL == video, exporter.status)
206 let size = aspect.dimensions(resolution: 720)
207 try await verifyVideo(video, width: size.width, height: size.height, fps: 30, duration: duration)
208 }
209 let shortURL = root.appendingPathComponent("soundtrack-2s.wav")
210 try excerpt(source, start: 40, duration: 2, to: shortURL)
211 exporter.aspect = .wide; exporter.resolution = 2160; exporter.fps = 60
212 let fourK = root.appendingPathComponent("native-expansion-4k60.mp4")
213 await exporter.export(audioURL: shortURL, render: state, to: fourK,
214 segments: [StudioSegment(start: 0, end: 0.7, scene: 91), StudioSegment(start: 0.7, end: 1.4, scene: 33), StudioSegment(start: 1.4, end: 2, scene: 84)])
215 try require(exporter.exportedURL == fourK, exporter.status)
216 try await verifyVideo(fourK, width: 3840, height: 2160, fps: 60, duration: 2)
217 print("PASS \(scenes.count) new designs (\(active.count) active) through real soundtrack analysis, every canvas shape, Studio switching, GPU timing and decoded exports.")
218 }
219}