SPB Git

Repository Public License

PulseSynth.swift 27.0 KB 575 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Arcade9// File             : Games/PulseBeat/PulseSynth.swift10// Description      : Pulse Beat — offline synthesiser that renders a composed11//                    track to mono samples (drums, bass, lead, arpeggio, pads,12//                    echo, sidechain pumping, filter sweeps, risers) plus the13//                    loudness envelope that drives the reactive visuals.14// Module           : Games15// Repository       : https://git.spboucher.ai/orix-arcade16// Created          : 2026-11-2217// Last Modified    : 2026-11-2218//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : Proprietary, all rights reserved (see license file)84// License File     : LICENSE85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation9394/// Three loudness bands sampled 60 times a second, each normalised to 0…1. Drives the background, never the gameplay.95nonisolated struct PulseEnvelope: Sendable, Equatable {96    static let rate = 60.097    var low: [Float] = []98    var mid: [Float] = []99    var high: [Float] = []100101    func value(_ band: [Float], at time: Double) -> Double {102        guard !band.isEmpty, time >= 0 else { return 0 }103        let position = time * Self.rate104        let index = Int(position)105        guard index < band.count - 1 else { return index < band.count ? Double(band[index]) : 0 }106        let t = position - Double(index)107        return Double(band[index]) * (1 - t) + Double(band[index + 1]) * t108    }109}110111nonisolated struct PulseLayers: OptionSet, Sendable {112    let rawValue: Int113    static let drums = PulseLayers(rawValue: 1)114    static let bass = PulseLayers(rawValue: 2)115    static let lead = PulseLayers(rawValue: 4)116    static let arp = PulseLayers(rawValue: 8)117    static let pad = PulseLayers(rawValue: 16)118    static let effects = PulseLayers(rawValue: 32)119    static let all: PulseLayers = [.drums, .bass, .lead, .arp, .pad, .effects]120}121122nonisolated enum PulseSynth {123    static let sampleRate = Synth.sampleRate124    private static let tableBits = 12125    private static let tableSize = 1 << tableBits126    private static let tableShift = UInt32(32 - tableBits)127128    private static func additive(_ harmonics: Int, odd: Bool, rolloff: Double) -> [Float] {129        var table = [Float](repeating: 0, count: tableSize + 1)130        var peak = 0.0001131        var values = [Double](repeating: 0, count: tableSize + 1)132        for i in 0...tableSize {133            let x = 2 * Double.pi * Double(i) / Double(tableSize)134            var v = 0.0135            var h = 1136            while h <= harmonics {137                v += sin(x * Double(h)) / pow(Double(h), rolloff)138                h += odd ? 2 : 1139            }140            values[i] = v141            peak = max(peak, abs(v))142        }143        for i in 0...tableSize { table[i] = Float(values[i] / peak) }144        return table145    }146147    private static let sineTable = additive(1, odd: false, rolloff: 1)148    private static let triangleTable = additive(9, odd: true, rolloff: 2)149    private static let sawTable = additive(20, odd: false, rolloff: 1)150    private static let softSawTable = additive(7, odd: false, rolloff: 1.15)151    private static let squareTable = additive(15, odd: true, rolloff: 1)152    private static let softSquareTable = additive(5, odd: true, rolloff: 1.1)153154    static func frequency(_ midi: Int) -> Double { 440 * pow(2, (Double(midi) - 69) / 12) }155    static func frame(_ seconds: Double) -> Int { Int((seconds * sampleRate).rounded()) }156157    private static func table(_ timbre: PulseTimbre, frequency: Double) -> [Float] {158        switch timbre {159        case .sine: sineTable160        case .triangle: triangleTable161        case .saw: frequency > 520 ? softSawTable : sawTable162        case .square: frequency > 480 ? softSquareTable : squareTable163        }164    }165166    // MARK: Voices167168    /// Adds one wavetable voice: linear attack and release, exponential decay in between (`halfLife` in seconds, 0 = sustain).169    private static func voice(_ out: UnsafeMutablePointer<Float>, _ total: Int, table: [Float], start: Int, length: Int, frequency: Double,170                              amp: Float, attack: Double, release: Double, halfLife: Double = 0, phase: UInt32 = 0) {171        guard start < total, length > 0, start >= 0 else { return }172        let n = min(length, total - start)173        let increment = UInt32(truncatingIfNeeded: Int64(frequency / sampleRate * 4_294_967_296))174        let attackFrames = max(1, min(frame(attack), n / 2))175        let releaseFrames = max(1, min(frame(release), n / 2))176        let decay: Float = halfLife > 0 ? Float(pow(0.5, 1 / (halfLife * sampleRate))) : 1177        let attackStep = 1 / Float(attackFrames), releaseStep = 1 / Float(releaseFrames)178        let shift = tableShift179        table.withUnsafeBufferPointer { wave in180            guard let w = wave.baseAddress else { return }181            let target = out + start182            var ph = phase183            var level = amp184            var i = 0185            // Attack.186            while i < attackFrames {187                target[i] += w[Int(ph >> shift)] * level * (Float(i) * attackStep)188                ph &+= increment189                level *= decay190                i += 1191            }192            // Body.193            let bodyEnd = n - releaseFrames194            while i < bodyEnd {195                target[i] += w[Int(ph >> shift)] * level196                ph &+= increment197                level *= decay198                i += 1199            }200            // Release.201            while i < n {202                target[i] += w[Int(ph >> shift)] * level * (Float(n - i) * releaseStep)203                ph &+= increment204                level *= decay205                i += 1206            }207        }208    }209210    @inline(__always)211    private static func nextNoise(_ state: inout UInt32) -> Float {212        state ^= state << 13213        state ^= state >> 17214        state ^= state << 5215        return Float(Int32(bitPattern: state)) * (1 / 2_147_483_648)216    }217218    /// Adds filtered noise with an exponential decay. `brightness` 0…1 is the low-pass coefficient; `highpass` keeps what the low-pass removes.219    private static func noise(_ out: UnsafeMutablePointer<Float>, _ total: Int, start: Int, length: Int, amp: Float, halfLife: Double,220                              brightness: Float, highpass: Bool, seed: UInt32, attack: Int = 24) {221        guard start < total, length > 0, start >= 0 else { return }222        let n = min(length, total - start)223        let decay = Float(pow(0.5, 1 / (halfLife * sampleRate)))224        let target = out + start225        var state = seed | 1226        var lp: Float = 0227        var level = amp228        let fade = max(1, min(n / 4, 200))229        for i in 0..<n {230            let white = nextNoise(&state)231            lp += brightness * (white - lp)232            var v = (highpass ? white - lp : lp) * level233            if i < attack { v *= Float(i) / Float(attack) }234            if n - i < fade { v *= Float(n - i) / Float(fade) }235            target[i] += v236            level *= decay237        }238    }239240    /// Kick drum: a sine that drops from `from` to `to` hertz, with a short click on the very first samples.241    private static func kick(_ out: UnsafeMutablePointer<Float>, _ total: Int, start: Int, amp: Float, from: Double = 165, to: Double = 46) {242        let length = min(frame(0.26), total - start)243        guard start >= 0, length > 0 else { return }244        let target = out + start245        var sweep = from - to246        let sweepDecay = pow(0.5, 1 / (0.022 * sampleRate))247        let ampDecay = Float(pow(0.5, 1 / (0.07 * sampleRate)))248        var phase = 0.0249        var level = amp250        let fade = 300251        sineTable.withUnsafeBufferPointer { wave in252            guard let w = wave.baseAddress else { return }253            let size = Double(tableSize)254            for i in 0..<length {255                phase += (to + sweep) / sampleRate256                if phase >= 1 { phase -= 1 }257                var v = w[Int(phase * size)] * level258                if i < 12 { v *= Float(i + 1) / 12 }259                if length - i < fade { v *= Float(length - i) / Float(fade) }260                target[i] += v261                sweep *= sweepDecay262                level *= ampDecay263            }264        }265        noise(out, total, start: start, length: frame(0.006), amp: amp * 0.35, halfLife: 0.002, brightness: 0.6, highpass: false, seed: 0xBEEF, attack: 4)266    }267268    private static func snare(_ out: UnsafeMutablePointer<Float>, _ total: Int, start: Int, amp: Float, seed: UInt32) {269        noise(out, total, start: start, length: frame(0.17), amp: amp * 0.75, halfLife: 0.035, brightness: 0.35, highpass: true, seed: seed, attack: 6)270        voice(out, total, table: sineTable, start: start, length: frame(0.09), frequency: 188, amp: amp * 0.5, attack: 0.0004, release: 0.02, halfLife: 0.022)271        voice(out, total, table: sineTable, start: start, length: frame(0.06), frequency: 331, amp: amp * 0.28, attack: 0.0004, release: 0.02, halfLife: 0.015)272    }273274    // MARK: Render275276    /// Renders the whole track to mono samples at `sampleRate`. Every event starts on the sample `frame(song.time(step))`.277    /// `master` applies the soft clipper and normalises; stems rendered for analysis usually leave it on too.278    static func render(_ song: PulseSong, layers: PulseLayers = .all, master: Bool = true) -> [Float] {279        let total = frame(song.duration)280        var samples = [Float](repeating: 0, count: total)281        let step = song.stepDuration282        let spec = song.spec283        samples.withUnsafeMutableBufferPointer { buffer in284            guard let out = buffer.baseAddress else { return }285            func at(_ s: Int) -> Int { frame(Double(s) * step) }286287            // 1. Lead and arpeggio, then a dotted-eighth echo over both.288            if layers.contains(.lead) {289                for note in song.lead {290                    let f = frequency(note.midi)291                    // Each note stops just short of the next grid step, so every attack starts from near silence and reads as a clear onset.292                    let length = at(note.step + note.length) - at(note.step) - frame(0.012)293                    let amp = Float(0.13 * note.velocity)294                    let wave = table(spec.lead, frequency: f)295                    let sustain = Double(note.length) * step296                    voice(out, total, table: wave, start: at(note.step), length: length, frequency: f, amp: amp, attack: 0.002, release: 0.02,297                          halfLife: max(0.35, sustain * 0.9))298                    voice(out, total, table: wave, start: at(note.step), length: length, frequency: f * 1.006, amp: amp * 0.8, attack: 0.002, release: 0.02,299                          halfLife: max(0.35, sustain * 0.9), phase: 0x4000_0000)300                    voice(out, total, table: sineTable, start: at(note.step), length: min(length, frame(0.12)), frequency: f * 2, amp: amp * 0.5,301                          attack: 0.001, release: 0.03, halfLife: 0.03)302                }303            }304            if layers.contains(.arp) {305                for note in song.arp {306                    let f = frequency(note.midi)307                    voice(out, total, table: triangleTable, start: at(note.step), length: frame(step * Double(note.length) * 1.6 + 0.04), frequency: f,308                          amp: Float(0.075 * note.velocity), attack: 0.002, release: 0.03, halfLife: 0.07)309                }310            }311            if layers.contains(.effects), layers.contains(.lead) || layers.contains(.arp) {312                let delay = frame(step * 3)313                var i = delay314                while i < total {315                    out[i] += out[i - delay] * 0.3316                    i += 1317                }318            }319320            // 2. Pads and bass.321            if layers.contains(.pad) {322                for chord in song.pads {323                    let start = at(chord.step)324                    let length = at(chord.step + chord.length) - start + frame(0.35)325                    for (index, midi) in chord.midis.enumerated() {326                        let f = frequency(midi)327                        let amp = Float(0.05 * chord.velocity) * (index == 3 ? 0.7 : 1)328                        voice(out, total, table: softSawTable, start: start, length: length, frequency: f, amp: amp, attack: 0.12, release: 0.35,329                              phase: UInt32(truncatingIfNeeded: index &* 0x2468_ACE1))330                        voice(out, total, table: triangleTable, start: start, length: length, frequency: f * 1.0045, amp: amp, attack: 0.16, release: 0.35,331                              phase: UInt32(truncatingIfNeeded: index &* 0x1357_9BDF))332                    }333                }334            }335            if layers.contains(.bass) {336                for note in song.bass {337                    let f = frequency(note.midi)338                    let length = at(note.step + note.length) - at(note.step) - frame(0.012)339                    let amp = Float(0.3 * note.velocity)340                    voice(out, total, table: sineTable, start: at(note.step), length: length, frequency: f, amp: amp, attack: 0.002, release: 0.01, halfLife: 0.4)341                    voice(out, total, table: softSawTable, start: at(note.step), length: length, frequency: f, amp: amp * 0.45, attack: 0.002, release: 0.01, halfLife: 0.12)342                }343            }344345            // 3. Sidechain: everything melodic ducks under each kick and swells back.346            if layers.contains(.effects), layers.contains(.drums) {347                let window = min(frame(0.24), frame(song.beatDuration * 0.9))348                for hit in song.kicks {349                    let start = at(hit.step)350                    let depth: Float = song.section(atStep: hit.step) == .drop ? 0.62 : 0.4351                    let end = min(total, start + window)352                    var i = start353                    while i < end {354                        let x = Float(i - start) / Float(window)355                        let dip = depth * (1 - x) * (1 - x) * min(1, Float(i - start) / 64)356                        out[i] *= 1 - dip357                        i += 1358                    }359                }360            }361362            // 4. Builds: a low-pass filter opens from dark to bright over the section.363            if layers.contains(.effects) {364                for riser in song.risers {365                    let start = at(riser.start), end = min(total, at(riser.end))366                    guard end > start else { continue }367                    var state: Float = 0368                    let span = Float(end - start)369                    var i = start370                    while i < end {371                        let x = Float(i - start) / span372                        let coefficient = 0.035 + 0.965 * x * x * x373                        state += coefficient * (out[i] - state)374                        out[i] = state375                        i += 1376                    }377                }378            }379380            // 5. Drums and one-shots, on top and unfiltered so their attacks stay sharp.381            if layers.contains(.drums) {382                for hit in song.kicks { kick(out, total, start: at(hit.step), amp: Float(0.85 * hit.velocity)) }383                for (index, hit) in song.snares.enumerated() {384                    snare(out, total, start: at(hit.step), amp: Float(0.5 * hit.velocity), seed: UInt32(truncatingIfNeeded: 0x51A9 &+ index &* 7919))385                }386                for (index, hit) in song.hats.enumerated() {387                    noise(out, total, start: at(hit.step), length: frame(0.05), amp: Float(0.16 * hit.velocity), halfLife: 0.009, brightness: 0.85,388                          highpass: true, seed: UInt32(truncatingIfNeeded: 0x4A7 &+ index &* 104_729), attack: 4)389                }390                for (index, hit) in song.openHats.enumerated() {391                    noise(out, total, start: at(hit.step), length: frame(0.2), amp: Float(0.14 * hit.velocity), halfLife: 0.05, brightness: 0.8,392                          highpass: true, seed: UInt32(truncatingIfNeeded: 0x0FE7 &+ index &* 15_485_863), attack: 8)393                }394            }395            if layers.contains(.effects), layers.contains(.drums) {396                for (index, crash) in song.crashes.enumerated() {397                    noise(out, total, start: at(crash), length: frame(1.6), amp: 0.3, halfLife: 0.32, brightness: 0.55, highpass: true,398                          seed: UInt32(truncatingIfNeeded: 0xC4A5 &+ index &* 31), attack: 30)399                }400                for (index, riser) in song.risers.enumerated() {401                    let start = at(riser.start), end = min(total, at(riser.end))402                    guard end > start else { continue }403                    var state = UInt32(truncatingIfNeeded: 0x715E &+ index &* 977) | 1404                    var lp: Float = 0405                    let span = Float(end - start)406                    var i = start407                    while i < end {408                        let x = Float(i - start) / span409                        let white = nextNoise(&state)410                        lp += (0.05 + 0.5 * x) * (white - lp)411                        var v = lp * 0.2 * x * x412                        if end - i < 220 { v *= Float(end - i) / 220 }413                        out[i] += v414                        i += 1415                    }416                }417            }418419            // 6. Master: soft clip, then normalise.420            guard master else { return }421            var peak: Float = 0.0001422            var i = 0423            while i < total {424                let v = tanhf(out[i] * 1.05)425                out[i] = v426                let magnitude = v < 0 ? -v : v427                if magnitude > peak { peak = magnitude }428                i += 1429            }430            let gain = min(0.9 / peak, 4)431            i = 0432            while i < total {433                out[i] *= gain434                i += 1435            }436        }437        return samples438    }439440    // MARK: Analysis441442    /// Loudness in three bands (below ~160 Hz, everything, above ~3 kHz), each normalised to its own 97th percentile.443    static func envelope(of samples: [Float]) -> PulseEnvelope {444        let hop = Int(sampleRate / PulseEnvelope.rate)445        let frames = samples.count / hop446        guard frames > 0 else { return PulseEnvelope() }447        var low = [Float](repeating: 0, count: frames), mid = low, high = low448        samples.withUnsafeBufferPointer { buffer in449            guard let x = buffer.baseAddress else { return }450            var lpLow: Float = 0, lpHigh: Float = 0451            for f in 0..<frames {452                var sumLow: Float = 0, sumAll: Float = 0, sumHigh: Float = 0453                var i = f * hop454                let end = i + hop455                while i < end {456                    let v = x[i]457                    lpLow += 0.0225 * (v - lpLow)458                    lpHigh += 0.35 * (v - lpHigh)459                    let top = v - lpHigh460                    sumLow += lpLow * lpLow461                    sumAll += v * v462                    sumHigh += top * top463                    i += 1464                }465                low[f] = (sumLow / Float(hop)).squareRoot()466                mid[f] = (sumAll / Float(hop)).squareRoot()467                high[f] = (sumHigh / Float(hop)).squareRoot()468            }469        }470        func normalise(_ band: inout [Float]) {471            let sorted = band.sorted()472            let reference = max(sorted[min(sorted.count - 1, Int(Double(sorted.count) * 0.97))], 0.0001)473            for i in band.indices { band[i] = min(1, band[i] / reference) }474        }475        normalise(&low)476        normalise(&mid)477        normalise(&high)478        return PulseEnvelope(low: low, mid: mid, high: high)479    }480481    /// Time at which the sound rises near `time` (within `radius` seconds), or nil when nothing clearly starts there.482    ///483    /// Short-time energy is measured in sliding windows. The quietest window around the expected time marks "before"; the loudest window in the484    /// 25 ms after it marks "after"; the onset is where the energy first climbs 40 % of the way, corrected for the window length. An attack must485    /// at least triple the energy to count. The high band (first difference) sees clicks, snares and plucks; the low band is the fallback for a486    /// kick under a ringing cymbal.487    static func onset(in samples: [Float], near time: Double, radius: Double = 0.012) -> Double? {488        detect(samples, time, radius, lowBand: false) ?? detect(samples, time, radius, lowBand: true)489    }490491    private static func detect(_ samples: [Float], _ time: Double, _ radius: Double, lowBand: Bool) -> Double? {492        let window = frame(lowBand ? 0.006 : 0.003)493        let hop = 11494        let center = frame(time)495        let from = center - frame(radius) - window, to = center + frame(radius) + frame(0.025) + window * 2496        guard from > 2400, to < samples.count else { return nil }497        let count = to - from498        // Running sum of the squared band signal.499        var prefix = [Double](repeating: 0, count: count + 1)500        if lowBand {501            var lp: Float = 0502            for i in (from - 2400)..<to {503                lp += 0.04 * (samples[i] - lp)504                if i >= from { prefix[i - from + 1] = prefix[i - from] + Double(lp * lp) }505            }506        } else {507            for i in from..<to {508                let d = samples[i] - samples[i - 1]509                prefix[i - from + 1] = prefix[i - from] + Double(d * d)510            }511        }512        func energy(_ start: Int) -> Double { prefix[start + window] - prefix[start] }513        // The quietest window that ends inside the search range.514        let lastStart = 2 * frame(radius)515        var quietStart = 0516        var quiet = Double.infinity517        var start = 0518        while start <= lastStart {519            let e = energy(start)520            if e < quiet { quiet = e; quietStart = start }521            start += hop522        }523        var loud = 0.0524        start = quietStart525        let horizon = min(count - window, quietStart + frame(0.025))526        while start <= horizon {527            loud = max(loud, energy(start))528            start += hop529        }530        guard loud > 1e-9, loud >= 3 * quiet else { return nil }531        let threshold = quiet + 0.4 * (loud - quiet)532        start = quietStart533        while start <= horizon {534            if energy(start) >= threshold {535                return (Double(from + start + window) - 0.4 * Double(window)) / sampleRate536            }537            start += hop538        }539        return nil540    }541542    // MARK: Small sounds543544    /// The calibration click track: `count` clicks, one every `interval` seconds, the first at `lead`. Returns the samples and the click times.545    static func clickTrack(count: Int, interval: Double, lead: Double, accentEvery: Int = 4) -> (samples: [Float], clicks: [Double]) {546        let total = frame(lead + Double(count) * interval + 0.4)547        var samples = [Float](repeating: 0, count: total)548        var clicks: [Double] = []549        samples.withUnsafeMutableBufferPointer { buffer in550            guard let out = buffer.baseAddress else { return }551            for index in 0..<count {552                let time = lead + Double(index) * interval553                clicks.append(time)554                let accent = index % accentEvery == 0555                voice(out, total, table: sineTable, start: frame(time), length: frame(0.05), frequency: accent ? 1760 : 1320, amp: 0.7,556                      attack: 0.0003, release: 0.01, halfLife: 0.008)557                noise(out, total, start: frame(time), length: frame(0.004), amp: 0.4, halfLife: 0.001, brightness: 0.9, highpass: false, seed: 0xC11C, attack: 2)558            }559        }560        return (samples, clicks)561    }562563    /// Soft percussive tick played when a note is hit.564    static func hitSound() -> [Float] {565        let total = frame(0.06)566        var samples = [Float](repeating: 0, count: total)567        samples.withUnsafeMutableBufferPointer { buffer in568            guard let out = buffer.baseAddress else { return }569            voice(out, total, table: triangleTable, start: 0, length: frame(0.05), frequency: 1480, amp: 0.5, attack: 0.0004, release: 0.01, halfLife: 0.008)570            noise(out, total, start: 0, length: frame(0.012), amp: 0.3, halfLife: 0.003, brightness: 0.8, highpass: true, seed: 0x7AC, attack: 2)571        }572        return samples573    }574}575
Files main
Menu

Theme