Branchwell

PulseCanvas / app / Sources / PulseCanvas / AudioAnalysis.swift

1import Accelerate
2import AVFoundation
3import Foundation
4import simd
5
6struct SongSegmentation {
7 let boundaries: [Double]
8 let bpm: Double?
9}
10
11struct AudioFeatures {
12 var bands: [Float]
13 var pulse: Float
14 var momentum: Float = 0
15 var beatMotionTime: Double = 0
16 var treblePulse: Float = 0
17 var trebleAttackTime: Double? = nil
18 /// Smoothed low, low-mid, high-mid and high levels, normalized per song (0...1).
19 var envelopes = SIMD4<Float>(repeating: 0)
20 /// Attack envelope with a short rise and ~0.25 s fall, for fluid element motion.
21 var swell: Float = 0
22 static let silence = AudioFeatures(bands: [Float](repeating: 0, count: 32), pulse: 0)
23}
24
25/// Source PCM is sampled at the playhead, before preview volume. Both preview
26/// and export use this bounded, stateless window, including on backwards seeks.
27final class SoundtrackAnalyzer {
28 private let file: AVAudioFile
29 private let length = 2048
30 private let setup: FFTSetup
31 private let window: [Float]
32 private let rhythm: RhythmTimeline
33 private var segmentationPlans: [Int: SongSegmentation] = [:]
34 var sampleRate: Double { file.processingFormat.sampleRate }
35 var duration: Double { Double(file.length) / sampleRate }
36
37 init(url: URL) throws {
38 file = try AVAudioFile(forReading: url, commonFormat: .pcmFormatFloat32, interleaved: false)
39 guard file.length > 0, file.processingFormat.sampleRate > 80,
40 let setup = vDSP_create_fftsetup(11, FFTRadix(kFFTRadix2)) else {
41 throw AudioAnalysisError(String(localized: "Soundtrack contains no readable PCM samples"))
42 }
43 self.setup = setup
44 var values = [Float](repeating: 0, count: length)
45 vDSP_hann_window(&values, vDSP_Length(length), Int32(vDSP_HANN_NORM))
46 window = values
47 rhythm = try RhythmTimeline(file: file)
48 }
49 deinit { vDSP_destroy_fftsetup(setup) }
50
51 /// Stereo PCM at 44.1 kHz, the sample rate expected by Milkdrop presets.
52 /// It is read before preview volume and used by preview and offline export.
53 func pcm(at time: Double, count: Int = 1024) throws -> [Float] {
54 guard time.isFinite, time >= 0 else { return [] }
55 let windowStart = (time - Double(count) / 44100) * sampleRate
56 let first = max(0, Int(floor(windowStart)))
57 let required = Int(ceil(Double(count) * sampleRate / 44100)) + 2
58 let available = min(required, Int(file.length) - first)
59 guard available > 0, let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(available)) else { return [] }
60 file.framePosition = AVAudioFramePosition(first); try file.read(into: buffer)
61 guard let channels = buffer.floatChannelData else { return [] }
62 var result = [Float](repeating: 0, count: count * 2)
63 for index in 0..<count {
64 let position = windowStart + Double(index) * sampleRate / 44100 - Double(first)
65 guard position >= 0 else {continue}
66 let lower = Int(position), upper = lower + 1, fraction = Float(position - Double(lower))
67 guard lower >= 0, upper < Int(buffer.frameLength) else {continue}
68 for channel in 0..<2 {
69 let samples = channels[min(channel, Int(buffer.format.channelCount) - 1)]
70 result[index * 2 + channel] = samples[lower] * (1 - fraction) + samples[upper] * fraction
71 }
72 }
73 return result
74 }
75
76 func segmentPlan(beatsPerSection: Int = 16) -> SongSegmentation {
77 let beats = max(1, beatsPerSection)
78 if let cached = segmentationPlans[beats] { return cached }
79 let plan = rhythm.segmentPlan(duration: Double(file.length) / sampleRate, beatsPerSection: beats)
80 segmentationPlans[beats] = plan
81 return plan
82 }
83
84 func frame(at time: Double, clipStart: Double, clipEnd: Double, frameInterval: Double = 1.0 / 60) throws -> AudioFeatures {
85 guard time.isFinite, clipStart.isFinite, clipEnd.isFinite, time >= 0 else { return .silence }
86 let center = Int((time * sampleRate).rounded())
87 let fftStart = center - length / 2
88 let first = max(0, fftStart)
89 let last = min(Int(file.length), center + length / 2)
90 guard last > first,
91 let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(last - first)) else { return .silence }
92 file.framePosition = AVAudioFramePosition(first)
93 try file.read(into: buffer)
94 guard let channels = buffer.floatChannelData else { throw AudioAnalysisError(String(localized: "Cannot read soundtrack PCM")) }
95 let channelCount = Int(buffer.format.channelCount)
96 let frameCount = Int(buffer.frameLength)
97 var power = [Float](repeating: 0, count: length / 2)
98 for channel in 0..<channelCount {
99 var samples = [Float](repeating: 0, count: length)
100 for i in 0..<length {
101 let source = fftStart + i, offset = source - first
102 if offset >= 0 && offset < frameCount && source >= Int(clipStart * sampleRate) && source < Int(clipEnd * sampleRate) {
103 samples[i] = channels[channel][offset] * window[i]
104 }
105 }
106 var real = [Float](repeating: 0, count: length / 2)
107 var imaginary = real, channelPower = real
108 real.withUnsafeMutableBufferPointer { re in
109 imaginary.withUnsafeMutableBufferPointer { im in
110 var split = DSPSplitComplex(realp: re.baseAddress!, imagp: im.baseAddress!)
111 samples.withUnsafeBufferPointer { input in
112 input.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: length / 2) {
113 vDSP_ctoz($0, 2, &split, 1, vDSP_Length(length / 2))
114 }
115 }
116 vDSP_fft_zrip(setup, &split, 1, 11, FFTDirection(FFT_FORWARD))
117 split.imagp[0] = 0
118 vDSP_zvmags(&split, 1, &channelPower, 1, vDSP_Length(length / 2))
119 }
120 }
121 for bin in power.indices { power[bin] += channelPower[bin] / Float(channelCount) }
122 }
123 let maximum = min(16_000, sampleRate / 2)
124 var bands = [Float](repeating: 0, count: 32)
125 for band in bands.indices {
126 let lower = 40 * pow(maximum / 40, Double(band) / 32)
127 let upper = 40 * pow(maximum / 40, Double(band + 1) / 32)
128 let firstBin = min(length / 2 - 1, max(1, Int(lower * Double(length) / sampleRate)))
129 let lastBin = min(length / 2 - 1, max(firstBin, Int(upper * Double(length) / sampleRate)))
130 let amplitude = sqrt(power[firstBin...lastBin].max() ?? 0) / Float(length)
131 // Keep musical dynamics; the old -70...0 dB mapping flattened loud music.
132 bands[band] = min(1, pow(max(0, amplitude - 0.0005) * 5, 0.6))
133 }
134 let reaction = rhythm.at(time, frameInterval: frameInterval)
135 let (envelopes, swell) = rhythm.envelopes(at: time)
136 return AudioFeatures(bands: bands, pulse: reaction.pulse, momentum: reaction.momentum, beatMotionTime: reaction.beatMotionTime, treblePulse: reaction.treblePulse, trebleAttackTime: reaction.trebleAttackTime, envelopes: envelopes, swell: swell)
137 }
138
139}
140
141struct AudioAnalysisError: LocalizedError {
142 let message: String
143 init(_ message: String) { self.message = message }
144 var errorDescription: String? { message }
145}
146
147/// Detect actual attacks once from continuous PCM, then read them on the source timeline.
148/// No running tempo, frame-history dependency, or resetting filter at each preview frame.
149private struct RhythmTimeline {
150 struct Attack { let time: Double; let strength: Float }
151 let attacks: [Attack]
152 let trebleAttacks: [Attack]
153 let hopSeconds: Double
154 let momentum: [Float]
155 let motionTimes: [Double]
156 /// Per-hop smoothed band levels and attack swell, computed once so every frame is a
157 /// pure function of soundtrack time (identical in preview, Studio and export).
158 let bandEnvelopes: [SIMD4<Float>]
159 let swells: [Float]
160
161 init(file: AVAudioFile) throws {
162 let rate = file.processingFormat.sampleRate
163 let hop = max(1, Int((rate * 0.01).rounded()))
164 hopSeconds = Double(hop) / rate
165 let channelCount = Int(file.processingFormat.channelCount)
166 let capacity = AVAudioFrameCount(hop * 100)
167 guard let buffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: capacity) else {
168 throw AudioAnalysisError(String(localized: "Cannot allocate rhythm analysis buffer"))
169 }
170 var bass = [Float](), body = [Float](), treble = [Float]()
171 var bandEnergy = [SIMD4<Float>]()
172 // Crossovers match the renderer's 32-band groups: 123, 552 and 2960 Hz.
173 let crossovers = SIMD3<Float>(Float(1 - exp(-2 * Double.pi * 123 / rate)), Float(1 - exp(-2 * Double.pi * 552 / rate)), Float(1 - exp(-2 * Double.pi * 2960 / rate)))
174 var splitA = [SIMD3<Float>](repeating: .zero, count: channelCount), splitB = splitA
175 var lower = [Float](repeating: 0, count: channelCount), lower2 = lower, upper = lower
176 var high2 = lower, high3 = lower, high4 = lower
177 let lowCoefficient = Float(1 - exp(-2 * Double.pi * 180 / rate))
178 let highCoefficient = Float(1 - exp(-2 * Double.pi * 1800 / rate))
179 file.framePosition = 0
180 while file.framePosition < file.length {
181 try Task.checkCancellation()
182 try file.read(into: buffer, frameCount: capacity)
183 guard let samples = buffer.floatChannelData, buffer.frameLength > 0 else { break }
184 let count = Int(buffer.frameLength)
185 for first in stride(from: 0, to: count, by: hop) {
186 let last = min(count, first + hop)
187 var lo: Float = 0, mid: Float = 0, hi: Float = 0
188 var split = SIMD4<Float>(repeating: 0)
189 for channel in 0..<channelCount {
190 for index in first..<last {
191 let sample = samples[channel][index]
192 splitA[channel] += crossovers * (SIMD3(repeating: sample) - splitA[channel])
193 splitB[channel] += crossovers * (splitA[channel] - splitB[channel])
194 let lows = splitB[channel]
195 let parts = SIMD4(lows.x, lows.y - lows.x, lows.z - lows.y, sample - lows.z)
196 split += parts * parts
197 lower[channel] += lowCoefficient * (sample - lower[channel])
198 lower2[channel] += lowCoefficient * (lower[channel] - lower2[channel])
199 upper[channel] += highCoefficient * (sample - upper[channel])
200 let middle = upper[channel] - lower[channel]
201 // Four high-pass stages reject low-frequency leakage at a bass onset.
202 let high1 = sample - upper[channel]
203 high2[channel] += highCoefficient * (high1 - high2[channel])
204 let highSecond = high1 - high2[channel]
205 high3[channel] += highCoefficient * (highSecond - high3[channel])
206 let highThird = highSecond - high3[channel]
207 high4[channel] += highCoefficient * (highThird - high4[channel])
208 let high = highThird - high4[channel]
209 lo += lower2[channel] * lower2[channel]; mid += middle * middle; hi += high * high
210 }
211 }
212 let divisor = Float((last - first) * channelCount)
213 bass.append(lo / divisor); body.append(mid / divisor); treble.append(hi / divisor)
214 bandEnergy.append(split / divisor)
215 }
216 }
217 var events = [Attack](), hats = [Attack](), drive = [Float](repeating: 0, count: bass.count)
218 var lastKick = -Double.infinity, lastSnare = lastKick, lastHat = lastKick
219 var baseline = SIMD3<Float>(repeating: 0), previous = baseline
220 var currentMomentum: Float = 0
221 for tick in bass.indices {
222 let start = max(0, tick - 2), divisor = Float(tick - start + 1)
223 let envelope = SIMD3(sqrt(bass[start...tick].reduce(0,+) / divisor),
224 sqrt(body[start...tick].reduce(0,+) / divisor),
225 sqrt(treble[max(0,tick-1)...tick].reduce(0,+) / Float(min(tick+1,2))))
226 let rise = Self.simdMaxZero(envelope - previous)
227 let timestamp = max(0, Double(tick + 1) * hopSeconds - 0.008)
228 let kick = rise.x > max(0.0012, baseline.x * 0.20) && envelope.x > baseline.x * 1.3 && timestamp - lastKick > 0.085
229 let snare = rise.y > max(0.0025, baseline.y * 0.32) && envelope.y > baseline.y * 1.5 &&
230 envelope.z > max(0.001, envelope.y * 0.08) && timestamp - lastSnare > 0.075
231 let hat = rise.z > max(0.001, baseline.z * 0.4) && envelope.z > baseline.z * 1.5 && rise.z > rise.x * 0.10 && timestamp - lastHat > 0.035
232 var strength: Float = 0
233 if kick { strength = min(1, rise.x / max(0.003, baseline.x * 0.65)); lastKick = timestamp }
234 if snare { strength = max(strength, min(1, rise.y / max(0.005, baseline.y * 0.8))); lastSnare = timestamp }
235 if hat {
236 let hatStrength = min(1, rise.z / max(0.0015, baseline.z * 0.8))
237 hats.append(Attack(time: timestamp, strength: hatStrength))
238 strength = max(strength, hatStrength * 0.42); lastHat = timestamp
239 }
240 // A short silent lead-in has no synthetic pulse; only measured rises add drive.
241 if strength > 0.08 { events.append(Attack(time: timestamp, strength: strength)) }
242 currentMomentum = min(1, currentMomentum * Float(exp(-hopSeconds / 0.7)) + strength * 0.24)
243 drive[tick] = currentMomentum
244 baseline += (envelope - baseline) * Float(1 - exp(-hopSeconds / 0.22))
245 previous = envelope
246 }
247 attacks = events; trebleAttacks = hats; momentum = drive
248 (bandEnvelopes, swells) = Self.smoothedLevels(energy: bandEnergy, attacks: events, hop: hopSeconds)
249 var accumulated = [0.0]
250 accumulated.reserveCapacity(drive.count + 1)
251 for value in drive { accumulated.append(accumulated.last! + Double(value) * hopSeconds) }
252 motionTimes = accumulated
253 }
254
255 /// Normalizes each band against its own loud passages (95th percentile of non-silent
256 /// hops), so dynamics within a song are kept, then applies a rise/fall follower.
257 private static func smoothedLevels(energy: [SIMD4<Float>], attacks: [Attack], hop: Double) -> ([SIMD4<Float>], [Float]) {
258 guard !energy.isEmpty else { return ([], []) }
259 let amplitudes = energy.map { $0.replacing(with: 0, where: $0 .< 0).squareRoot() }
260 var reference = SIMD4<Float>(repeating: 1)
261 for band in 0..<4 {
262 let audible = amplitudes.map { $0[band] }.filter { $0 > 1e-4 }.sorted()
263 reference[band] = audible.isEmpty ? 1 : max(1e-4, audible[min(audible.count - 1, Int(Double(audible.count) * 0.95))])
264 }
265 // Resolve short subdivisions without holding most of a beat.
266 let rise = Float(1 - exp(-hop / 0.018)), fall = Float(1 - exp(-hop / 0.095))
267 var envelopes = [SIMD4<Float>](), level = SIMD4<Float>(repeating: 0)
268 envelopes.reserveCapacity(amplitudes.count)
269 for amplitude in amplitudes {
270 let target = simd_min(amplitude / reference, SIMD4<Float>(repeating: 1.15)) * 0.87
271 for band in 0..<4 { level[band] += (target[band] - level[band]) * (target[band] > level[band] ? rise : fall) }
272 envelopes.append(level)
273 }
274 var raw = [Float](repeating: 0, count: energy.count)
275 for attack in attacks {
276 let first = max(0, Int(attack.time / hop))
277 for tick in first..<min(raw.count, first + Int(0.35 / hop)) {
278 let age = max(0, Double(tick) * hop - attack.time)
279 raw[tick] = max(raw[tick], attack.strength * Float(exp(-age / 0.065)))
280 }
281 }
282 let attackRise = Float(1 - exp(-hop / 0.02)), attackFall = Float(1 - exp(-hop / 0.25))
283 var swells = [Float](), swell: Float = 0
284 swells.reserveCapacity(raw.count)
285 for value in raw {
286 swell += (value - swell) * (value > swell ? attackRise : attackFall)
287 swells.append(swell)
288 }
289 return (envelopes, swells)
290 }
291
292 func envelopes(at time: Double) -> (SIMD4<Float>, Float) {
293 guard !bandEnvelopes.isEmpty, time.isFinite, time >= 0 else { return (SIMD4<Float>(repeating: 0), 0) }
294 let position = min(Double(bandEnvelopes.count - 1), time / hopSeconds)
295 let tick = Int(position), next = min(bandEnvelopes.count - 1, tick + 1)
296 let fraction = Float(position - Double(tick))
297 let envelope = bandEnvelopes[tick] + (bandEnvelopes[next] - bandEnvelopes[tick]) * fraction
298 return (envelope, swells[tick] + (swells[next] - swells[tick]) * fraction)
299 }
300
301 func at(_ time: Double, frameInterval: Double) -> (pulse: Float, momentum: Float, beatMotionTime: Double, treblePulse: Float, trebleAttackTime: Double?) {
302 // Binary search keeps lookup cheap even for long soundtracks.
303 var low = 0, high = attacks.count
304 while low < high { let mid = (low + high) / 2; if attacks[mid].time <= time { low = mid + 1 } else { high = mid } }
305 var pulse: Float = 0, index = low - 1
306 while index >= 0 {
307 let attack = attacks[index], age = time - attack.time
308 if age > 0.32 { break }
309 pulse = max(pulse, attack.strength * Float(exp(-age / 0.065)))
310 index -= 1
311 }
312 let tick = max(0, min(momentum.count - 1, Int(time / hopSeconds)))
313 var hatLow = 0, hatHigh = trebleAttacks.count
314 while hatLow < hatHigh { let mid = (hatLow + hatHigh) / 2; if trebleAttacks[mid].time <= time { hatLow = mid + 1 } else { hatHigh = mid } }
315 var treble: Float = 0, hatIndex = hatLow - 1
316 let duration = max(0.025, min(0.1, frameInterval.isFinite ? frameInterval : 1.0 / 60))
317 while hatIndex >= 0 && time - trebleAttacks[hatIndex].time < duration {
318 treble = max(treble, trebleAttacks[hatIndex].strength); hatIndex -= 1
319 }
320 let lastHat = hatLow - 1
321 let attackTime = lastHat >= 0 ? trebleAttacks[lastHat].time : nil
322 if let attackTime, time - attackTime < 0.1 { treble = trebleAttacks[lastHat].strength }
323 let position = min(Double(momentum.count), max(0, time / hopSeconds))
324 let motion = momentum.isEmpty ? 0 : motionTimes[tick] + Double(momentum[tick]) * hopSeconds * (position - Double(tick))
325 return (pulse, momentum.isEmpty ? 0 : momentum[tick], motion, treble, attackTime)
326 }
327 func segmentPlan(duration: Double, beatsPerSection: Int) -> SongSegmentation {
328 let strong = attacks.filter { $0.strength >= 0.55 }
329 var period = 0.5, detectedBPM: Double? = nil, phase = 0.0
330 if strong.count >= 4 && duration >= 2 {
331 var impulses = [Float](repeating: 0, count: momentum.count)
332 for attack in strong {
333 let index = min(impulses.count - 1, Int(attack.time / hopSeconds))
334 if index >= 0 { impulses[index] = max(impulses[index], attack.strength) }
335 }
336 var bestScore: Float = 0
337 for lag in Int(0.3 / hopSeconds)...Int(1.0 / hopSeconds) where lag < impulses.count {
338 var score: Float = 0
339 for i in lag..<impulses.count where impulses[i] > 0 {
340 let lo = max(0, i - lag - 2), hi = min(impulses.count - 1, i - lag + 2)
341 score += impulses[i] * (impulses[lo...hi].max() ?? 0)
342 }
343 let candidate = Double(lag) * hopSeconds
344 score *= Float(exp(-pow(log(candidate / 0.5), 2) / 0.5))
345 if score > bestScore { bestScore = score; period = candidate }
346 }
347 if bestScore > 1 {
348 detectedBPM = 60 / period
349 var phases = [Float](repeating: 0, count: 64)
350 for attack in strong {
351 let fraction = attack.time / period - floor(attack.time / period)
352 let bin = Int(fraction * 64) % 64
353 for offset in -2...2 { phases[(bin + offset + 64) % 64] += attack.strength * Float(3 - abs(offset)) }
354 }
355 phase = Double(phases.indices.max(by: { phases[$0] < phases[$1] }) ?? 0) / 64 * period
356 }
357 }
358 let spacing = period * Double(max(1, beatsPerSection))
359 var points = [0.0], target = phase + spacing
360 while target < duration - 0.5 {
361 let nearby = strong.filter { abs($0.time - target) < period * 0.18 }
362 let cue = nearby.min(by: { abs($0.time-target) < abs($1.time-target) })?.time ?? target
363 if cue > points.last! + 0.5 { points.append(cue) }
364 target += spacing
365 }
366 points.append(duration)
367 return SongSegmentation(boundaries: points, bpm: detectedBPM)
368 }
369 private static func simdMaxZero(_ value: SIMD3<Float>) -> SIMD3<Float> {
370 SIMD3(max(0,value.x),max(0,value.y),max(0,value.z))
371 }
372}