Branchwell

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

Raw 9.0 KB on 15681b389943bdb82ce0ee35ea3df6538f046361
1import AppKit
2@preconcurrency import AVFoundation
3import Foundation
4@preconcurrency import Metal
5
6@main struct NativeExportAgreementSmoke {
7 static func require(_ condition: Bool, _ message: String) throws {
8 if !condition { throw ExportError(message) }
9 }
10 static func pixels(_ texture: MTLTexture) -> [UInt8] {
11 var bytes = [UInt8](repeating: 0, count: texture.width * texture.height * 4)
12 bytes.withUnsafeMutableBytes {
13 texture.getBytes($0.baseAddress!, bytesPerRow: texture.width * 4,
14 from: MTLRegionMake2D(0, 0, texture.width, texture.height), mipmapLevel: 0)
15 }
16 return bytes
17 }
18 static func png(_ bytes: [UInt8], width: Int, height: Int, to url: URL) throws {
19 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height,
20 bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
21 colorSpaceName: .deviceRGB, bytesPerRow: width * 4, bitsPerPixel: 32)!
22 for pixel in stride(from: 0, to: bytes.count, by: 4) {
23 bitmap.bitmapData![pixel] = bytes[pixel + 2]
24 bitmap.bitmapData![pixel + 1] = bytes[pixel + 1]
25 bitmap.bitmapData![pixel + 2] = bytes[pixel]
26 bitmap.bitmapData![pixel + 3] = 255
27 }
28 try bitmap.representation(using: .png, properties: [:])!.write(to: url)
29 }
30 static func excerpt(_ source: URL, duration: Double, to target: URL) throws {
31 let input = try AVAudioFile(forReading: source)
32 let count = AVAudioFrameCount(duration * input.processingFormat.sampleRate)
33 let buffer = AVAudioPCMBuffer(pcmFormat: input.processingFormat, frameCapacity: count)!
34 try input.read(into: buffer, frameCount: count)
35 var settings = input.processingFormat.settings
36 settings[AVLinearPCMIsNonInterleaved] = false
37 try AVAudioFile(forWriting: target, settings: settings).write(from: buffer)
38 }
39 static func verifyVideo(_ url: URL, width: Int, height: Int, fps: Int, duration: Double,
40 expectedFrames: [Int: [UInt8]] = [:]) async throws {
41 let asset = AVURLAsset(url: url)
42 let track = try await asset.loadTracks(withMediaType: .video).first!
43 let size = try await track.load(.naturalSize)
44 let rate = try await track.load(.nominalFrameRate)
45 let seconds = try await asset.load(.duration).seconds
46 try require(size.width == Double(width) && size.height == Double(height), "Wrong video dimensions")
47 try require(abs(rate-Float(fps)) < 0.01 && abs(seconds-duration) < 0.04, "Wrong video timing")
48 let audioTracks = try await asset.loadTracks(withMediaType: .audio)
49 try require(!audioTracks.isEmpty, "Real soundtrack must be included in the preview")
50 let reader = try AVAssetReader(asset: asset)
51 let output = AVAssetReaderTrackOutput(track: track, outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA])
52 reader.add(output); try require(reader.startReading(), "Decoder did not start")
53 var count = 0, minimumMean = 255.0, compared = 0, largestError = 0.0
54 while let sample = output.copyNextSampleBuffer() {
55 guard let buffer = CMSampleBufferGetImageBuffer(sample) else { throw ExportError("Decoded frame missing") }
56 CVPixelBufferLockBaseAddress(buffer, .readOnly)
57 let data = CVPixelBufferGetBaseAddress(buffer)!.assumingMemoryBound(to: UInt8.self)
58 let stride = CVPixelBufferGetBytesPerRow(buffer)
59 var sum = 0.0, samples = 0, sampled: [UInt8] = []
60 for y in Swift.stride(from: 0, to: height, by: 16) {
61 for x in Swift.stride(from: 0, to: width, by: 16) {
62 let index = y * stride + x * 4
63 sum += Double(data[index]) + Double(data[index+1]) + Double(data[index+2]); samples += 3
64 if expectedFrames[count] != nil { sampled += [data[index], data[index+1], data[index+2]] }
65 }
66 }
67 CVPixelBufferUnlockBaseAddress(buffer, .readOnly)
68 if let expected = expectedFrames[count] {
69 try require(sampled.count == expected.count, "Decoded/reference sample sizes differ")
70 let error = zip(sampled,expected).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(expected.count)
71 try require(error < 12, "Decoded/reference RGB error at frame \(count), \(width)x\(height): \(error)")
72 compared += 1; largestError = max(largestError,error)
73 }
74 minimumMean = min(minimumMean, sum / Double(samples)); count += 1
75 }
76 try require(reader.status == .completed && count == Int((duration * Double(fps)).rounded()), "Missing decoded video frames")
77 try require(minimumMean > 1, "Black frame in exported video, minimum RGB \(minimumMean)")
78 try require(compared == expectedFrames.count, "Missing per-section reference comparisons")
79 print("PASS decoded \(url.lastPathComponent): \(count) frames, \(width)x\(height), \(fps) fps, soundtrack present, minimum RGB \(minimumMean)")
80 if compared > 0 { print("PASS \(compared) Studio sections match default-profile native preview samples after compression; largest mean RGB error \(largestError)") }
81 }
82 @MainActor static func referenceFrames(scenes: [Int], width: Int, height: Int, fps: Int,
83 analyzer: SoundtrackAnalyzer, duration: Double) throws -> [Int: [UInt8]] {
84 let state = RenderState(), renderer = VisualizerRenderer(state: state)
85 try renderer.prepareOffscreen(width: width, height: height)
86 var result: [Int: [UInt8]] = [:]
87 for (index,scene) in scenes.enumerated() {
88 state.scene = scene; VisualPreset.defaults(for: scene).apply(to: state)
89 let time = Double(index) + 0.5
90 let features = try analyzer.frame(at: time, clipStart: 0, clipEnd: duration)
91 let frame = pixels(try renderer.renderOffscreen(time: time, audioBands: features.bands,
92 audioPulse: features.pulse, audioMomentum: features.momentum, audioBeatMotionTime: features.beatMotionTime,
93 audioTreblePulse: features.treblePulse, audioTrebleAttackTime: features.trebleAttackTime, audioEnvelopes: features.envelopes, audioSwell: features.swell))
94 var samples: [UInt8] = []
95 for y in Swift.stride(from: 0, to: height, by: 16) {
96 for x in Swift.stride(from: 0, to: width, by: 16) {
97 let offset = (y*width+x)*4
98 samples += [frame[offset],frame[offset+1],frame[offset+2]]
99 }
100 }
101 result[Int((Double(index) + 0.5)*Double(fps))] = samples
102 }
103 return result
104 }
105 @MainActor static func main() async {
106 NSApplication.shared.setActivationPolicy(.accessory)
107 do { try await run() } catch { print("FAIL: \(error.localizedDescription)"); exit(1) }
108 }
109 @MainActor static func run() async throws {
110 let root = URL(fileURLWithPath: ".build/native-export-agreement", isDirectory: true)
111 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
112 let source = URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3")
113 let active = NativeEffects.activeIDs
114 try require(active.count >= 4, "Expected at least four active native effects")
115 let scenes = [active[0], active[active.count / 3], active[2 * active.count / 3], active[active.count - 1]]
116 let duration = Double(scenes.count)
117 let soundtrack = root.appendingPathComponent("soundtrack.wav")
118 try excerpt(source, duration: duration, to: soundtrack)
119 let analyzer = try SoundtrackAnalyzer(url: soundtrack)
120 let segments = scenes.enumerated().map {
121 StudioSegment(start: Double($0.offset), end: Double($0.offset + 1), scene: $0.element)
122 }
123 let exporter = SocialExportController(), state = RenderState()
124 let preferencesKey = "PulseCanvas.videoFormat.v1"
125 let savedFormat = UserDefaults.standard.data(forKey: preferencesKey)
126 defer { UserDefaults.standard.set(savedFormat, forKey: preferencesKey) }
127 exporter.resolution = 720
128 exporter.fps = 30
129 for aspect in [SocialAspect.wide, .phone, .square] {
130 exporter.aspect = aspect
131 let size = aspect.dimensions(resolution:720)
132 let tag = aspect == .wide ? "wide" : (aspect == .phone ? "phone" : "square")
133 let output = root.appendingPathComponent("native-\(tag)-\(UUID().uuidString).mp4")
134 await exporter.export(audioURL: soundtrack, render: state, to: output, segments: segments)
135 try require(exporter.exportedURL == output, exporter.status)
136 let expected = try referenceFrames(scenes:scenes,width:size.width,height:size.height,fps:30,analyzer:analyzer,duration:duration)
137 try await verifyVideo(output,width:size.width,height:size.height,fps:30,duration:duration,expectedFrames:expected)
138 }
139 }
140}