Branchwell

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

Raw 7.4 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1import AVFoundation
2import Foundation
3@main struct RhythmSmoke {
4 static func require(_ condition: Bool, _ message: String) throws { if !condition { throw AudioAnalysisError(message) } }
5 static func fixture(_ url: URL, duration: Double, sample: (Double) -> Float) throws {
6 let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 2)!
7 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(duration * 44_100))!
8 buffer.frameLength = buffer.frameCapacity
9 for i in 0..<Int(buffer.frameLength) {
10 let value = sample(Double(i) / 44_100)
11 buffer.floatChannelData![0][i] = value; buffer.floatChannelData![1][i] = -value
12 }
13 var settings = format.settings; settings[AVLinearPCMIsNonInterleaved] = false
14 try AVAudioFile(forWriting: url, settings: settings).write(from: buffer)
15 }
16 static func main() throws {
17 let root = URL(fileURLWithPath: ".build/rhythm-validation")
18 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
19 let url = root.appendingPathComponent("drum-density.wav")
20 let sparse = [3.05, 3.55, 4.05], dense = (0..<8).map { 5.05 + Double($0) * 0.25 }
21 try fixture(url, duration: 9) { time in
22 let swell = min(1, max(0, (time - 0.3) / 0.7))
23 var sample = swell * (0.035 * sin(time * 2 * .pi * 55) + 0.025 * sin(time * 2 * .pi * 440))
24 for attack in sparse + dense {
25 let age = time - attack
26 if age >= 0 && age < 0.13 { sample += 0.65 * exp(-age * 30) * sin(age * 2 * .pi * 65) }
27 }
28 return Float(sample)
29 }
30 let reader = try SoundtrackAnalyzer(url: url)
31 let calm = try (120..<270).map { try reader.frame(at: Double($0)/100, clipStart: 0, clipEnd: 9) }
32 try require(calm.map(\.pulse).max()! < 0.12, "Melody without drums must not invent beats")
33 let sparseDrive = try (330..<445).map { try reader.frame(at: Double($0)/100, clipStart: 0, clipEnd: 9).momentum }.reduce(0,+) / 115
34 let denseDrive = try (570..<690).map { try reader.frame(at: Double($0)/100, clipStart: 0, clipEnd: 9).momentum }.reduce(0,+) / 120
35 let released = try reader.frame(at: 8.5, clipStart: 0, clipEnd: 9)
36 try require(denseDrive > sparseDrive * 1.5 && released.momentum < denseDrive * 0.2, "Drum density must build momentum, then release")
37 for attack in sparse + dense {
38 let peaks = try (0...7).map { try reader.frame(at: attack + Double($0)/100, clipStart: 0, clipEnd: 9).pulse }
39 try require(peaks.max()! > 0.5, "Every kick must trigger close to its source attack")
40 }
41 print("PASS: no fabricated rhythm over sustained melody; sparse drive \(sparseDrive), dense drive \(denseDrive), quiet release \(released.momentum); every kick within 70 ms")
42 let hats = (0..<7).map { 0.113 + Double($0) * 0.07 }
43 let hatURL = root.appendingPathComponent("off-grid-hats.wav")
44 try fixture(hatURL, duration: 0.8) { time in
45 var sample = 0.0
46 for attack in hats {
47 let age = time - attack
48 if age >= 0 && age < 0.02 { sample += 0.7 * exp(-age * 180) * sin(age * 2 * .pi * 8000) }
49 }
50 return Float(sample)
51 }
52 let hatReader = try SoundtrackAnalyzer(url: hatURL)
53 for fps in [24,30,60] {
54 var detector = StrobeDetector(), emitted = Set<Double>()
55 for index in 0..<Int(0.8 * Double(fps)) {
56 let time = Double(index)/Double(fps), feature = try hatReader.frame(at: time, clipStart: 0, clipEnd: 0.8)
57 let flash = detector.nextSourceFrame(time: time, attackTime: feature.trebleAttackTime, strength: feature.treblePulse)
58 if flash > 0, let attack = feature.trebleAttackTime { emitted.insert(attack) }
59 }
60 try require(emitted.count == hats.count, "All seven off-grid hats must flash at \(fps)fps; found \(emitted.count)")
61 print("PASS: all seven off-grid treble attacks flash at \(fps) fps")
62 }
63 var bassDetector = StrobeDetector(), bassFlashes = 0
64 for index in 200..<450 {
65 let t = Double(index)/60, feature = try reader.frame(at: t, clipStart: 0, clipEnd: 9)
66 if bassDetector.nextSourceFrame(time: t, attackTime: feature.trebleAttackTime, strength: feature.treblePulse) > 0 { bassFlashes += 1 }
67 }
68 try require(bassFlashes == 0, "Bass-only kicks must not trigger hi-hat strobe")
69 print("PASS: bass-only PCM triggers no white flashes")
70 let beatURL = root.appendingPathComponent("120bpm.wav")
71 try fixture(beatURL, duration: 25) { time in
72 let age = (time - 0.1).truncatingRemainder(dividingBy: 0.5)
73 return age >= 0 && age < 0.13 ? Float(0.65 * exp(-age * 30) * sin(age * 2 * .pi * 65)) : 0
74 }
75 let beatReader = try SoundtrackAnalyzer(url: beatURL), plan = beatReader.segmentPlan()
76 try require(abs((plan.bpm ?? 0) - 120) < 3, "Detect a real 120 BPM fixture: \(plan.bpm ?? 0)")
77 try require(plan.boundaries.first == 0 && plan.boundaries.last == 25 && plan.boundaries.count == 5, "Four-bar sections must span source duration: \(plan.boundaries)")
78 for cue in plan.boundaries.dropFirst().dropLast() {
79 let nearest = 0.1 + ((cue - 0.1) / 0.5).rounded() * 0.5
80 try require(abs(cue - nearest) < 0.04, "Section must align to a detected source beat")
81 }
82 try require(plan.boundaries == beatReader.segmentPlan().boundaries, "Segment detection must be deterministic")
83 print("PASS: 120 BPM detected, four-bar sections aligned to source beats, deterministic boundaries \(plan.boundaries)")
84 for bars in [1, 2, 3, 4, 5, 6, 7, 8, 12] {
85 let cadence = beatReader.segmentPlan(beatsPerSection: bars * 4)
86 try require(cadence.boundaries.first == 0 && cadence.boundaries.last == 25, "Cadence must cover the full song")
87 if cadence.boundaries.count > 3 {
88 try require(abs(cadence.boundaries[2] - cadence.boundaries[1] - Double(bars) * 2) < 0.05, "Cadence must use requested bars")
89 }
90 }
91 let sustained = root.appendingPathComponent("sustained.wav")
92 try fixture(sustained, duration: 20) { time in Float(0.1 * sin(time * 2 * .pi * 440)) }
93 let fallback = try SoundtrackAnalyzer(url: sustained).segmentPlan(beatsPerSection: 12)
94 try require(fallback.bpm == nil && fallback.boundaries == [0, 6, 12, 18, 20], "No-grid audio uses requested bars at a 120 BPM fallback")
95 print("PASS: 1–8 and 12 bar cadence preserves full-song coverage and requested beat-aligned spacing")
96
97 if CommandLine.arguments.count > 1 {
98 let started = Date(), music = try SoundtrackAnalyzer(url: URL(fileURLWithPath: CommandLine.arguments[1]))
99 var csv = "seconds,pulse,momentum,treble\n"
100 for index in 0..<3600 {
101 let t = Double(index)/30, f = try music.frame(at: t, clipStart: 0, clipEnd: 120)
102 csv += "\(t),\(f.pulse),\(f.momentum),\(f.treblePulse)\n"
103 }
104 try csv.write(to: root.appendingPathComponent("soundtrack-reaction.csv"), atomically: true, encoding: .utf8)
105 print("Soundtrack Studio plan: \(music.segmentPlan().boundaries), BPM \(music.segmentPlan().bpm ?? 0)")
106 print("Soundtrack 120s timeline and 3600 feature lookups: \(Date().timeIntervalSince(started))s")
107 }
108 }
109}