Branchwell

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

Raw 6.8 KB on 32796b3b2cff314d20e7c78bdc17d74e2eace8c1
1import Foundation
2@preconcurrency import AVFoundation
3import Metal
4
5@main struct VisionInterchangeExportSmoke {
6 @MainActor static func main() async throws {
7 let root = URL(fileURLWithPath: ProcessInfo.processInfo.environment["PULSECANVAS_VALIDATION_OUTPUT"]
8 ?? FileManager.default.temporaryDirectory.appendingPathComponent("PulseCanvas-Vision-export-validation").path)
9 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
10 let scenes = Array(NativeEffects.activeIDs.prefix(3))
11 var native = VisionProject()
12 native.clips = [VisionClip(scene: scenes[0], bars: 1), VisionClip(scene: scenes[1], bars: 2),
13 VisionClip(scene: scenes[2], bars: 1)]
14 native.barBoundaries = [0, 1, 2, 3, 4]
15 native.loopPlayback = false
16 native.looks[scenes[0]] = VisionLook(scene: scenes[0])
17 native.looks[scenes[0]]!.chaos = 0.87
18 native.looks[scenes[0]]!.motionBlur = 0.2
19 native.looks[scenes[0]]!.rotation = 0.7
20 native.looks[scenes[0]]!.haloCount = 9
21 native.looks[scenes[0]]!.strobeSensitivity = 1.6
22 let data = try native.portableData(duration: 4, scene: scenes[0])
23 let mac = try JSONDecoder().decode(CreatorProject.self, from: data).remapped(using: .shared)
24 precondition(mac.version == 1 && mac.bundledSoundtrack == "pulsecanvas" && mac.fps == 60)
25 precondition(mac.loopPlayback == false)
26 precondition(mac.timeline?.map(\.end) == [1, 3, 4] && mac.timeline?.map(\.bars) == [1, 2, 1])
27 precondition(StudioTimeline.valid(mac.timeline!, sceneCount: RenderState.sceneNames.count))
28 precondition(mac.visualPresets?[scenes[0]] == native.looks[scenes[0]]!.preset)
29 let reopened = try VisionProject.openPortable(data)
30 precondition(reopened.clips.map(\.scene) == native.clips.map(\.scene))
31 precondition(reopened.looks[scenes[0]] == native.looks[scenes[0]])
32 precondition(!reopened.loopPlayback)
33 precondition(reopened.segments(duration: 4).map(\.end) == [1, 3, 4])
34 let again = try JSONDecoder().decode(CreatorProject.self, from: reopened.portableData(duration: 4, scene: scenes[0]))
35 precondition(again.appearance == mac.appearance && again.aspect == mac.aspect && again.fps == mac.fps)
36 var external = mac
37 external.bundledSoundtrack = nil; external.soundtrack = URL(fileURLWithPath: "/Users/example/Music/Track.wav")
38 let imported = try VisionProject.openPortable(JSONEncoder().encode(external))
39 precondition(imported.externalAudioURL == external.soundtrack && imported.audioFile == nil)
40 var bad = mac; bad.effectIdentities = [scenes[0]: "community:unsupported"]
41 do { _ = try VisionProject.openPortable(JSONEncoder().encode(bad)); fatalError("External effect accepted") } catch {}
42 try data.write(to: root.appendingPathComponent("Vision-to-Mac.pulsecanvas"))
43 try JSONEncoder().encode(again).write(to: root.appendingPathComponent("Mac-to-Vision-to-Mac.pulsecanvas"))
44 print("PASS shared Mac Codable project: native IDs, exact mixed-bar cuts, all appearance fields, export format, bundled/external audio references and unsupported-effect rejection")
45
46 let audio = root.appendingPathComponent("four-second-drums.wav")
47 let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)!
48 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 176_400)!
49 buffer.frameLength = buffer.frameCapacity
50 for i in 0..<Int(buffer.frameLength) {
51 let t = Double(i) / 44_100, beat = t.truncatingRemainder(dividingBy: 0.4)
52 let sample = Float(sin(2 * .pi * 100 * t) * exp(-beat * 25) * 0.6)
53 buffer.floatChannelData![0][i] = sample; buffer.floatChannelData![1][i] = sample
54 }
55 var file: AVAudioFile? = try AVAudioFile(forWriting: audio, settings: format.settings)
56 try file?.write(from: buffer); file = nil
57 let state = RenderState(); state.scene = scenes[0]
58 let exporter = SocialExportController(scratchDirectory: root)
59 exporter.aspect = .wide; exporter.fps = 60
60 for resolution in [1080, 2160] {
61 exporter.resolution = resolution
62 let width = resolution * 16 / 9
63 let target = root.appendingPathComponent("Vision-\(resolution)p60.mp4")
64 await exporter.export(audioURL: audio, render: state, to: target,
65 segments: native.segments(duration: 4), appearances: native.looks.mapValues(\.preset))
66 precondition(exporter.exportedURL == target, exporter.status)
67 let asset = AVURLAsset(url: target)
68 let video = try await asset.loadTracks(withMediaType: .video).first!
69 let sound = try await asset.loadTracks(withMediaType: .audio).first!
70 let size = try await video.load(.naturalSize), fps = try await video.load(.nominalFrameRate)
71 let duration = try await asset.load(.duration).seconds
72 precondition(size == CGSize(width: width, height: resolution) && fps == 60 && abs(duration - 4) < 0.04)
73 let reader = try AVAssetReader(asset: asset)
74 let output = AVAssetReaderTrackOutput(track: video, outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA])
75 reader.add(output); precondition(reader.startReading())
76 var frames = 0, times: [Double] = [], nonblack = Set<Int>()
77 while let sample = output.copyNextSampleBuffer() {
78 times.append(CMSampleBufferGetPresentationTimeStamp(sample).seconds)
79 if let pixels = CMSampleBufferGetImageBuffer(sample) {
80 CVPixelBufferLockBaseAddress(pixels, .readOnly)
81 let bytes = CVPixelBufferGetBaseAddress(pixels)!.assumingMemoryBound(to: UInt8.self)
82 let stride = CVPixelBufferGetBytesPerRow(pixels)
83 var sum = 0
84 for y in Swift.stride(from: 0, to: resolution, by: 24) {
85 for x in Swift.stride(from: 0, to: width, by: 24) {
86 let offset = y * stride + x * 4; sum += Int(bytes[offset]) + Int(bytes[offset+1]) + Int(bytes[offset+2])
87 }
88 }
89 if sum > 300 { nonblack.insert(min(2, frames < 60 ? 0 : frames < 180 ? 1 : 2)) }
90 CVPixelBufferUnlockBaseAddress(pixels, .readOnly)
91 }
92 frames += 1
93 }
94 precondition(reader.status == .completed && frames == 240 && nonblack == Set([0, 1, 2]))
95 precondition(zip(times, times.dropFirst()).allSatisfy { abs($1 - $0 - 1.0/60) < 0.00001 })
96 let audioRange = try await sound.load(.timeRange)
97 precondition(abs(audioRange.duration.seconds - 4) < 0.06)
98 print("PASS actual decoded export: \(width)×\(resolution) H.264, 240 exact 60-fps frames, nonblack output across three sections, full-length AAC soundtrack")
99 }
100 }
101}