Branchwell

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

Raw 22.4 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1import Foundation
2import AVFoundation
3import Metal
4import CoreGraphics
5import AppKit
6
7private struct StoredStylesFixture: Codable { let presets: [Int:VisualPreset]; let identities: [Int:String]? }
8@main struct ProjectMIntegrationSmoke {
9 @MainActor static func main() async throws {
10 // Prevent the singleton fixture from reading or pruning an installed app's backups.
11 let favoriteKeys = ["PulseCanvas.effectFavorites.v1", "PulseCanvas.metalEffectFavorites.v1"]
12 let savedFavorites = favoriteKeys.map { UserDefaults.standard.object(forKey: $0) }
13 for key in favoriteKeys { UserDefaults.standard.set([String](), forKey: key) }
14 defer {
15 for (key, saved) in zip(favoriteKeys, savedFavorites) {
16 if let saved { UserDefaults.standard.set(saved, forKey: key) }
17 else { UserDefaults.standard.removeObject(forKey: key) }
18 }
19 }
20 let base = ProcessInfo.processInfo.environment["PULSECANVAS_VALIDATION_DIR"] ?? ".build/validation"
21 let root = URL(fileURLWithPath: base).appendingPathComponent("projectm-integration-"+UUID().uuidString)
22 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
23 let suiteName = "PulseCanvas.ProjectM.tests.\(UUID().uuidString)"
24 let defaults = UserDefaults(suiteName:suiteName)!
25 defer {defaults.removePersistentDomain(forName:suiteName)}
26 var library = ProjectMPresets(importedRoot:root.appendingPathComponent("Imported"), defaults:defaults)
27 let report = try JSONSerialization.jsonObject(with:Data(contentsOf:library.bundledRoot.appendingPathComponent("compatibility-report.json"))) as! [String:Any]
28 let countRetained = report["retained"] as! Int
29 let nativeCount = RenderState.nativeSceneNames.count
30 precondition(library.entries.count == countRetained && library.sceneNames.count == countRetained + nativeCount)
31 precondition(library.availableScenes.count == countRetained + NativeEffects.activeIDs.count)
32 let fixtureScene = library.scene(for:"projectm:Dancer/Glowsticks/EoS - glowsticks v2 04 music minimal (benjam's tracer mix).milk")!
33 let secondScene = library.scene(for:"projectm:Dancer/Comet Mirror/EoS + Phat - chasers 14 sentinel 616_1.milk")!
34 precondition(library.sceneNames[fixtureScene] == "Mosaic Nova")
35 let duplicatedNames = Dictionary(grouping: library.sceneNames, by: { $0 }).filter { $0.value.count > 1 }.keys.sorted()
36 if !duplicatedNames.isEmpty { FileHandle.standardError.write(Data("Duplicate display names: \(duplicatedNames)\n".utf8)) }
37 precondition(duplicatedNames.isEmpty, "Every preset needs a unique display name")
38 precondition(library.entries.allSatisfy {$0.title.split(separator:" ").count == 2 && $0.originalTitle != nil && $0.icon != nil})
39 let icons = Set(library.sceneNames.indices.map {library.icon(for:$0)})
40 let invalidIcons = icons.filter { NSImage(systemSymbolName: $0, accessibilityDescription: nil) == nil }.sorted()
41 if !invalidIcons.isEmpty { FileHandle.standardError.write(Data("Invalid icons: \(invalidIcons)\n".utf8)) }
42 precondition(icons.isSuperset(of: Set(library.iconNames)) && invalidIcons.isEmpty)
43 precondition(NativeEffects.activeIDs.allSatisfy { library.icon(for: $0) == NativeEffects.all[$0].icon }, "Native visualizers must use their registered icons")
44 precondition(library.categories.contains("Fractal") && library.categories.contains("Waveform"))
45 precondition(!library.categories.contains("Transitions") && !library.categories.contains("! Transition"))
46 let offered = library.availableScenes
47 precondition(library.collections == ["Native Metal", "Cream of the Crop"])
48 precondition(library.filteredScenes() == offered, "Filters must preserve the strip's original order")
49 precondition(!NativeEffects.activeIDs.contains { NativeEffects.category(for: $0) == "Other native" })
50 for collection in library.collections {
51 let all = library.filteredScenes(collection: collection)
52 precondition(!all.isEmpty && all.allSatisfy { library.collection(for: $0) == collection })
53 for category in library.categories(in: collection) {
54 let scenes = library.filteredScenes(collection: collection, category: category)
55 precondition(!scenes.isEmpty && scenes.allSatisfy { library.category(for: $0) == category })
56 for folder in library.folders(in: category, collection: collection) {
57 precondition(library.filteredScenes(collection: collection, category: category, folder: folder)
58 .allSatisfy { library.preset(for: $0)?.category == folder })
59 }
60 }
61 }
62 precondition(library.filteredScenes(collection: "Native Metal", category: "Tunnels").contains(22))
63 precondition(library.filteredScenes(query: "Nested Spiral", collection: "Cream of the Crop")
64 .allSatisfy { library.preset(for: $0)?.category.localizedCaseInsensitiveContains("Nested Spiral") == true })
65 print("PASS Library filters: native themes, upstream categories/subfolders, collection and search intersection, unchanged order")
66 library.toggleFavorite(fixtureScene); library.toggleFavorite(22)
67 let restored = ProjectMPresets(importedRoot:root.appendingPathComponent("Imported"), defaults:defaults)
68 precondition(restored.isFavorite(fixtureScene) && restored.isFavorite(22))
69 library.toggleFavorite(fixtureScene); precondition(!library.isFavorite(fixtureScene))
70 // Existing imported libraries must remain readable even though the app
71 // no longer exposes an import action. Write an old-format disk fixture.
72 let previousNames = library.sceneNames
73 let pack = library.importedRoot.appendingPathComponent("FixturePack")
74 try FileManager.default.createDirectory(at:pack.appendingPathComponent("Waves"),withIntermediateDirectories:true)
75 let preset = ProjectMPresets.shared.preset(for:fixtureScene)!
76 try FileManager.default.copyItem(at:ProjectMPresets.shared.url(for:preset),to:pack.appendingPathComponent("Waves/Fixture.milk"))
77 try Data([0,1,2]).write(to:pack.appendingPathComponent("Waves/texture.png"))
78 let imported = ProjectMPreset(id:"import:FixturePack/Waves/Fixture.milk",path:"FixturePack/Waves/Fixture.milk",title:"Fixture Wave",category:"Imported · FixturePack",originalTitle:"Fixture",icon:"waveform")
79 try JSONEncoder().encode([imported]).write(to:library.importedRoot.appendingPathComponent("imports.json"))
80 library = ProjectMPresets(importedRoot:library.importedRoot,defaults:defaults)
81 let scene = library.scene(for:imported.id)!
82 precondition(Array(library.sceneNames.prefix(previousNames.count)) == previousNames)
83 precondition(scene == countRetained + nativeCount && library.url(for:imported).lastPathComponent == "Fixture.milk")
84 precondition(FileManager.default.fileExists(atPath:library.url(for:imported).deletingLastPathComponent().appendingPathComponent("texture.png").path))
85 let restoredImport = ProjectMPresets(importedRoot:library.importedRoot, defaults:defaults)
86 precondition(restoredImport.scene(for:imported.id) == scene)
87 precondition(restoredImport.isFavorite(22))
88 let ids = library.identities(for:[0,fixtureScene,scene]); precondition(ids.count == 3 && ids[scene] == imported.id && ids[0] == "native:0")
89 let firstLegacy = legacyPresetID(library)
90 let movedExternal = try library.migratedScene(31, identities: [31: firstLegacy])
91 precondition(movedExternal == library.scene(for: firstLegacy) && movedExternal >= nativeCount)
92 let newNative = try library.migratedScene(31, identities: [31: "native:31"])
93 precondition(newNative == 31)
94 print("PASS Library: all presets indexed, categories, stable identities, persistent favorites and legacy imports with textures")
95
96 let legacy = try JSONDecoder().decode([String].self,from:Data(contentsOf:library.bundledRoot.appendingPathComponent("legacy-identities.json")))
97 let oldFixture = legacy.firstIndex(of:library.identity(for:fixtureScene))! + 31
98 let retiredID = "projectm:Fractal/Blobby/va ultramix2 - 28.milk"
99 let oldRetired = legacy.firstIndex(of:retiredID)! + 31
100 precondition(library.scene(for:retiredID) == nil && library.retiredIDs.contains(retiredID))
101 var nativeAppearance = VisualPreset(); nativeAppearance.chaos = 0.22
102 var fixtureAppearance = VisualPreset(); fixtureAppearance.chaos = 0.42
103 let original = CreatorProject(scene:oldRetired,appearance:VisualPreset(),aspect:SocialAspect.landscape.rawValue,resolution:1080,fps:60,
104 timeline:[StudioSegment(start:0,end:8,scene:oldFixture),StudioSegment(start:8,end:16,scene:oldRetired),StudioSegment(start:16,end:24,scene:22)],
105 studioEnabled:true,visualPresets:[oldFixture:fixtureAppearance,oldRetired:VisualPreset(),22:nativeAppearance],
106 effectIdentities:[oldFixture:library.identity(for:fixtureScene),oldRetired:retiredID])
107 for useIdentities in [true,false] {
108 var project = original; if !useIdentities {project.effectIdentities = nil}
109 defaults.set(try JSONEncoder().encode(StoredStylesFixture(presets:project.visualPresets!,identities:project.effectIdentities)),forKey:"PulseCanvas.studio.v1")
110 let migratedStore = StudioStore(defaults:defaults)
111 precondition(migratedStore.presets.count == 2 && migratedStore.presets[fixtureScene]?.chaos == 0.42 && migratedStore.presets[22]?.chaos == 0.22)
112 let migrated = try project.remapped(using:library)
113 precondition(migrated.scene == 22 && migrated.timeline?.map(\.scene) == [fixtureScene,22,22])
114 precondition(migrated.appearance.chaos == 0.22, "The selected retired effect must use the saved fallback appearance")
115 precondition(migrated.timeline?.map {[$0.start,$0.end]} == [[0,8],[8,16],[16,24]])
116 precondition(migrated.visualPresets?.count == 2 && migrated.visualPresets?[fixtureScene]?.chaos == 0.42 && migrated.visualPresets?[22]?.chaos == 0.22)
117 }
118 var missingImport = original; missingImport.effectIdentities = [oldFixture:library.identity(for:fixtureScene),oldRetired:"import:missing/preset.milk"]
119 do {_ = try missingImport.remapped(using:library); fatalError("Missing user imports must report an error")} catch is ProjectMError {}
120 let preview = ProjectMPreviewSize.dimensions(width:3840,height:2160)
121 let portraitPreview = ProjectMPreviewSize.dimensions(width:2160,height:3840)
122 precondition(preview.width == 1280 && preview.height == 720 && portraitPreview.width == 720 && portraitPreview.height == 1280)
123 precondition(ProjectMPreviewSize.dimensions(width:577,height:325).width == 577)
124 print("PASS retirement migration: stable IDs and older numeric indices retain styles; retired clips fall back without collisions, boundaries unchanged; missing imports report errors")
125 print("PASS preview sizing: capped for Retina performance; aspect ratio and small canvases retained")
126
127 let audioURL = root.appendingPathComponent("soundtrack.wav")
128 let format = AVAudioFormat(standardFormatWithSampleRate:48000,channels:2)!
129 let buffer = AVAudioPCMBuffer(pcmFormat:format,frameCapacity:115200)!
130 buffer.frameLength = 115200
131 for frame in 0..<115200 {
132 let t = Double(frame)/48000
133 let envelope = exp(-fmod(t,0.25)*20)
134 buffer.floatChannelData![0][frame] = Float(sin(t*2*Double.pi*180)*envelope*0.85)
135 buffer.floatChannelData![1][frame] = Float(sin(t*2*Double.pi*660)*envelope*0.7)
136 }
137 do {let audio = try AVAudioFile(forWriting:audioURL,settings:format.settings); try audio.write(from:buffer)}
138 let analysis = try SoundtrackAnalyzer(url:audioURL)
139 let beginning = try analysis.pcm(at:0)
140 precondition(beginning.allSatisfy {$0 == 0})
141 let pcm = try analysis.pcm(at:0.1)
142 precondition(pcm.count == 2048 && pcm.contains {$0 != 0})
143 precondition(stride(from:0,to:pcm.count,by:2).contains {pcm[$0] != pcm[$0+1]})
144 print("PASS audio: 48 kHz source resamples to stereo 44.1 kHz; no lookahead before track start")
145
146 let state = RenderState(), renderer = VisualizerRenderer(state:state)
147 state.scene = fixtureScene; state.chaos = 1; state.zoomSpeed = 0
148 try renderer.prepareOffscreen(width:320,height:180)
149 var last: MTLTexture?
150 for frame in 0..<60 {
151 let t = Double(frame)/60
152 state.audioPCM = try analysis.pcm(at:t)
153 last = try renderer.renderOffscreen(time:t,audioBands:[],audioPulse:0)
154 }
155 var pixels = [UInt8](repeating:0,count:320*180*4)
156 last!.getBytes(&pixels,bytesPerRow:320*4,from:MTLRegionMake2D(0,0,320,180),mipmapLevel:0)
157 precondition(stride(from:0,to:pixels.count,by:4).contains {max(pixels[$0],pixels[$0+1],pixels[$0+2]) > 20})
158 print("PASS rendering: preset equations, waves and feedback produce GPU output through the Metal compositor")
159 for (width, height) in [(577,325),(513,287),(63,99),(719,959),(3840,2160)] {
160 try renderer.prepareOffscreen(width:width,height:height)
161 let texture = try renderer.renderOffscreen(time:1.1,audioBands:[],audioPulse:0)
162 precondition(texture.width == width && texture.height == height)
163 }
164 print("PASS shared GPU surfaces: arbitrary window widths, portrait and 4K render without stride validation failures")
165 // Save and restore the user's format settings, which this test changes only temporarily.
166 let formatKey = "PulseCanvas.videoFormat.v1", savedFormat = UserDefaults.standard.data(forKey:formatKey)
167 defer {if let savedFormat {UserDefaults.standard.set(savedFormat,forKey:formatKey)} else {UserDefaults.standard.removeObject(forKey:formatKey)}}
168 let export = SocialExportController(); export.resolution = 720; export.fps = 30; export.aspect = .portrait
169 let destination = root.appendingPathComponent("studio.mp4")
170 let sections = [StudioSegment(start:0,end:0.8,scene:fixtureScene),StudioSegment(start:0.8,end:1.6,scene:22),StudioSegment(start:1.6,end:2.4,scene:secondScene)]
171 var appearance = VisualPreset(); appearance.chaos = 1; appearance.zoomSpeed = 0
172 await export.export(audioURL:audioURL,render:state,to:destination,segments:sections,appearances:[fixtureScene:appearance,22:appearance,secondScene:appearance])
173 precondition(export.exportedURL == destination, export.status)
174 let asset = AVURLAsset(url:destination)
175 let duration = try await asset.load(.duration).seconds
176 let video = try await asset.loadTracks(withMediaType:.video)
177 let tracks = try await asset.loadTracks(withMediaType:.audio)
178 precondition(!tracks.isEmpty && !video.isEmpty && abs(duration-2.4)<0.05)
179 let dimensions = try await video[0].load(.naturalSize)
180 precondition(dimensions.width == 720 && dimensions.height == 960)
181 let generator = AVAssetImageGenerator(asset:asset)
182 for timestamp in [0.6,1.4,2.2] {
183 let result = try await generator.image(at:CMTime(seconds:timestamp,preferredTimescale:600))
184 precondition(result.image.width == 720 && result.image.height == 960)
185 var decoded = [UInt8](repeating:0,count:64*64*4)
186 decoded.withUnsafeMutableBytes { bytes in
187 let context = CGContext(data:bytes.baseAddress,width:64,height:64,bitsPerComponent:8,bytesPerRow:64*4,space:CGColorSpaceCreateDeviceRGB(),bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)!
188 context.draw(result.image,in:CGRect(x:0,y:0,width:64,height:64))
189 }
190 precondition(stride(from:0,to:decoded.count,by:4).contains {max(decoded[$0],decoded[$0+1],decoded[$0+2]) > 20}, "Section \(timestamp) must contain visible exported graphics")
191 }
192 print("PASS export: portrait MP4 decodes all three Studio sections across ProjectM / Metal / ProjectM, includes soundtrack, correct duration and dimensions")
193
194 // These effects went black only after a preceding preset left its clock
195 // and audio history in the shared engine. Check their actual 4K MP4 frames.
196 let transitionIDs = [
197 "projectm:Waveform/Wire Flat Double/suksma - demonizer - a shot.milk",
198 "projectm:Dancer/Comet Mirror/beta106S + Phat - sentinel linearity b nz+ ski mbullox.milk",
199 "projectm:Waveform/Wire Circular/phinjamain.milk",
200 "projectm:Fractal/Nested Spiral/Stahlregen - Spiral Beats (Fluctuating Flowers).milk"
201 ]
202 let transitionScenes = [fixtureScene] + transitionIDs.map { library.scene(for: $0)! }
203 let transitionSections = transitionScenes.enumerated().map {
204 StudioSegment(start: Double($0.offset) * 0.48, end: Double($0.offset + 1) * 0.48, scene: $0.element)
205 }
206 export.resolution = 2160; export.fps = 60; export.aspect = .wide
207 let transitionDestination = root.appendingPathComponent("transitions-4k.mp4")
208 await export.export(audioURL: audioURL, render: state, to: transitionDestination, segments: transitionSections,
209 appearances: Dictionary(uniqueKeysWithValues: transitionScenes.map { ($0, appearance) }))
210 precondition(export.exportedURL == transitionDestination, export.status)
211 let transitionAsset = AVURLAsset(url: transitionDestination)
212 let transitionGenerator = AVAssetImageGenerator(asset: transitionAsset)
213 transitionGenerator.requestedTimeToleranceBefore = .zero; transitionGenerator.requestedTimeToleranceAfter = .zero
214 for (index, section) in transitionSections.enumerated() {
215 let result = try await transitionGenerator.image(at: CMTime(seconds: section.start + 0.4, preferredTimescale: 600))
216 precondition(result.image.width == 3840 && result.image.height == 2160)
217 var decoded = [UInt8](repeating: 0, count: 128 * 72 * 4)
218 decoded.withUnsafeMutableBytes { bytes in
219 let context = CGContext(data: bytes.baseAddress, width: 128, height: 72, bitsPerComponent: 8, bytesPerRow: 128 * 4,
220 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
221 context.draw(result.image, in: CGRect(x: 0, y: 0, width: 128, height: 72))
222 }
223 let visible = stride(from: 0, to: decoded.count, by: 4).filter { max(decoded[$0], decoded[$0 + 1], decoded[$0 + 2]) > 24 }.count
224 print("4K section \(index + 1), \(library.sceneNames[section.scene]): \(visible)/9216 visible pixels"); fflush(stdout)
225 precondition(visible > 128 * 72 / 100, "4K section \(index + 1), \(library.sceneNames[section.scene]), must contain visible graphics")
226 }
227 print("PASS 4K/60 export: decoded Tangled Weave, Crimson Spark, Temporal Flame and Spiral Helix after consecutive ProjectM switches")
228 if ProcessInfo.processInfo.environment["PULSECANVAS_ADMISSION_EXPORT"] == "1" {
229 let receipt = try JSONSerialization.jsonObject(with: Data(contentsOf: library.bundledRoot.appendingPathComponent("preset-admissions.json"))) as! [String: Any]
230 let admissions = receipt["presets"] as! [[String: Any]]
231 let scenes = admissions.map { library.scene(for: $0["id"] as! String)! }
232 let demo = try AVAudioFile(forReading: URL(fileURLWithPath: "Sources/PulseCanvas/Resources/Audio/PulseCanvas.mp3"))
233 let rate = demo.processingFormat.sampleRate
234 demo.framePosition = AVAudioFramePosition(42 * rate)
235 let length = AVAudioFrameCount(Double(scenes.count * 4) * rate)
236 let music = AVAudioPCMBuffer(pcmFormat: demo.processingFormat, frameCapacity: length)!
237 try demo.read(into: music)
238 precondition(music.frameLength == length)
239 let realMusic = root.appendingPathComponent("admissions-soundtrack.wav")
240 do { let file = try AVAudioFile(forWriting: realMusic, settings: demo.processingFormat.settings); try file.write(from: music) }
241 let sections = scenes.enumerated().map { StudioSegment(start: Double($0.offset * 4), end: Double(($0.offset + 1) * 4), scene: $0.element) }
242 export.resolution = 1080; export.fps = 30; export.aspect = .wide
243 let movie = root.appendingPathComponent("admissions-full-hd.mp4")
244 await export.export(audioURL: realMusic, render: state, to: movie, segments: sections,
245 appearances: Dictionary(uniqueKeysWithValues: scenes.map { ($0, appearance) }))
246 precondition(export.exportedURL == movie, export.status)
247 let asset = AVURLAsset(url: movie)
248 let audio = try await asset.loadTracks(withMediaType: .audio)
249 let movieDuration = try await asset.load(.duration).seconds
250 precondition(!audio.isEmpty && abs(movieDuration - Double(scenes.count * 4)) < 0.05)
251 let generator = AVAssetImageGenerator(asset: asset)
252 generator.requestedTimeToleranceBefore = .zero; generator.requestedTimeToleranceAfter = .zero
253 for section in sections {
254 for offset in [2.5, 3.8] {
255 let image = try await generator.image(at: CMTime(seconds: section.start + offset, preferredTimescale: 600)).image
256 precondition(image.width == 1920 && image.height == 1080)
257 var pixels = [UInt8](repeating: 0, count: 160 * 90 * 4)
258 pixels.withUnsafeMutableBytes {
259 let context = CGContext(data: $0.baseAddress, width: 160, height: 90, bitsPerComponent: 8,
260 bytesPerRow: 640, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
261 context.draw(image, in: CGRect(x: 0, y: 0, width: 160, height: 90))
262 }
263 let visible = stride(from: 0, to: pixels.count, by: 4).filter { max(pixels[$0], pixels[$0+1], pixels[$0+2]) > 24 }.count
264 print("Admission \(library.sceneNames[section.scene]) @ \(offset): \(visible)/14400 pixels"); fflush(stdout)
265 precondition(visible > 144, "Admission export black: \(library.sceneNames[section.scene])")
266 }
267 }
268 print("PASS admission export: \(scenes.count) restored presets, actual music, consecutive Studio switches, full-HD MP4 decoded at two times each; soundtrack and duration verified: \(movie.path)")
269 }
270
271 }
272 @MainActor private static func legacyPresetID(_ library: ProjectMPresets) -> String {
273 library.entries[0].id
274 }
275}