PulseCanvas / app · pulsecanvas.ai / scripts / AudioSyncSmoke.swift
| 1 | import AppKit |
| 2 | import AVFoundation |
| 3 | import Foundation |
| 4 | import MetalKit |
| 5 | |
| 6 | @main struct AudioSyncSmoke { |
| 7 | static func require(_ condition: Bool, _ message: String) throws { |
| 8 | if !condition { throw AudioAnalysisError(message) } |
| 9 | } |
| 10 | @MainActor static func main() async throws { |
| 11 | _ = NSApplication.shared |
| 12 | let root = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(".build/audio-sync-validation") |
| 13 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 14 | let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)! |
| 15 | let attacks = [0.3, 0.8, 1.3, 1.8] |
| 16 | func fixture(_ name: String, beats: Bool, gain: Float = 1, rightOnly: Bool = false) throws -> URL { |
| 17 | let url = root.appendingPathComponent(name + ".wav") |
| 18 | let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 110_250)! |
| 19 | buffer.frameLength = buffer.frameCapacity |
| 20 | for i in 0..<Int(buffer.frameLength) { |
| 21 | let t = Double(i) / 44_100 |
| 22 | var sample = 0.035 * sin(2 * Double.pi * 55 * t) + 0.025 * sin(2 * Double.pi * 440 * t) |
| 23 | if beats { |
| 24 | for attack in attacks { |
| 25 | let age = t - attack |
| 26 | if age >= 0 && age < 0.12 { sample += 0.65 * exp(-age * 30) * sin(2 * Double.pi * 65 * age) } |
| 27 | } |
| 28 | } |
| 29 | buffer.floatChannelData![0][i] = rightOnly ? 0 : Float(sample) * gain |
| 30 | buffer.floatChannelData![1][i] = -Float(sample) * gain |
| 31 | } |
| 32 | var settings = format.settings; settings[AVLinearPCMIsNonInterleaved] = false |
| 33 | let file = try AVAudioFile(forWriting: url, settings: settings) |
| 34 | try file.write(from: buffer) |
| 35 | return url |
| 36 | } |
| 37 | let track = try fixture("beat-fixture", beats: true) |
| 38 | let reader = try SoundtrackAnalyzer(url: track) |
| 39 | for gain in [Float(1), 0.2] { |
| 40 | let url = try fixture("right-only-\(gain)", beats: true, gain: gain, rightOnly: true) |
| 41 | let analysis = try SoundtrackAnalyzer(url: url) |
| 42 | for attack in attacks { |
| 43 | let frames = try (0...6).map { try analysis.frame(at: attack + Double($0) / 100, clipStart: 0, clipEnd: 2.5) } |
| 44 | let peak = frames.map(\.pulse).max() ?? 0 |
| 45 | let released = try analysis.frame(at: attack + 0.25, clipStart: 0, clipEnd: 2.5).pulse |
| 46 | print("beat \(attack), gain \(gain): peak \(peak), released \(released)") |
| 47 | try require(peak > 0.4 && released < peak * 0.2, "Beat must give a sharp pulse followed by release, including right-only and quiet audio") |
| 48 | } |
| 49 | } |
| 50 | let sustained = try SoundtrackAnalyzer(url: fixture("sustained", beats: false)) |
| 51 | let steadyPulses = try (30..<140).map { try sustained.frame(at: Double($0) / 60, clipStart: 0, clipEnd: 2.5).pulse } |
| 52 | print("sustained max \(steadyPulses.max() ?? 0)") |
| 53 | try require((steadyPulses.max() ?? 1) < 0.12, "Sustained bass must not fabricate rhythmic attacks") |
| 54 | let frame = try reader.frame(at: 1.33, clipStart: 0, clipEnd: 2.5) |
| 55 | _ = try reader.frame(at: 2.2, clipStart: 0, clipEnd: 2.5) |
| 56 | let seek = try reader.frame(at: 1.33, clipStart: 1.2, clipEnd: 2) |
| 57 | try require(frame.pulse == seek.pulse && frame.bands == seek.bands, "Seeking and clip trims must retain exact PCM response") |
| 58 | print("PASS: real PCM attacks, quiet/right-only stereo, sustained-bass rejection, deterministic seeking and clip boundaries") |
| 59 | |
| 60 | let audio = AudioController() |
| 61 | audio.volume = 0 |
| 62 | try require(audio.load(url: track), "Preview soundtrack must load") |
| 63 | audio.seek(fraction: 1.33 / 2.5) |
| 64 | try require(abs(audio.beatPulse - frame.pulse) < 0.01, "Muted preview must match export analysis at the same playhead") |
| 65 | audio.playPause() |
| 66 | var livePeak: Float = 0 |
| 67 | for _ in 0..<45 { |
| 68 | try await Task.sleep(for: .milliseconds(15)) |
| 69 | livePeak = max(livePeak, audio.beatPulse) |
| 70 | } |
| 71 | audio.pause() |
| 72 | try require(livePeak > 0.4 && audio.playbackSeconds > 1.8, "Live playback must publish actual beat pulses while muted") |
| 73 | audio.clear() |
| 74 | print("PASS: live preview publishes PCM pulse and matches export independently of monitor volume") |
| 75 | |
| 76 | if CommandLine.arguments.count > 1 { |
| 77 | let url = URL(fileURLWithPath: CommandLine.arguments[1]) |
| 78 | let realTrack = try SoundtrackAnalyzer(url: url) |
| 79 | let source = try AVAudioFile(forReading: url) |
| 80 | let duration = Double(source.length) / source.processingFormat.sampleRate |
| 81 | let started = Date() |
| 82 | var peaks = 0, previous: Float = 0, maximum: Float = 0 |
| 83 | var csv = "seconds,pulse\n" |
| 84 | for index in 0..<Int(min(120, duration) * 30) { |
| 85 | let time = Double(index) / 30 |
| 86 | let features = try realTrack.frame(at: time, clipStart: 0, clipEnd: duration) |
| 87 | if features.pulse > 0.45 && features.pulse > previous + 0.15 { peaks += 1 } |
| 88 | maximum = max(maximum, features.pulse); previous = features.pulse |
| 89 | csv += "\(time),\(features.pulse)\n" |
| 90 | } |
| 91 | try csv.write(to: root.appendingPathComponent("soundtrack-pulses.csv"), atomically: true, encoding: .utf8) |
| 92 | print("Soundtrack check: \(peaks) strong attacks, max pulse \(maximum), \(Date().timeIntervalSince(started)) seconds to analyze \(min(120, duration)) seconds") |
| 93 | } |
| 94 | |
| 95 | func pixels(_ texture: MTLTexture) -> [UInt8] { |
| 96 | var bytes = [UInt8](repeating: 0, count: texture.width * texture.height * 4) |
| 97 | bytes.withUnsafeMutableBytes { texture.getBytes($0.baseAddress!, bytesPerRow: texture.width * 4, |
| 98 | from: MTLRegionMake2D(0, 0, texture.width, texture.height), mipmapLevel: 0) } |
| 99 | return bytes |
| 100 | } |
| 101 | let state = RenderState(), renderer = VisualizerRenderer(state: state) |
| 102 | try renderer.prepareOffscreen(width: 180, height: 320) |
| 103 | var paletteChecks = 0 |
| 104 | for scene in NativeEffects.activeIDs { |
| 105 | state.scene = scene; state.zoom = 1; state.brightness = 1; state.strobeEnabled = false |
| 106 | let idle = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frame.bands, audioPulse: 0)) |
| 107 | // Real analysis always pairs an attack with its smoothed swell. |
| 108 | let beat = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frame.bands, audioPulse: 1, audioSwell: 1)) |
| 109 | let changed = zip(idle, beat).filter { abs(Int($0) - Int($1)) > 8 }.count |
| 110 | try require(changed > 100, "Beat pulse must visibly change scene \(scene), with white strobe off") |
| 111 | var results = Set<Data>() |
| 112 | for palette in VisualPalette.allCases { |
| 113 | state.palette = palette.rawValue |
| 114 | let image = pixels(try renderer.renderOffscreen(time: 1.33, audioBands: frame.bands)) |
| 115 | results.insert(Data(image)) |
| 116 | // Palettes now include contrasting accents. A frame can emphasize an |
| 117 | // accent, so whole-frame channel ratios no longer define correctness. |
| 118 | paletteChecks += 1 |
| 119 | if scene == 19 { |
| 120 | let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 180, pixelsHigh: 320, |
| 121 | bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, |
| 122 | colorSpaceName: .deviceRGB, bytesPerRow: 180 * 4, bitsPerPixel: 32)! |
| 123 | for i in stride(from: 0, to: image.count, by: 4) { |
| 124 | bitmap.bitmapData![i] = image[i+2]; bitmap.bitmapData![i+1] = image[i+1] |
| 125 | bitmap.bitmapData![i+2] = image[i]; bitmap.bitmapData![i+3] = 255 |
| 126 | } |
| 127 | try bitmap.representation(using: .png, properties: [:])!.write(to: root.appendingPathComponent("palette-\(palette.rawValue).png")) |
| 128 | } |
| 129 | } |
| 130 | try require(results.count == VisualPalette.allCases.count, "Every palette must differ in scene \(scene)") |
| 131 | } |
| 132 | print("PASS: \(NativeEffects.activeIDs.count) scenes visibly pulse without strobe; \(paletteChecks) distinct GPU palette outputs") |
| 133 | } |
| 134 | } |