PulseCanvas / app · pulsecanvas.ai / scripts / HighFrameRateSmoke.swift
| 1 | import AppKit |
| 2 | @preconcurrency import AVFoundation |
| 3 | import Foundation |
| 4 | import CryptoKit |
| 5 | |
| 6 | /// Exercise the actual exporter, then decode every frame rather than trusting metadata. |
| 7 | @main struct HighFrameRateSmoke { |
| 8 | static func require(_ value: Bool, _ message: String) throws { |
| 9 | if !value { throw ExportError(message) } |
| 10 | } |
| 11 | |
| 12 | static func verify(_ url: URL, width: Int, height: Int, fps: Int, duration: Double, allowPresetStartup: Bool) async throws -> (frames: Int, startupDarkFrames: Int, laterDarkFrames: Int) { |
| 13 | let asset = AVURLAsset(url: url) |
| 14 | let tracks = try await asset.loadTracks(withMediaType: .video) |
| 15 | guard let track = tracks.first else { throw ExportError("Video track missing") } |
| 16 | let size = try await track.load(.naturalSize) |
| 17 | let rate = try await track.load(.nominalFrameRate) |
| 18 | let seconds = try await asset.load(.duration).seconds |
| 19 | try require(size.width == Double(width) && size.height == Double(height), "Incorrect dimensions") |
| 20 | try require(abs(rate - Float(fps)) < 0.01 && abs(seconds - duration) < 0.02, "Incorrect frame rate/duration") |
| 21 | let audioTracks = try await asset.loadTracks(withMediaType: .audio) |
| 22 | try require(!audioTracks.isEmpty, "Soundtrack missing") |
| 23 | let reader = try AVAssetReader(asset: asset) |
| 24 | let output = AVAssetReaderTrackOutput(track: track, outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 25 | reader.add(output) |
| 26 | try require(reader.startReading(), "Decoder did not start") |
| 27 | var count = 0, startupDarkFrames = 0, laterDarkFrames = 0, hashes = Set<String>() |
| 28 | while let sample = output.copyNextSampleBuffer() { |
| 29 | let time = CMSampleBufferGetPresentationTimeStamp(sample).seconds |
| 30 | try require(abs(time - Double(count) / Double(fps)) < 0.0001, "Frame timestamp gap at \(count)") |
| 31 | guard let buffer = CMSampleBufferGetImageBuffer(sample) else { throw ExportError("Missing image") } |
| 32 | CVPixelBufferLockBaseAddress(buffer, .readOnly) |
| 33 | let data = CVPixelBufferGetBaseAddress(buffer)!.assumingMemoryBound(to: UInt8.self) |
| 34 | let row = CVPixelBufferGetBytesPerRow(buffer) |
| 35 | var pixels = Data(), sum = 0 |
| 36 | for y in stride(from: 0, to: height, by: 32) { |
| 37 | for x in stride(from: 0, to: width, by: 32) { |
| 38 | for channel in 0..<3 { |
| 39 | let byte = data[y * row + x * 4 + channel] |
| 40 | pixels.append(byte); sum += Int(byte) |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | CVPixelBufferUnlockBaseAddress(buffer, .readOnly) |
| 45 | if Double(sum) / Double(pixels.count) <= 1 { |
| 46 | // Record brightness separately so timing/decoding evidence survives |
| 47 | // a preset that becomes too dark at the experimental frame rate. |
| 48 | if allowPresetStartup && time < 0.5 { startupDarkFrames += 1 } |
| 49 | else { laterDarkFrames += 1 } |
| 50 | } |
| 51 | hashes.insert(SHA256.hash(data: pixels).description) |
| 52 | count += 1 |
| 53 | } |
| 54 | try require(reader.status == .completed && count == Int(duration * Double(fps)), "Missing decoded frames") |
| 55 | try require(hashes.count > count / 2, "Animation is largely duplicated") |
| 56 | // Decode audio too, to catch a broken mux rather than merely an empty track. |
| 57 | let audioReader = try AVAssetReader(asset: asset) |
| 58 | let audioOutput = AVAssetReaderTrackOutput(track: audioTracks[0], outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM]) |
| 59 | audioReader.add(audioOutput) |
| 60 | try require(audioReader.startReading(), "Audio decoder did not start") |
| 61 | var audioSamples = 0 |
| 62 | while let sample = audioOutput.copyNextSampleBuffer() { audioSamples += CMSampleBufferGetNumSamples(sample) } |
| 63 | try require(audioReader.status == .completed && audioSamples > 0, "Audio decoding failed") |
| 64 | return (count, startupDarkFrames, laterDarkFrames) |
| 65 | } |
| 66 | |
| 67 | @MainActor static func main() async { |
| 68 | NSApplication.shared.setActivationPolicy(.accessory) |
| 69 | do { try await run() } catch { fputs("FAIL: \(error.localizedDescription)\n", stderr); exit(1) } |
| 70 | } |
| 71 | |
| 72 | @MainActor static func run() async throws { |
| 73 | let args = CommandLine.arguments |
| 74 | guard args.count == 2 else { throw ExportError("Usage: HighFrameRateSmoke OUTPUT_DIRECTORY_ON_MUSIC") } |
| 75 | let root = URL(fileURLWithPath: args[1], isDirectory: true).standardizedFileURL |
| 76 | try require(root.path.hasPrefix("/Volumes/Music/"), "Benchmarks must use the Music drive") |
| 77 | let volume = try URL(fileURLWithPath: "/Volumes/Music").resourceValues(forKeys: [.isVolumeKey]) |
| 78 | try require(volume.isVolume == true, "Music drive is not mounted") |
| 79 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 80 | let key = "PulseCanvas.videoFormat.v1", saved = UserDefaults.standard.data(forKey: "PulseCanvas.videoFormat.v1") |
| 81 | defer { |
| 82 | if let saved { UserDefaults.standard.set(saved, forKey: key) } |
| 83 | else { UserDefaults.standard.removeObject(forKey: key) } |
| 84 | } |
| 85 | let duration = 3.0 |
| 86 | let audio = root.appendingPathComponent("soundtrack-excerpt.wav") |
| 87 | let source = try AVAudioFile(forReading: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3")) |
| 88 | source.framePosition = AVAudioFramePosition(42 * source.processingFormat.sampleRate) |
| 89 | let count = AVAudioFrameCount(duration * source.processingFormat.sampleRate) |
| 90 | let buffer = AVAudioPCMBuffer(pcmFormat: source.processingFormat, frameCapacity: count)! |
| 91 | try source.read(into: buffer, frameCount: count) |
| 92 | var settings = source.processingFormat.settings |
| 93 | settings[AVLinearPCMIsNonInterleaved] = false |
| 94 | try AVAudioFile(forWriting: audio, settings: settings).write(from: buffer) |
| 95 | guard let scene = RenderState.nativeSceneNames.firstIndex(of: "Octagon Vault") else { throw ExportError("Benchmark scene missing") } |
| 96 | let exporter = SocialExportController(scratchDirectory: root) |
| 97 | exporter.aspect = .wide; exporter.resolution = 1080; exporter.fps = 120 |
| 98 | try require(SocialExportController().fps == 120, "120 fps preference does not restore") |
| 99 | let appearance = VisualPreset.defaults(for: scene) |
| 100 | let project = CreatorProject(scene: scene, appearance: appearance, aspect: SocialAspect.wide.rawValue, resolution: 1080, fps: 120) |
| 101 | let decoded = try JSONDecoder().decode(CreatorProject.self, from: JSONEncoder().encode(project)) |
| 102 | try require(decoded.fps == 120 && SocialExportController.supportedFrameRates.contains(decoded.fps), "120 fps project round trip failed") |
| 103 | var cases: [(String, SocialAspect, Int, Int, Int, Bool)] = [ |
| 104 | ("native-1080p-60", .wide, 1080, 60, scene, false), |
| 105 | ("native-1080p-120", .wide, 1080, 120, scene, false), |
| 106 | ("native-4K-60", .wide, 2160, 60, scene, false), |
| 107 | ("native-4K-120", .wide, 2160, 120, scene, false), |
| 108 | ("phone-120", .phone, 720, 120, scene, false), |
| 109 | ("studio-120", .square, 720, 120, scene, true) |
| 110 | ] |
| 111 | #if !STORE_BUILD |
| 112 | let presets = try JSONDecoder().decode([ProjectMPreset].self, from: Data(contentsOf: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/ProjectM/catalog.json"))) |
| 113 | guard let external = presets.first, let externalScene = ProjectMPresets.shared.scene(for: external.id) else { throw ExportError("OpenGL benchmark preset missing") } |
| 114 | cases.append(("opengl-60", .wide, 720, 60, externalScene, false)) |
| 115 | cases.append(("opengl-120", .wide, 720, 120, externalScene, false)) |
| 116 | if let glass = presets.first(where: { $0.title == "Glass Chamber" }), let glassScene = ProjectMPresets.shared.scene(for: glass.id) { |
| 117 | cases.append(("opengl-glass-chamber-120", .wide, 720, 120, glassScene, false)) |
| 118 | } |
| 119 | #endif |
| 120 | var results: [[String: Any]] = [] |
| 121 | var brightnessFailures = 0 |
| 122 | for (name, aspect, resolution, fps, selectedScene, studio) in cases { |
| 123 | let state = RenderState() |
| 124 | state.scene = selectedScene |
| 125 | VisualPreset.defaults(for: selectedScene).apply(to: state) |
| 126 | state.chaos = 1 |
| 127 | exporter.aspect = aspect; exporter.resolution = resolution; exporter.fps = fps |
| 128 | let secondScene = RenderState.nativeSceneNames.firstIndex(of: "Double Twist")! |
| 129 | let segments = studio ? [StudioSegment(start: 0, end: 1.5, scene: selectedScene), StudioSegment(start: 1.5, end: duration, scene: secondScene)] : [] |
| 130 | let destination = root.appendingPathComponent(name + ".mp4") |
| 131 | let start = ProcessInfo.processInfo.systemUptime |
| 132 | await exporter.export(audioURL: audio, render: state, to: destination, segments: segments) |
| 133 | let elapsed = ProcessInfo.processInfo.systemUptime - start |
| 134 | try require(exporter.exportedURL == destination, exporter.status) |
| 135 | try require(exporter.totalFrames == Int(duration * Double(fps)) && exporter.renderedFrames == exporter.totalFrames, "Incorrect rendered frame count") |
| 136 | let size = aspect.dimensions(resolution: resolution) |
| 137 | let decoded = try await verify(destination, width: size.width, height: size.height, fps: fps, duration: duration, allowPresetStartup: selectedScene >= RenderState.nativeSceneNames.count) |
| 138 | let frames = decoded.frames |
| 139 | let visible = decoded.laterDarkFrames == 0 |
| 140 | if !visible { brightnessFailures += 1 } |
| 141 | let result: [String: Any] = ["case": name, "visualizer": RenderState.sceneNames[selectedScene], "width": size.width, "height": size.height, "fps": fps, "duration": duration, "decodedFrames": frames, "startupDarkFrames": decoded.startupDarkFrames, "laterDarkFrames": decoded.laterDarkFrames, "timingAudioMotion": "passed", "brightnessCheck": visible ? "passed" : "failed", "exportSeconds": elapsed, "endToEndFramesPerSecond": Double(frames) / elapsed, "lastProgressFramesPerSecond": exporter.framesPerSecond, "path": destination.path] |
| 142 | results.append(result) |
| 143 | print("PASS \(name): \(frames) decoded frames, exact cadence, audio and motion; \(decoded.startupDarkFrames) startup dark frames; export \(String(format: "%.2f", elapsed)) s (\(String(format: "%.1f", Double(frames) / elapsed)) frames/s)") |
| 144 | if !visible { print("FAIL \(name) brightness check: \(decoded.laterDarkFrames) frames have sampled mean RGB <= 1 after startup") } |
| 145 | } |
| 146 | let receipt: [String: Any] = ["date": ISO8601DateFormatter().string(from: Date()), "results": results, "preferencesAndProjectRoundTrip": "passed", "decoder": "AVAssetReader, every video frame and all audio samples", "encoder": "H.264, hardware acceleration requested; backend use not instrumented"] |
| 147 | try JSONSerialization.data(withJSONObject: receipt, options: [.prettyPrinted, .sortedKeys]).write(to: root.appendingPathComponent("receipt.json")) |
| 148 | try require(brightnessFailures == 0, "\(brightnessFailures) visual brightness checks failed; complete timing and benchmark results are in receipt.json") |
| 149 | } |
| 150 | } |