PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / StrobeDetector.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// High-frequency onset gate. No tempo guessing or low-frequency beat trigger. |
| 4 | /// Absolute timestamps keep seeking, preview, and offline rendering consistent. |
| 5 | struct StrobeDetector { |
| 6 | private var previousEnergy: Float = 0 |
| 7 | private var noiseFloor: Float = 0 |
| 8 | private var lastTime = -Double.infinity |
| 9 | private var lastAttack = -Double.infinity |
| 10 | private var flashUntil = -Double.infinity |
| 11 | |
| 12 | mutating func reset() { self = StrobeDetector() } |
| 13 | |
| 14 | /// One white flash per source attack, including attacks between rendered frames. |
| 15 | mutating func nextSourceFrame(time: Double, attackTime: Double?, strength: Float, sensitivity: Float = 1) -> Float { |
| 16 | guard time.isFinite else { return 0 } |
| 17 | if time < lastTime || time - lastTime > 0.25 { reset() } |
| 18 | if time == lastTime { return time < flashUntil ? 1 : 0 } |
| 19 | let interval = lastTime.isFinite ? max(0.025, min(0.1, time - lastTime)) : 0.025 |
| 20 | let gain = max(0.25, min(4, sensitivity)) |
| 21 | if let attackTime, attackTime <= time, time - attackTime <= interval, |
| 22 | attackTime > lastAttack, strength >= 0.22 / gain { |
| 23 | lastAttack = attackTime; flashUntil = time + 0.020 |
| 24 | } |
| 25 | lastTime = time |
| 26 | return time < flashUntil ? 1 : 0 |
| 27 | } |
| 28 | |
| 29 | mutating func nextFrame(time: Double, bands: [Float], sensitivity: Float = 1) -> Float { |
| 30 | guard time.isFinite else { return 0 } |
| 31 | if time < lastTime || time - lastTime > 0.25 { reset() } |
| 32 | if time == lastTime { return time < flashUntil ? 1 : 0 } |
| 33 | let dt = lastTime.isFinite ? max(0, time - lastTime) : 1.0 / 60 |
| 34 | let treble = bands.dropFirst(24).prefix(8).map { $0.isFinite ? max(0, min(1, $0)) : 0 } |
| 35 | let energy = treble.isEmpty ? 0 : treble.reduce(0, +) / Float(treble.count) |
| 36 | let flux = max(0, energy - previousEnergy) |
| 37 | let gain = max(0.25, min(4, sensitivity)) |
| 38 | let threshold: Float = 0.055 / gain |
| 39 | let onset = flux > threshold && energy > max(0.10 / gain, noiseFloor * 1.08) |
| 40 | if onset && time - lastAttack >= 0.035 { |
| 41 | lastAttack = time |
| 42 | flashUntil = time + 0.025 |
| 43 | } |
| 44 | let follow = Float(1 - exp(-dt / 0.4)) |
| 45 | noiseFloor += (energy - noiseFloor) * follow |
| 46 | previousEnergy = energy |
| 47 | lastTime = time |
| 48 | return time < flashUntil ? 1 : 0 |
| 49 | } |
| 50 | } |