PulseCanvas / app · pulsecanvas.ai / scripts / SocialExportSmoke.swift
| 1 | import AppKit |
| 2 | @preconcurrency import AVFoundation |
| 3 | import Foundation |
| 4 | |
| 5 | @main |
| 6 | struct SocialExportSmoke { |
| 7 | @MainActor static func main() async { |
| 8 | NSApplication.shared.setActivationPolicy(.accessory) |
| 9 | do { try await run() } |
| 10 | catch { print("FAIL: \(error.localizedDescription)"); exit(1) } |
| 11 | } |
| 12 | static func require(_ condition: Bool, _ message: String) throws { |
| 13 | if !condition { throw ExportError(message) } |
| 14 | } |
| 15 | @MainActor static func run() async throws { |
| 16 | let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(".build/social-export-validation", isDirectory: true) |
| 17 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 18 | let soundtrack = root.appendingPathComponent("stereo-test.wav") |
| 19 | let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)! |
| 20 | var settings = format.settings |
| 21 | settings[AVLinearPCMIsNonInterleaved] = false |
| 22 | var file: AVAudioFile? = try AVAudioFile(forWriting: soundtrack, settings: settings) |
| 23 | let pcm = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 88_200)! |
| 24 | pcm.frameLength = 88_200 |
| 25 | for index in 0..<88_200 { |
| 26 | let t = Double(index) / 44_100 |
| 27 | let sample: Float = t < 0.4 ? 0 : Float(0.45 * sin(2 * Double.pi * 200 * t)) |
| 28 | pcm.floatChannelData![0][index] = sample |
| 29 | pcm.floatChannelData![1][index] = -sample // Prevent a mono-downmix shortcut passing. |
| 30 | } |
| 31 | try file?.write(from: pcm) |
| 32 | file = nil |
| 33 | let analyzer = try SoundtrackAnalyzer(url: soundtrack) |
| 34 | let silence = try analyzer.frame(at: 0.15, clipStart: 0, clipEnd: 2).bands |
| 35 | let tone = try analyzer.frame(at: 0.55, clipStart: 0, clipEnd: 2).bands |
| 36 | try require((silence.max() ?? 1) < 0.01 && (tone.max() ?? 0) > 0.5, "FFT must react to actual opposite-phase stereo samples and distinguish silence") |
| 37 | print("PASS: exact-timestamp FFT distinguishes silence and opposite-phase stereo tone") |
| 38 | var detector = StrobeDetector() |
| 39 | var bass = [Float](repeating: 0, count: 32) |
| 40 | for index in 0..<8 { bass[index] = 1 } |
| 41 | try require(detector.nextFrame(time: 0, bands: bass) == 0, "Bass must not trigger hi-hat strobe") |
| 42 | var treble = [Float](repeating: 0, count: 32) |
| 43 | for index in 24..<32 { treble[index] = 1 } |
| 44 | try require(detector.nextFrame(time: 0.05, bands: treble) == 1, "Treble attack must trigger strobe") |
| 45 | try require(detector.nextFrame(time: 0.09, bands: treble) == 0, "Strobe must remain brief and cannot retrigger sustained treble") |
| 46 | print("PASS: optional hi-hat strobe responds to treble attacks, ignores bass, and releases") |
| 47 | let state = RenderState() |
| 48 | state.scene = 10 |
| 49 | let exporter = SocialExportController() |
| 50 | for (index, aspect) in SocialAspect.allCases.enumerated() { |
| 51 | exporter.aspect = aspect |
| 52 | exporter.resolution = index == 4 ? 1080 : 720 |
| 53 | exporter.fps = [24, 30, 60, 24, 30][index] |
| 54 | let target = root.appendingPathComponent("\(index)-\(exporter.fps).mp4") |
| 55 | try? FileManager.default.removeItem(at: target) |
| 56 | await exporter.export(audioURL: soundtrack, render: state, to: target) |
| 57 | try require(exporter.exportedURL == target, exporter.status) |
| 58 | let dimensions = aspect.dimensions(resolution: exporter.resolution) |
| 59 | try await verify(target, width: dimensions.width, height: dimensions.height, |
| 60 | fps: exporter.fps, duration: 2, hasAudio: true) |
| 61 | print("PASS: \(aspect.rawValue) \(dimensions.width)x\(dimensions.height) \(exporter.fps)fps: exact timeline, H.264, full soundtrack stereo AAC") |
| 62 | } |
| 63 | exporter.aspect = .square |
| 64 | exporter.resolution = 720 |
| 65 | exporter.fps = 24 |
| 66 | let silent = root.appendingPathComponent("silent.mp4") |
| 67 | try? FileManager.default.removeItem(at: silent) |
| 68 | await exporter.export(audioURL: nil, render: state, to: silent) |
| 69 | try require(exporter.exportedURL == silent, exporter.status) |
| 70 | try await verify(silent, width: 720, height: 720, fps: 24, duration: 15, hasAudio: false) |
| 71 | print("PASS: procedural silent clip has exact 360-frame timeline and no audio track") |
| 72 | await exporter.export(audioURL: nil, render: state, to: silent) |
| 73 | try require(exporter.exportedURL == silent, "Existing destination replacement failed: \(exporter.status)") |
| 74 | try await verify(silent, width: 720, height: 720, fps: 24, duration: 15, hasAudio: false) |
| 75 | print("PASS: completed export safely replaces an existing destination") |
| 76 | let entire = root.appendingPathComponent("entire-track.mp4") |
| 77 | try? FileManager.default.removeItem(at: entire) |
| 78 | await exporter.export(audioURL: soundtrack, render: state, to: entire) |
| 79 | try require(exporter.exportedURL == entire, exporter.status) |
| 80 | try await verify(entire, width: 720, height: 720, fps: 24, duration: 2, hasAudio: true) |
| 81 | print("PASS: entire soundtrack exports all 48 frames and full 2-second audio") |
| 82 | let cancelled = entire |
| 83 | let preserved = try Data(contentsOf: entire) |
| 84 | let pending = Task { @MainActor in await exporter.export(audioURL: soundtrack, render: state, to: cancelled) } |
| 85 | while !exporter.isExporting { await Task.yield() } |
| 86 | while exporter.isExporting && exporter.progress < 0.1 { try await Task.sleep(for: .milliseconds(2)) } |
| 87 | exporter.cancel() |
| 88 | await pending.value |
| 89 | let afterCancel = try Data(contentsOf: cancelled) |
| 90 | try require(exporter.status == "Export cancelled" && afterCancel == preserved, "Cancellation must preserve existing output") |
| 91 | print("PASS: cancellation preserves existing output and cleans up partial export") |
| 92 | // Drive the real detector from PCM, then decode the compressed output. |
| 93 | let hats = root.appendingPathComponent("treble-attacks.wav") |
| 94 | let hatBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 26_460)! |
| 95 | hatBuffer.frameLength = hatBuffer.frameCapacity |
| 96 | for index in 0..<Int(hatBuffer.frameLength) { |
| 97 | let t = Double(index) / 44_100 |
| 98 | var sample = 0.0 |
| 99 | for attack in [0.06, 0.18, 0.30, 0.42, 0.54] { |
| 100 | let age = t - attack |
| 101 | if age >= 0 && age < 0.025 { |
| 102 | for frequency in [4000.0, 5500, 7000, 8500, 11000, 14000] { |
| 103 | sample += 0.11 * sin(2 * Double.pi * frequency * age) * exp(-60 * age) |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | hatBuffer.floatChannelData![0][index] = Float(sample) |
| 108 | hatBuffer.floatChannelData![1][index] = Float(sample) |
| 109 | } |
| 110 | do { let writer = try AVAudioFile(forWriting: hats, settings: settings); try writer.write(from: hatBuffer) } |
| 111 | state.scene = 19; state.particleSize = 1.6; state.strobeEnabled = true |
| 112 | exporter.aspect = .phone; exporter.resolution = 720; exporter.fps = 60 |
| 113 | let hatVideo = root.appendingPathComponent("hat-strobe.mp4") |
| 114 | await exporter.export(audioURL: hats, render: state, to: hatVideo) |
| 115 | try require(exporter.exportedURL == hatVideo, exporter.status) |
| 116 | let hatFrames = try whiteFrames(hatVideo) |
| 117 | try require(hatFrames.white >= 3 && hatFrames.white < hatFrames.total / 2, "Real treble attacks must produce brief full white frames: \(hatFrames)") |
| 118 | let bassVideo = root.appendingPathComponent("bass-no-strobe.mp4") |
| 119 | await exporter.export(audioURL: soundtrack, render: state, to: bassVideo) |
| 120 | try require(exporter.exportedURL == bassVideo, exporter.status) |
| 121 | let bassFrames = try whiteFrames(bassVideo) |
| 122 | try require(bassFrames.white == 0, "Pure bass must not cause white flashes") |
| 123 | print("PASS: actual treble PCM -> MP4 yields \(hatFrames.white) brief white frames; bass PCM yields none") |
| 124 | let kicks = root.appendingPathComponent("kick-attacks.wav") |
| 125 | let kickBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 48_510)! |
| 126 | kickBuffer.frameLength = kickBuffer.frameCapacity |
| 127 | for index in 0..<Int(kickBuffer.frameLength) { |
| 128 | let time = Double(index) / 44_100 |
| 129 | var value = 0.02 * sin(2 * Double.pi * 440 * time) |
| 130 | for attack in [0.3, 0.8] { |
| 131 | let age = time - attack |
| 132 | if age >= 0 && age < 0.12 { value += 0.65 * exp(-age * 30) * sin(2 * Double.pi * 65 * age) } |
| 133 | } |
| 134 | kickBuffer.floatChannelData![0][index] = Float(value) |
| 135 | kickBuffer.floatChannelData![1][index] = -Float(value) |
| 136 | } |
| 137 | do { let writer = try AVAudioFile(forWriting: kicks, settings: settings); try writer.write(from: kickBuffer) } |
| 138 | state.strobeEnabled = false; state.palette = VisualPalette.blueHour.rawValue |
| 139 | state.speed = 0; state.zoom = 1; state.brightness = 1; state.motionBlur = 0 |
| 140 | let pulseVideo = root.appendingPathComponent("beat-pulse.mp4") |
| 141 | await exporter.export(audioURL: kicks, render: state, to: pulseVideo) |
| 142 | try require(exporter.exportedURL == pulseVideo, exporter.status) |
| 143 | let pulseFrames = try pixelSequence(pulseVideo) |
| 144 | func frameChange(_ a: [UInt8], _ b: [UInt8]) -> Double { |
| 145 | zip(a,b).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(a.count) |
| 146 | } |
| 147 | let firstKick = frameChange(pulseFrames[19],pulseFrames[36]), secondKick = frameChange(pulseFrames[49],pulseFrames[36]) |
| 148 | // Use settled tone before the kick, after the soundtrack onset has released. |
| 149 | let quietChange = frameChange(pulseFrames[12],pulseFrames[36]) |
| 150 | try require(firstKick > 0.5 && secondKick > 0.5 && quietChange < min(firstKick,secondKick)*0.5, |
| 151 | "Decoded MP4 must deform on both actual kicks and release: \(firstKick), \(secondKick), quiet \(quietChange)") |
| 152 | print("PASS: decoded MP4 deforms elements on both PCM kicks and releases, with procedural motion frozen and white strobe disabled") |
| 153 | for scene in [22,23] { |
| 154 | state.scene = scene; state.chaos = 1 |
| 155 | let movie = root.appendingPathComponent("organic-waves-\(scene).mp4") |
| 156 | await exporter.export(audioURL: kicks, render: state, to: movie) |
| 157 | try require(exporter.exportedURL == movie, exporter.status) |
| 158 | let frames = try pixelSequence(movie) |
| 159 | let kickChange = min(frameChange(frames[19],frames[36]),frameChange(frames[49],frames[36])) |
| 160 | let releaseChange = frameChange(frames[12],frames[36]) |
| 161 | try require(kickChange > 0.5 && releaseChange < kickChange*0.5, "Surface waves must follow PCM kicks and relax: scene \(scene), hit \(kickChange), release \(releaseChange)") |
| 162 | print("PASS: \(RenderState.sceneNames[scene]) local waves survive MP4, kick change \(kickChange), relaxed change \(releaseChange)") |
| 163 | } |
| 164 | state.speed = 1; state.chaos = 0 |
| 165 | let calmVideo = root.appendingPathComponent("chaos-low.mp4") |
| 166 | await exporter.export(audioURL: kicks, render: state, to: calmVideo) |
| 167 | try require(exporter.exportedURL == calmVideo && state.chaos == 0, exporter.status) |
| 168 | let calmLevels = try frameBrightness(calmVideo) |
| 169 | state.chaos = 1 |
| 170 | let chaoticVideo = root.appendingPathComponent("chaos-high.mp4") |
| 171 | await exporter.export(audioURL: kicks, render: state, to: chaoticVideo) |
| 172 | try require(exporter.exportedURL == chaoticVideo && state.chaos == 1, exporter.status) |
| 173 | let chaoticLevels = try frameBrightness(chaoticVideo) |
| 174 | let chaosDifference = zip(calmLevels, chaoticLevels).reduce(0.0) { $0 + abs($1.0-$1.1) } / Double(calmLevels.count) |
| 175 | try require(chaosDifference > 0.25, "Decoded exports must preserve and respond to the Chaos setting: \(chaosDifference)") |
| 176 | print("PASS: decoded low/high Chaos exports differ on real PCM beats while retaining the live setting, mean brightness difference \(chaosDifference)") |
| 177 | state.scene = 18; state.palette = 4; state.zoom = 0.8 |
| 178 | exporter.aspect = .wide; exporter.resolution = 720; exporter.fps = 24 |
| 179 | let studioVideo = root.appendingPathComponent("studio-sequence.mp4") |
| 180 | var blue = VisualPreset(); blue.palette = 3; blue.zoom = 1.37; blue.particleSize = 1.9 |
| 181 | var warm = VisualPreset(); warm.palette = 2; warm.zoom = 1.1 |
| 182 | // Compress a seven-bar fixture into two seconds for the decoded export check. |
| 183 | let barsSuite = "PulseCanvas.ExportBars." + UUID().uuidString |
| 184 | let barsDefaults = UserDefaults(suiteName: barsSuite)! |
| 185 | defer { barsDefaults.removePersistentDomain(forName: barsSuite) } |
| 186 | let barsStudio = StudioStore(defaults: barsDefaults), barsState = RenderState() |
| 187 | barsStudio.isStudio = true |
| 188 | barsStudio.segments = [StudioSegment(start: 0, end: 8.0 / 7, scene: 18, bars: 4), StudioSegment(start: 8.0 / 7, end: 2, scene: 20, bars: 4)] |
| 189 | let barsGrid = SongSegmentation(boundaries: (0...7).map { Double($0) * 2 / 7 }, bpm: nil) |
| 190 | try require(barsStudio.setBars(1, at: 1, grid: barsGrid, render: barsState), "Set one-bar middle section") |
| 191 | try require(barsStudio.setBars(2, at: 2, grid: barsGrid, render: barsState), "Set two-bar final section") |
| 192 | barsStudio.segments[2].scene = 18 |
| 193 | let sections = barsStudio.segments |
| 194 | try require(sections.map(\.bars) == [4,1,2], "Export fixture must use individual card lengths") |
| 195 | await exporter.export(audioURL: soundtrack, render: state, to: studioVideo, segments: sections, appearances: [18: blue, 20: warm]) |
| 196 | try require(exporter.exportedURL == studioVideo, exporter.status) |
| 197 | try await verify(studioVideo, width: 1280, height: 720, fps: 24, duration: 2, hasAudio: true) |
| 198 | let colors = try frameColors(studioVideo) |
| 199 | for index in [5, 15, 27, 35, 40] { try require(colors[index].2 > colors[index].0 * 1.4, "Blue section must use shared Blue Hour appearance at frame \(index)") } |
| 200 | for index in [28, 30, 34] { try require(colors[index].0 > colors[index].2 * 1.4, "Warm section must switch on its bar boundary at frame \(index)") } |
| 201 | try require(state.scene == 18 && state.palette == 4 && state.zoom == 0.8, "Export cannot mutate live appearance") |
| 202 | print("PASS: decoded Studio MP4 follows generated 4/1/2 per-card bar timing exactly, repeats shared blue appearance, applies first-section preset, retains live state and full audio") |
| 203 | let fourKAudio = root.appendingPathComponent("4k-soundtrack.wav") |
| 204 | let shortPCM = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 8820)! |
| 205 | shortPCM.frameLength = shortPCM.frameCapacity |
| 206 | for i in 0..<Int(shortPCM.frameLength) { |
| 207 | let sample = Float(0.2 * sin(Double(i) / 44100 * 2 * .pi * 200)) |
| 208 | shortPCM.floatChannelData![0][i] = sample; shortPCM.floatChannelData![1][i] = -sample |
| 209 | } |
| 210 | do { let writer = try AVAudioFile(forWriting: fourKAudio, settings: settings); try writer.write(from: shortPCM) } |
| 211 | exporter.resolution = 2160; exporter.fps = 24 |
| 212 | for aspect in [SocialAspect.wide, .phone] { |
| 213 | exporter.aspect = aspect |
| 214 | let target = root.appendingPathComponent("4k-\(aspect == .wide ? "wide" : "phone").mp4") |
| 215 | await exporter.export(audioURL: fourKAudio, render: state, to: target) |
| 216 | try require(exporter.exportedURL == target, exporter.status) |
| 217 | let size = aspect.dimensions(resolution: 2160) |
| 218 | try await verify(target, width: size.width, height: size.height, fps: 24, duration: 0.2, hasAudio: true) |
| 219 | print("PASS: 4K \(aspect.rawValue) \(size.width)x\(size.height) decodes every frame with full soundtrack") |
| 220 | } |
| 221 | let savedFormat = SocialExportController() |
| 222 | try require(savedFormat.resolution == 2160 && savedFormat.aspect == .phone, "4K project settings persist") |
| 223 | exporter.aspect = .wide; exporter.resolution = 720; exporter.fps = 24 |
| 224 | let spatialScenes = [4,10,12,22,23,24,25,26,27,28,29,30] |
| 225 | let spatialSections = spatialScenes.enumerated().map { index, scene in |
| 226 | StudioSegment(start: Double(index)*2/Double(spatialScenes.count), end: Double(index+1)*2/Double(spatialScenes.count), scene: scene) |
| 227 | } |
| 228 | let spatialPresets = Dictionary(uniqueKeysWithValues: spatialScenes.map { scene in |
| 229 | var preset = VisualPreset(); preset.palette = VisualPalette.blueHour.rawValue; preset.chaos = 0.8 |
| 230 | return (scene,preset) |
| 231 | }) |
| 232 | let spatialVideo = root.appendingPathComponent("spatial-studio.mp4") |
| 233 | await exporter.export(audioURL: soundtrack, render: state, to: spatialVideo, segments: spatialSections, appearances: spatialPresets) |
| 234 | try require(exporter.exportedURL == spatialVideo, exporter.status) |
| 235 | try await verify(spatialVideo, width: 1280, height: 720, fps: 24, duration: 2, hasAudio: true) |
| 236 | let spatialColors = try frameColors(spatialVideo) |
| 237 | for index in spatialScenes.indices { |
| 238 | let frame = Int((Double(index)+0.5)*48/Double(spatialScenes.count)) |
| 239 | try require(spatialColors[frame].2 > spatialColors[frame].0 * 1.8 && spatialColors[frame].2 > 1000, "Every spatial Studio section must render its shared blue preset") |
| 240 | } |
| 241 | print("PASS: decoded Studio export plays all \(spatialScenes.count) spatial designs with shared palettes and full audio") |
| 242 | state.scene = 23 |
| 243 | var liquidPreset = VisualPreset(); liquidPreset.palette = VisualPalette.blueHour.rawValue; liquidPreset.chaos = 0.8 |
| 244 | liquidPreset.apply(to: state) |
| 245 | var liquidFrames: [[(Double,Double,Double)]] = [] |
| 246 | for detail: Float in [0,1] { |
| 247 | state.liquidDetail = detail |
| 248 | let movie = root.appendingPathComponent("liquid-detail-\(Int(detail)).mp4") |
| 249 | await exporter.export(audioURL: soundtrack, render: state, to: movie) |
| 250 | try require(exporter.exportedURL == movie && state.liquidDetail == detail, "Liquid export must retain the live setting") |
| 251 | liquidFrames.append(try frameColors(movie)) |
| 252 | } |
| 253 | let liquidChange = zip(liquidFrames[0],liquidFrames[1]).reduce(0.0) { $0 + abs($1.0.0-$1.1.0) + abs($1.0.1-$1.1.1) + abs($1.0.2-$1.1.2) } / 48 |
| 254 | try require(liquidChange > 28_800, "Decoded low/high Liquid detail movies must visibly differ") |
| 255 | state.liquidDetail = 0; liquidPreset.liquidDetail = 1 |
| 256 | let liquidStudio = root.appendingPathComponent("liquid-shared-preset.mp4") |
| 257 | await exporter.export(audioURL: soundtrack, render: state, to: liquidStudio, segments: [StudioSegment(start: 0, end: 2, scene: 23)], appearances: [23:liquidPreset]) |
| 258 | try require(exporter.exportedURL == liquidStudio && state.liquidDetail == 0, "Studio must apply its shared liquid preset and retain the live setting") |
| 259 | let sharedLiquid = try frameColors(liquidStudio) |
| 260 | let sharedDifference = zip(sharedLiquid,liquidFrames[1]).reduce(0.0) { $0 + abs($1.0.0-$1.1.0) + abs($1.0.1-$1.1.1) + abs($1.0.2-$1.1.2) } / 48 |
| 261 | try require(sharedDifference < 14_400, "Shared Liquid detail must reproduce the matching single-visualizer export") |
| 262 | print("PASS: decoded Liquid detail exports visibly differ; Studio shared detail matches single-visualizer output and preserves live state") |
| 263 | for zoomScene in [18,22] { |
| 264 | state.scene = zoomScene |
| 265 | var zoomPreset = VisualPreset(); zoomPreset.palette = VisualPalette.blueHour.rawValue |
| 266 | zoomPreset.apply(to: state) |
| 267 | var zoomFrames: [[UInt8]] = [] |
| 268 | for speed: Float in [0,2.5] { |
| 269 | state.zoomSpeed = speed |
| 270 | let movie = root.appendingPathComponent("zoom-\(zoomScene)-\(speed).mp4") |
| 271 | await exporter.export(audioURL: soundtrack, render: state, to: movie) |
| 272 | try require(exporter.exportedURL == movie && state.zoomSpeed == speed, "Zoom export must retain the live setting") |
| 273 | zoomFrames.append(try framePixels(movie)) |
| 274 | } |
| 275 | let change = zip(zoomFrames[0],zoomFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(zoomFrames[0].count) |
| 276 | try require(change > 3, "Decoded flat/forward zoom movies must visibly differ: scene \(zoomScene), mean pixel change \(change)") |
| 277 | state.zoomSpeed = 0; zoomPreset.zoomSpeed = 2.5 |
| 278 | let studioZoom = root.appendingPathComponent("zoom-shared-\(zoomScene).mp4") |
| 279 | await exporter.export(audioURL: soundtrack, render: state, to: studioZoom, segments: [StudioSegment(start: 0, end: 2, scene: zoomScene)], appearances: [zoomScene:zoomPreset]) |
| 280 | try require(exporter.exportedURL == studioZoom && state.zoomSpeed == 0, "Studio zoom must retain the live setting") |
| 281 | let shared = try framePixels(studioZoom) |
| 282 | let mismatch = zip(shared,zoomFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(shared.count) |
| 283 | try require(mismatch < 2, "Shared zoom speed must reproduce direct export") |
| 284 | print("PASS: scene \(zoomScene) decoded zoom mean pixel change \(change), shared preset mismatch \(mismatch)") |
| 285 | } |
| 286 | print("PASS: decoded flat/forward zoom differs for geometry and mesh tunnels; Studio reproduces shared zoom and retains live state") |
| 287 | state.scene = 28 |
| 288 | var haloPreset = VisualPreset(); haloPreset.palette = VisualPalette.blueHour.rawValue |
| 289 | haloPreset.apply(to: state) |
| 290 | var haloFrames: [[UInt8]] = [] |
| 291 | for count in [2,12] { |
| 292 | state.haloCount = count |
| 293 | let movie = root.appendingPathComponent("halo-count-\(count).mp4") |
| 294 | await exporter.export(audioURL: soundtrack, render: state, to: movie) |
| 295 | try require(exporter.exportedURL == movie && state.haloCount == count, "Halo export must retain the live count") |
| 296 | haloFrames.append(try framePixels(movie)) |
| 297 | } |
| 298 | let haloChange = zip(haloFrames[0],haloFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(haloFrames[0].count) |
| 299 | try require(haloChange > 3, "Decoded Halo count movies must visibly differ") |
| 300 | state.haloCount = 2; haloPreset.haloCount = 12 |
| 301 | let haloStudio = root.appendingPathComponent("halo-shared-preset.mp4") |
| 302 | await exporter.export(audioURL: soundtrack, render: state, to: haloStudio, segments: [StudioSegment(start: 0, end: 2, scene: 28)], appearances: [28:haloPreset]) |
| 303 | try require(exporter.exportedURL == haloStudio && state.haloCount == 2, "Studio halo count must retain the live setting") |
| 304 | let sharedHalos = try framePixels(haloStudio) |
| 305 | let haloMismatch = zip(sharedHalos,haloFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(sharedHalos.count) |
| 306 | try require(haloMismatch < 2, "Shared Halo count must reproduce direct export: \(haloMismatch)") |
| 307 | print("PASS: decoded Halo count changes geometry, mean pixel change \(haloChange); shared Studio preset mismatch \(haloMismatch), live count retained") |
| 308 | state.scene = 22 |
| 309 | var blurPreset = VisualPreset(); blurPreset.palette = VisualPalette.blueHour.rawValue |
| 310 | blurPreset.apply(to: state) |
| 311 | var blurFrames: [[UInt8]] = [] |
| 312 | for strength: Float in [0, 0.9] { |
| 313 | state.motionBlur = strength |
| 314 | let movie = root.appendingPathComponent("content-blur-\(strength).mp4") |
| 315 | await exporter.export(audioURL: soundtrack, render: state, to: movie) |
| 316 | try require(exporter.exportedURL == movie && state.motionBlur == strength, "Content blur export must retain live setting") |
| 317 | blurFrames.append(try framePixels(movie)) |
| 318 | } |
| 319 | let blurChange = zip(blurFrames[0],blurFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(blurFrames[0].count) |
| 320 | try require(blurChange > 0.5, "Whole-image softness must survive MP4 encoding") |
| 321 | state.motionBlur = 0; blurPreset.motionBlur = 0.9 |
| 322 | let blurStudio = root.appendingPathComponent("content-blur-shared.mp4") |
| 323 | await exporter.export(audioURL: soundtrack, render: state, to: blurStudio, segments: [StudioSegment(start: 0, end: 2, scene: 22)], appearances: [22:blurPreset]) |
| 324 | try require(exporter.exportedURL == blurStudio && state.motionBlur == 0, "Studio blur must retain live setting") |
| 325 | let sharedBlur = try framePixels(blurStudio) |
| 326 | let blurMismatch = zip(sharedBlur,blurFrames[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(sharedBlur.count) |
| 327 | try require(blurMismatch < 2, "Studio must reproduce shared content blur") |
| 328 | print("PASS: decoded uniform blur visibly softens movie, mean pixel change \(blurChange); shared Studio mismatch \(blurMismatch), live blur retained") |
| 329 | // Zero Chaos must export pure procedural motion, even with a soundtrack |
| 330 | // and a saved Studio preset. Compare decoded output to true silent PCM. |
| 331 | let silentPCM = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 88_200)! |
| 332 | silentPCM.frameLength = silentPCM.frameCapacity |
| 333 | for channel in 0..<Int(format.channelCount) { |
| 334 | silentPCM.floatChannelData![channel].initialize(repeating: 0, count: Int(silentPCM.frameLength)) |
| 335 | } |
| 336 | let silentTrack = root.appendingPathComponent("zero-chaos-silent.wav") |
| 337 | do { let writer = try AVAudioFile(forWriting: silentTrack, settings: settings); try writer.write(from: silentPCM) } |
| 338 | for scene in [18,22,25,29] { |
| 339 | var calmPreset = VisualPreset(); calmPreset.chaos = 0; calmPreset.zoomSpeed = 1.5 |
| 340 | calmPreset.strobeEnabled = true |
| 341 | calmPreset.apply(to: state); state.scene = scene |
| 342 | var movies: [[UInt8]] = [] |
| 343 | for (label, track) in [("audio",soundtrack),("silent",silentTrack)] { |
| 344 | let movie = root.appendingPathComponent("zero-chaos-\(scene)-\(label).mp4") |
| 345 | await exporter.export(audioURL: track, render: state, to: movie) |
| 346 | try require(exporter.exportedURL == movie && state.chaos == 0, "Zero-Chaos export must retain live settings") |
| 347 | movies.append(try framePixels(movie)) |
| 348 | } |
| 349 | let mismatch = zip(movies[0],movies[1]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(movies[0].count) |
| 350 | try require(mismatch < 0.2, "Zero-Chaos movie must ignore music: scene \(scene), decoded mismatch \(mismatch)") |
| 351 | state.chaos = 1 |
| 352 | let sharedMovie = root.appendingPathComponent("zero-chaos-\(scene)-studio.mp4") |
| 353 | await exporter.export(audioURL: soundtrack, render: state, to: sharedMovie, |
| 354 | segments: [StudioSegment(start: 0, end: 2, scene: scene)], appearances: [scene:calmPreset]) |
| 355 | try require(exporter.exportedURL == sharedMovie && state.chaos == 1, "Studio zero Chaos must preserve the live setting") |
| 356 | let shared = try framePixels(sharedMovie) |
| 357 | let sharedMismatch = zip(shared,movies[0]).reduce(0.0) { $0 + Double(abs(Int($1.0)-Int($1.1))) } / Double(shared.count) |
| 358 | try require(sharedMismatch < 0.2, "Studio must honor zero Chaos: scene \(scene), decoded mismatch \(sharedMismatch)") |
| 359 | print("PASS: \(RenderState.sceneNames[scene]) zero-Chaos music/silence decoded mismatch \(mismatch), Studio mismatch \(sharedMismatch), live setting retained") |
| 360 | } |
| 361 | print("PASS: all offline social export checks") |
| 362 | } |
| 363 | |
| 364 | static func pixelSequence(_ url: URL) throws -> [[UInt8]] { |
| 365 | let asset = AVURLAsset(url: url) |
| 366 | let reader = try AVAssetReader(asset: asset) |
| 367 | let output = AVAssetReaderTrackOutput(track: asset.tracks(withMediaType: .video)[0], outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 368 | reader.add(output); try require(reader.startReading(), "Cannot decode shape pulse movie") |
| 369 | var frames: [[UInt8]] = [] |
| 370 | while let sample = output.copyNextSampleBuffer(), let image = CMSampleBufferGetImageBuffer(sample) { |
| 371 | CVPixelBufferLockBaseAddress(image, .readOnly) |
| 372 | let bytes = CVPixelBufferGetBaseAddress(image)!.assumingMemoryBound(to: UInt8.self) |
| 373 | let width = CVPixelBufferGetWidth(image), height = CVPixelBufferGetHeight(image), row = CVPixelBufferGetBytesPerRow(image) |
| 374 | var pixels: [UInt8] = [] |
| 375 | for y in stride(from: 0, to: height, by: 8) { for x in stride(from: 0, to: width, by: 8) { |
| 376 | let i=y*row+x*4; pixels.append(contentsOf: [bytes[i],bytes[i+1],bytes[i+2]]) |
| 377 | } } |
| 378 | CVPixelBufferUnlockBaseAddress(image, .readOnly); frames.append(pixels) |
| 379 | } |
| 380 | try require(reader.status == .completed && frames.count == 66, "Pulse movie must decode every frame") |
| 381 | return frames |
| 382 | } |
| 383 | |
| 384 | static func framePixels(_ url: URL) throws -> [UInt8] { |
| 385 | let asset = AVURLAsset(url: url) |
| 386 | let reader = try AVAssetReader(asset: asset) |
| 387 | let output = AVAssetReaderTrackOutput(track: asset.tracks(withMediaType: .video)[0], outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 388 | reader.add(output); try require(reader.startReading(), "Cannot decode zoom movie") |
| 389 | var pixels: [UInt8] = [], frames = 0 |
| 390 | while let sample = output.copyNextSampleBuffer(), let image = CMSampleBufferGetImageBuffer(sample) { |
| 391 | CVPixelBufferLockBaseAddress(image, .readOnly) |
| 392 | let bytes = CVPixelBufferGetBaseAddress(image)!.assumingMemoryBound(to: UInt8.self) |
| 393 | for y in stride(from: 0, to: CVPixelBufferGetHeight(image), by: 8) { |
| 394 | for x in stride(from: 0, to: CVPixelBufferGetWidth(image), by: 8) { |
| 395 | let index = y * CVPixelBufferGetBytesPerRow(image) + x * 4 |
| 396 | pixels.append(contentsOf: [bytes[index],bytes[index+1],bytes[index+2]]) |
| 397 | } |
| 398 | } |
| 399 | CVPixelBufferUnlockBaseAddress(image, .readOnly); frames += 1 |
| 400 | } |
| 401 | try require(reader.status == .completed && frames == 48, "Zoom movie must decode every frame") |
| 402 | return pixels |
| 403 | } |
| 404 | |
| 405 | static func frameColors(_ url: URL) throws -> [(Double, Double, Double)] { |
| 406 | let asset = AVURLAsset(url: url) |
| 407 | let reader = try AVAssetReader(asset: asset) |
| 408 | let output = AVAssetReaderTrackOutput(track: asset.tracks(withMediaType: .video)[0], outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 409 | reader.add(output); try require(reader.startReading(), "Cannot decode Studio movie") |
| 410 | var colors: [(Double, Double, Double)] = [] |
| 411 | while let sample = output.copyNextSampleBuffer(), let image = CMSampleBufferGetImageBuffer(sample) { |
| 412 | CVPixelBufferLockBaseAddress(image, .readOnly) |
| 413 | let bytes = CVPixelBufferGetBaseAddress(image)!.assumingMemoryBound(to: UInt8.self) |
| 414 | var r = 0.0, g = 0.0, b = 0.0 |
| 415 | for y in stride(from: 0, to: CVPixelBufferGetHeight(image), by: 8) { |
| 416 | for x in stride(from: 0, to: CVPixelBufferGetWidth(image), by: 8) { |
| 417 | let i = y * CVPixelBufferGetBytesPerRow(image) + x * 4 |
| 418 | r += Double(bytes[i+2]); g += Double(bytes[i+1]); b += Double(bytes[i]) |
| 419 | } |
| 420 | } |
| 421 | CVPixelBufferUnlockBaseAddress(image, .readOnly); colors.append((r,g,b)) |
| 422 | } |
| 423 | try require(reader.status == .completed && colors.count == 48, "Studio must decode every frame") |
| 424 | return colors |
| 425 | } |
| 426 | |
| 427 | static func frameBrightness(_ url: URL) throws -> [Double] { |
| 428 | let asset = AVURLAsset(url: url) |
| 429 | let reader = try AVAssetReader(asset: asset) |
| 430 | let output = AVAssetReaderTrackOutput(track: asset.tracks(withMediaType: .video)[0], outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 431 | reader.add(output) |
| 432 | try require(reader.startReading(), "Cannot decode beat pulse movie") |
| 433 | var levels: [Double] = [] |
| 434 | while let sample = output.copyNextSampleBuffer() { |
| 435 | guard let image = CMSampleBufferGetImageBuffer(sample) else { continue } |
| 436 | CVPixelBufferLockBaseAddress(image, .readOnly) |
| 437 | let bytes = CVPixelBufferGetBaseAddress(image)!.assumingMemoryBound(to: UInt8.self) |
| 438 | let width = CVPixelBufferGetWidth(image), height = CVPixelBufferGetHeight(image), row = CVPixelBufferGetBytesPerRow(image) |
| 439 | var total = 0.0, count = 0 |
| 440 | for y in stride(from: 0, to: height, by: 8) { |
| 441 | for x in stride(from: 0, to: width, by: 8) { |
| 442 | let index = y * row + x * 4 |
| 443 | total += Double(bytes[index]) + Double(bytes[index+1]) + Double(bytes[index+2]); count += 1 |
| 444 | } |
| 445 | } |
| 446 | CVPixelBufferUnlockBaseAddress(image, .readOnly) |
| 447 | levels.append(total / Double(max(1, count))) |
| 448 | } |
| 449 | try require(reader.status == .completed && levels.count == 66, "Beat clip must decode every frame") |
| 450 | return levels |
| 451 | } |
| 452 | |
| 453 | static func whiteFrames(_ url: URL) throws -> (white: Int, total: Int) { |
| 454 | let asset = AVURLAsset(url: url) |
| 455 | let reader = try AVAssetReader(asset: asset) |
| 456 | let output = AVAssetReaderTrackOutput(track: asset.tracks(withMediaType: .video)[0], outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 457 | reader.add(output) |
| 458 | try require(reader.startReading(), "Cannot decode strobe movie") |
| 459 | var white = 0, total = 0 |
| 460 | while let sample = output.copyNextSampleBuffer() { |
| 461 | guard let image = CMSampleBufferGetImageBuffer(sample) else { continue } |
| 462 | CVPixelBufferLockBaseAddress(image, .readOnly) |
| 463 | let bytes = CVPixelBufferGetBaseAddress(image)!.assumingMemoryBound(to: UInt8.self) |
| 464 | let width = CVPixelBufferGetWidth(image), height = CVPixelBufferGetHeight(image), row = CVPixelBufferGetBytesPerRow(image) |
| 465 | var bright = 0 |
| 466 | for y in 0..<5 { for x in 0..<5 { |
| 467 | let index = ((height * (y * 2 + 1)) / 10) * row + ((width * (x * 2 + 1)) / 10) * 4 |
| 468 | if min(bytes[index], bytes[index + 1], bytes[index + 2]) > 240 { bright += 1 } |
| 469 | } } |
| 470 | CVPixelBufferUnlockBaseAddress(image, .readOnly) |
| 471 | if bright >= 24 { white += 1 } |
| 472 | total += 1 |
| 473 | } |
| 474 | return (white, total) |
| 475 | } |
| 476 | |
| 477 | static func verify(_ url: URL, width: Int, height: Int, fps: Int, duration: Double, hasAudio: Bool) async throws { |
| 478 | let asset = AVURLAsset(url: url) |
| 479 | let actualDuration = try await asset.load(.duration).seconds |
| 480 | try require(abs(actualDuration - duration) < 0.002, "Wrong movie duration \(actualDuration), expected \(duration)") |
| 481 | let videos = try await asset.loadTracks(withMediaType: .video) |
| 482 | let audios = try await asset.loadTracks(withMediaType: .audio) |
| 483 | try require(videos.count == 1 && audios.count == (hasAudio ? 1 : 0), "Wrong video/audio track count") |
| 484 | let video = videos[0] |
| 485 | let size = try await video.load(.naturalSize) |
| 486 | try require(Int(size.width) == width && Int(size.height) == height, "Wrong video dimensions \(size)") |
| 487 | let descriptions = try await video.load(.formatDescriptions) |
| 488 | try require(descriptions.first.map { CMFormatDescriptionGetMediaSubType($0) } == kCMVideoCodecType_H264, "Video must be H.264") |
| 489 | let reader = try AVAssetReader(asset: asset) |
| 490 | let output = AVAssetReaderTrackOutput(track: video, outputSettings: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA]) |
| 491 | reader.add(output) |
| 492 | try require(reader.startReading(), "Cannot read exported video") |
| 493 | var times: [Double] = [] |
| 494 | while let sample = output.copyNextSampleBuffer() { |
| 495 | if CMSampleBufferGetNumSamples(sample) > 0 { times.append(CMSampleBufferGetPresentationTimeStamp(sample).seconds) } |
| 496 | } |
| 497 | try require(reader.status == .completed, "Exported video reader failed") |
| 498 | times.sort() |
| 499 | let frameCount = Int(ceil(duration * Double(fps) - 0.00000001)) |
| 500 | try require(times.count == frameCount, "Dropped or duplicated frame: found \(times.count), expected \(frameCount)") |
| 501 | for (index, time) in times.enumerated() { |
| 502 | try require(abs(time - Double(index) / Double(fps)) < 0.0001, "Wrong frame timestamp \(time) at \(index)") |
| 503 | } |
| 504 | if hasAudio { |
| 505 | let audio = audios[0] |
| 506 | let descriptions = try await audio.load(.formatDescriptions) |
| 507 | try require(descriptions.first.map { CMFormatDescriptionGetMediaSubType($0) } == kAudioFormatMPEG4AAC, "Soundtrack must be AAC") |
| 508 | let range = try await audio.load(.timeRange) |
| 509 | try require(abs(range.start.seconds) < 0.002 && abs(range.duration.seconds - duration) < 0.003, "Soundtrack trim or start time differs from video") |
| 510 | let audioReader = try AVAssetReader(asset: asset) |
| 511 | let pcm = AVAssetReaderTrackOutput(track: audio, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM, AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false]) |
| 512 | audioReader.add(pcm) |
| 513 | try require(audioReader.startReading(), "Cannot decode exported soundtrack") |
| 514 | var energy: Double = 0 |
| 515 | var count = 0 |
| 516 | while let sample = pcm.copyNextSampleBuffer() { |
| 517 | guard let description = CMSampleBufferGetFormatDescription(sample), |
| 518 | let format = CMAudioFormatDescriptionGetStreamBasicDescription(description), |
| 519 | let block = CMSampleBufferGetDataBuffer(sample) else { throw ExportError("Missing decoded audio buffer") } |
| 520 | try require(format.pointee.mChannelsPerFrame == 2, "Stereo soundtrack channels were lost") |
| 521 | var length = 0 |
| 522 | var pointer: UnsafeMutablePointer<Int8>? |
| 523 | try require(CMBlockBufferGetDataPointer(block, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: &length, dataPointerOut: &pointer) == noErr, "Cannot read soundtrack PCM") |
| 524 | pointer!.withMemoryRebound(to: Float.self, capacity: length / 4) { |
| 525 | for index in 0..<length / 4 { energy += Double($0[index] * $0[index]); count += 1 } |
| 526 | } |
| 527 | } |
| 528 | try require(count > 0 && sqrt(energy / Double(count)) > 0.1, "Trimmed export contains silence instead of selected tone") |
| 529 | } |
| 530 | } |
| 531 | } |