Branchwell

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

Raw 6.2 KB on 0c0f13aedcaf984646237f478d4915d73e9d0aeb
1import Foundation
2import Metal
3import AVFoundation
4import CoreGraphics
5import ImageIO
6import UniformTypeIdentifiers
7
8/// One preset per process: crashes and timeouts cannot poison the next candidate.
9@main struct ProjectMCandidateAudit {
10 struct Candidate: Decodable { let id: String; let path: String; let title: String }
11 static func main() throws {
12 let args = CommandLine.arguments
13 guard args.count == 9, let index = Int(args[3]), let width = Int(args[5]),
14 let height = Int(args[6]), let frames = Int(args[7]), frames >= 90 else {
15 fatalError("Usage: audit UPSTREAM CANDIDATES INDEX OUTPUT WIDTH HEIGHT FRAMES SOUNDTRACK")
16 }
17 let upstream = URL(fileURLWithPath: args[1]), output = URL(fileURLWithPath: args[4])
18 let candidates = try JSONDecoder().decode([Candidate].self, from: Data(contentsOf: URL(fileURLWithPath: args[2])))
19 let preset = candidates[index]
20 let audio = try AVAudioFile(forReading: URL(fileURLWithPath: args[8]))
21 let rate = audio.processingFormat.sampleRate
22 audio.framePosition = min(AVAudioFramePosition(42 * rate), max(0, audio.length - AVAudioFramePosition(12 * rate)))
23 let buffer = AVAudioPCMBuffer(pcmFormat: audio.processingFormat, frameCapacity: AVAudioFrameCount(12 * rate))!
24 try audio.read(into: buffer)
25 let channels = buffer.floatChannelData!, channelCount = Int(buffer.format.channelCount)
26 let sampleCount = Int(buffer.frameLength)
27 let device = MTLCreateSystemDefaultDevice()!, engine = try ProjectMEngine()
28 let url = upstream.appendingPathComponent(preset.path)
29 let textures = URL(fileURLWithPath: "Sources/PulseCanvas/Resources/ProjectM/Textures")
30 var timing: [Double] = [], motion: [Double] = [], coverage: [Double] = [], whites: [Double] = []
31 var previous: [UInt8]?, pixels = [UInt8](repeating: 0, count: width * height * 4)
32 var error: String?
33 do {
34 for frame in 0..<frames {
35 let end = Int(Double(frame + 1) * rate / 30) % max(1, sampleCount)
36 let pcm: [Float] = (0..<1024).flatMap { offset in
37 let sample = (end - 1024 + offset + sampleCount) % sampleCount
38 return [channels[0][sample], channels[min(1, channelCount - 1)][sample]]
39 }
40 let began = Date()
41 let texture = try engine.frame(preset: url, texturePaths: [url.deletingLastPathComponent(), textures],
42 device: device, width: width, height: height, time: Double(frame) / 30,
43 sourceTime: Double(frame) / 30, pcm: pcm, chaos: 1, fps: 30)
44 if frame >= 10 { timing.append(Date().timeIntervalSince(began) * 1000) }
45 // Do not spend minutes in a known high-instance family.
46 if timing.count >= 8, timing.sorted()[timing.count / 2] > 33 { error = "Playback exceeds 33 ms/frame"; break }
47 if frame >= 60 && frame % 15 == 0 {
48 texture.getBytes(&pixels, bytesPerRow: width * 4,
49 from: MTLRegionMake2D(0, 0, width, height), mipmapLevel: 0)
50 var lit = 0, white = 0, difference = 0
51 for y in stride(from: 0, to: height, by: 4) {
52 for x in stride(from: 0, to: width, by: 4) {
53 let p = (y * width + x) * 4
54 if max(pixels[p], pixels[p + 1], pixels[p + 2]) > 24 { lit += 1 }
55 if min(pixels[p], pixels[p + 1], pixels[p + 2]) > 245 { white += 1 }
56 if let previous {
57 difference += (0..<3).reduce(0) { $0 + abs(Int(pixels[p + $1]) - Int(previous[p + $1])) }
58 }
59 }
60 }
61 let samples = Double(((width + 3) / 4) * ((height + 3) / 4))
62 coverage.append(Double(lit) / samples); whites.append(Double(white) / samples)
63 if previous != nil { motion.append(Double(difference) / (samples * 3 * 255)) }
64 previous = pixels
65 if frame == frames - 15 {
66 let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32,
67 bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),
68 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue).union(.byteOrder32Little),
69 provider: CGDataProvider(data: Data(pixels) as CFData)!, decode: nil,
70 shouldInterpolate: false, intent: .defaultIntent)!
71 let destination = CGImageDestinationCreateWithURL(output.deletingPathExtension().appendingPathExtension("png") as CFURL,
72 UTType.png.identifier as CFString, 1, nil)!
73 CGImageDestinationAddImage(destination, image, nil)
74 guard CGImageDestinationFinalize(destination) else { throw CocoaError(.fileWriteUnknown) }
75 }
76 }
77 }
78 } catch let failure { error = failure.localizedDescription }
79 timing.sort()
80 let median = timing.isEmpty ? 0 : timing[timing.count / 2]
81 let p95 = timing.isEmpty ? 0 : timing[Int(Double(timing.count - 1) * 0.95)]
82 let visible = coverage.max() ?? 0, movement = motion.max() ?? 0, white = whites.min() ?? 0
83 let visibleFraction = Double(coverage.filter { $0 >= 0.01 }.count) / Double(max(1, coverage.count))
84 let passed = error == nil && visibleFraction >= 0.8 && movement >= 0.00005 && white <= 0.98 && median <= 33 && p95 <= 40
85 let result: [String: Any] = ["id": preset.id, "path": preset.path, "title": preset.title,
86 "width": width, "height": height, "frames": frames, "medianMS": median, "p95MS": p95,
87 "coverage": visible, "motion": movement, "whiteCoverage": white,
88 "visibleSampleFraction": visibleFraction, "soundtrackPCM": true,
89 "error": error as Any? ?? NSNull(), "passed": passed]
90 try JSONSerialization.data(withJSONObject: result, options: [.prettyPrinted, .sortedKeys]).write(to: output)
91 }
92}