Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX DJ9// File : Packages/ORIXDJCore/Tests/ORIXDSPTests/EffectsTests.swift10// Description : Behavioural tests of the 18 effect units, measured on11// synthesised signals.12// Module : ORIXDSPTests13// Repository : https://git.spboucher.ai/orix-dj14// Created : 2026-11-2115// Last Modified : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation90import ORIXDSP91import Testing9293@Suite struct GenericEffectTests {94 @Test func factoryBuildsEveryKind() {95 for kind in EffectKind.allCases {96 let fx = EffectFactory.make(kind, sampleRate: testRate)97 #expect(fx.kind == kind)98 for (i, p) in fx.descriptor.params.enumerated() { #expect(fx.values[i] == p.defaultValue) }99 }100 #expect(EffectKind.allCases.count == 18)101 }102103 /// Defaults, both extremes of every parameter, and all-min / all-max: finite and bounded output.104 @Test(arguments: EffectKind.allCases) func finiteAndBounded(kind: EffectKind) {105 let params = EffectCatalog.descriptor(kind).params106 var configs: [[Float]] = [params.map(\.defaultValue), params.map(\.min), params.map(\.max)]107 for (i, p) in params.enumerated() {108 for v in [p.min, p.max] { var c = params.map(\.defaultValue); c[i] = v; configs.append(c) }109 }110 let inL = testSignal(seconds: 2, seed: 7), inR = testSignal(seconds: 2, seed: 99)111 for config in configs {112 for sampleRate in [testRate, 44100] {113 let rig = Rig(kind, bpm: 128)114 let fx = sampleRate == testRate ? rig.fx : EffectFactory.make(kind, sampleRate: sampleRate)115 _ = fx // 44.1 kHz instance is exercised below through its own render calls116 if sampleRate != testRate {117 fx.setMix(1); fx.setEnabled(true); fx.setTransport(bpm: 128, beatPosition: 0)118 for (i, v) in config.enumerated() { fx.setParameter(i, v) }119 var l = Array(inL.prefix(20000)), r = Array(inR.prefix(20000))120 l.withUnsafeMutableBufferPointer { pl in r.withUnsafeMutableBufferPointer { pr in121 var i = 0122 while i < 20000 { let c = min(441, 20000 - i); fx.render(pl.baseAddress! + i, pr.baseAddress! + i, c); i += c }123 } }124 #expect(l.allSatisfy(\.isFinite) && r.allSatisfy(\.isFinite), "\(kind) \(config) @44.1k")125 continue126 }127 for (i, v) in config.enumerated() { rig.fx.setParameter(i, v) }128 let out = rig.run(inL, inR)129 #expect(out.l.allSatisfy(\.isFinite) && out.r.allSatisfy(\.isFinite), "\(kind) \(config)")130 let p = max(peak(out.l), peak(out.r))131 #expect(p <= 12, "\(kind) \(config) peak \(p)")132 }133 }134 }135136 /// Out-of-range and non-finite control values and NaN / infinite audio never leave the unit in a broken state.137 @Test(arguments: EffectKind.allCases) func survivesBadInput(kind: EffectKind) {138 let rig = Rig(kind)139 for i in 0 ..< rig.fx.descriptor.params.count {140 rig.fx.setParameter(i, .nan); rig.fx.setParameter(i, .infinity); rig.fx.setParameter(i, -1e9); rig.fx.setParameter(i, 1e9)141 }142 var bad = testSignal(seconds: 0.2)143 bad[100] = .nan; bad[200] = .infinity; bad[300] = -.infinity; bad[400] = 1e30144 _ = rig.run(bad)145 rig.fx.setTransport(bpm: 128, beatPosition: .nan)146 _ = rig.run(testSignal(seconds: 4.5)) // longer than the longest delay line so bad samples would resurface147 let out = rig.run(testSignal(seconds: 0.5))148 #expect(out.l.allSatisfy(\.isFinite) && out.r.allSatisfy(\.isFinite))149 #expect(max(peak(out.l), peak(out.r)) <= 40)150 }151152 @Test(arguments: EffectKind.allCases) func disabledIsBitTransparent(kind: EffectKind) {153 let rig = Rig(kind, mix: nil, enabled: false)154 let inL = testSignal(seconds: 0.5, seed: 3), inR = testSignal(seconds: 0.5, seed: 4)155 let out = rig.run(inL, inR)156 #expect(out.l == inL && out.r == inR)157 // Enabled then disabled: transparent again once the 12 ms fade is over.158 rig.fx.setEnabled(true); _ = rig.run(inL, inR)159 rig.fx.setEnabled(false); _ = rig.run(Array(inL.prefix(2048)), Array(inR.prefix(2048)))160 #expect(!rig.fx.isActive)161 let again = rig.run(inL, inR)162 #expect(again.l == inL && again.r == inR)163 }164165 /// Toggling the unit never produces a sample-to-sample step larger than what the dry and the steady wet signals contain.166 @Test(arguments: EffectKind.allCases) func enableDisableHasNoStep(kind: EffectKind) {167 let rig = Rig(kind, enabled: false)168 let input = sine(100, amplitude: 0.5, seconds: 1.5)169 let on = frames(0.5) + 137, off = frames(1.0) + 211170 var out: [Float] = []171 rig.block = 64172 out += rig.run(Array(input[..<on])).l173 rig.fx.setEnabled(true)174 out += rig.run(Array(input[on ..< off])).l175 rig.fx.setEnabled(false)176 out += rig.run(Array(input[off...])).l177 #expect(abs(out[on] - input[on]) < 0.02, "first enabled sample jumps away from the dry signal")178 let steady = maxDelta(out[(on + 4000) ..< off]), dry = maxDelta(input[0 ..< on])179 let bound = steady + dry + 0.01180 #expect(maxDelta(out[(on - 1) ..< (on + 700)]) <= bound, "enable step")181 #expect(maxDelta(out[(off - 1) ..< (off + 700)]) <= bound, "disable step")182 #expect(Array(out[(off + 700)...]) == Array(input[(off + 700)...]))183 }184185 /// The result does not depend on how the stream is cut into blocks.186 @Test(arguments: EffectKind.allCases) func blockSizeIndependent(kind: EffectKind) {187 let input = testSignal(seconds: 1)188 let a = Rig(kind, block: 512).run(input), b = Rig(kind, block: 64).run(input)189 let worst = zip(a.l, b.l).reduce(Float(0)) { max($0, abs($1.0 - $1.1)) }190 // The gate edge may land one sample apart (block-start phase vs accumulated phase): one step of its 1 ms ramp.191 #expect(worst < (kind == .gate ? 0.05 : 2e-3), "\(kind) differs by \(worst)")192 }193}194195@Suite struct SpaceEffectTests {196 @Test(arguments: [(128.0, Float(0.5), Float(0.35)), (120.0, Float(0.25), Float(0.8)), (93.0, Float(1), Float(0.5)), (60.0, Float(4), Float(0.6))])197 func delayImpulseResponse(bpm: Double, beats: Float, feedback: Float) {198 let rig = Rig(.delay, bpm: bpm)199 rig.set("time", beats); rig.set("feedback", feedback)200 rig.runSilence(seconds: 0.5) // enable fade, tap crossfade and smoothers settle201 let expected = Int((Double(beats) * 60 / bpm * testRate).rounded())202 var impulse = [Float](repeating: 0, count: expected * 3 + 100)203 impulse[0] = 1204 let out = rig.run(impulse).l205 let first = out.firstIndex { abs($0) > 1e-4 }206 #expect(first == expected, "first repeat at \(String(describing: first)), expected \(expected)")207 #expect(abs(out[expected] - 1) < 1e-3)208 #expect(abs(out[2 * expected] / out[expected] - feedback) < 2e-3)209 #expect(abs(out[3 * expected] / out[2 * expected] - feedback) < 2e-3)210 let between = out[(expected + 1) ..< (2 * expected)]211 #expect(peak(between) < 1e-6, "energy between repeats")212 }213214 @Test func delayPingPongAlternatesSides() {215 let rig = Rig(.delay, bpm: 120)216 rig.set("time", 0.25); rig.set("feedback", 0.5); rig.set("pingpong", 1)217 rig.runSilence(seconds: 0.5)218 var impulse = [Float](repeating: 0, count: 30000); impulse[0] = 1219 let out = rig.run(impulse), d = 6000220 #expect(abs(out.l[d]) > 0.9 && abs(out.r[d]) < 1e-3)221 #expect(abs(out.r[2 * d]) > 0.45 && abs(out.l[2 * d]) < 1e-3)222 #expect(abs(out.l[3 * d]) > 0.2 && abs(out.r[3 * d]) < 1e-3)223 }224225 /// Changing the delay time (parameter or tempo) on a steady tone is rendered as a crossfade, not a jump.226 @Test(arguments: [EffectKind.delay, .echo]) func delayTimeChangeDoesNotClick(kind: EffectKind) {227 let rig = Rig(kind, bpm: 120)228 rig.set("feedback", 0); rig.set("time", 0.5)229 if kind == .echo { rig.set("tone", 12000) }230 let tone = sine(200, amplitude: 0.5, seconds: 3)231 let a = rig.run(Array(tone[..<48000])).l232 rig.set("time", 0.37)233 let b = rig.run(Array(tone[48000 ..< 72000])).l234 rig.bpm = 97235 let c = rig.run(Array(tone[72000...])).l236 let steady = maxDelta(a[30000...])237 #expect(steady > 0.005)238 #expect(maxDelta((a.suffix(1) + b)[...]) <= steady * 1.1 + 1e-4)239 #expect(maxDelta((b.suffix(1) + c)[...]) <= steady * 1.1 + 1e-4)240 }241242 @Test func echoRepeatsOnTheGridAndGetDarker() {243 let rig = Rig(.echo, bpm: 120)244 rig.set("time", 0.5); rig.set("feedback", 0.7); rig.set("tone", 2000)245 rig.runSilence(seconds: 0.5)246 var click = [Float](repeating: 0, count: 60000); click[0] = 1247 let out = rig.run(click).l, d = 12000248 #expect(peak(out[0 ..< d]) < 1e-6)249 func brightness(_ k: Int) -> Double { // high band / low band energy of the k-th repeat250 let slice = Array(out[(k * d) ..< (k * d + 4000)])251 return bandEnergy(slice, centre: 8000) / bandEnergy(slice, centre: 300)252 }253 #expect(energy(out[d ..< d + 4000]) > 0)254 #expect(brightness(2) < brightness(1) * 0.7)255 #expect(brightness(3) < brightness(2) * 0.7)256 #expect(energy(out[(2 * d) ..< (2 * d + 4000)]) < energy(out[d ..< (d + 4000)]))257 }258259 /// Schroeder decay curve of the impulse response: energy per 100 ms window keeps falling and RT60 grows with size.260 @Test func reverbDecaysMonotonicallyAndGrowsWithSize() {261 func response(_ size: Float, seconds: Double) -> [Float] {262 let rig = Rig(.reverb)263 rig.set("size", size)264 rig.runSilence(seconds: 0.1)265 var impulse = silence(seconds); impulse[0] = 1266 let out = rig.run(impulse)267 return zip(out.l, out.r).map { ($0 * $0 + $1 * $1).squareRoot() }268 }269 func rt60(_ h: [Float]) -> Double {270 var tail = [Double](repeating: 0, count: h.count + 1)271 for i in stride(from: h.count - 1, through: 0, by: -1) { tail[i] = tail[i + 1] + Double(h[i]) * Double(h[i]) }272 let t5 = tail.firstIndex { $0 < tail[0] * pow(10, -0.5) }!, t25 = tail.firstIndex { $0 < tail[0] * pow(10, -2.5) }!273 return Double(t25 - t5) / testRate * 3274 }275 var times: [Double] = []276 for size in [Float(0), 0.3, 0.55, 0.8] {277 let h = response(size, seconds: 6), w = frames(0.1)278 let windows = stride(from: w, to: frames(1.5), by: w).map { energy(h[$0 ..< $0 + w]) }279 for k in 1 ..< windows.count { #expect(windows[k] < windows[k - 1], "size \(size): window \(k) grew") }280 #expect(windows[0] > 0)281 times.append(rt60(h))282 }283 print("Reverb RT60 (s) for size 0, 0.3, 0.55, 0.8:", times.map { String(format: "%.2f", $0) }.joined(separator: ", "))284 for k in 1 ..< times.count { #expect(times[k] > times[k - 1] * 1.15) }285 #expect(times[0] > 0.2 && times[3] < 6)286 }287288 @Test func reverbPreDelayAndWidth() {289 let rig = Rig(.reverb)290 rig.set("predelay", 100)291 rig.runSilence(seconds: 0.2)292 var impulse = silence(1); impulse[0] = 1293 let out = rig.run(impulse)294 #expect(peak(out.l[0 ..< 4800]) < 1e-6, "nothing may come out before the pre-delay")295 #expect(peak(out.l[4800 ..< 12000]) > 1e-3)296 #expect(out.l != out.r, "full width is decorrelated")297 let mono = Rig(.reverb); mono.set("width", 0); mono.runSilence(seconds: 1)298 let m = mono.run(impulse)299 #expect(zip(m.l, m.r).allSatisfy { abs($0 - $1) < 1e-6 }, "zero width is mono")300 }301}302303@Suite struct ModulationEffectTests {304 @Test func flangerDelaySweepsInsideItsRange() {305 let rig = Rig(.flanger)306 rig.set("feedback", 0); rig.set("rate", 2); rig.set("depth", 1)307 rig.runSilence(seconds: 0.1)308 var seen: [Int] = []309 for _ in 0 ..< 40 { // an impulse every 20 ms: the wet signal is the delayed impulse310 var impulse = [Float](repeating: 0, count: 960); impulse[0] = 1311 let out = rig.run(impulse).l312 seen.append(out.indices.max { abs(out[$0]) < abs(out[$1]) }!)313 }314 let lo = seen.min()!, hi = seen.max()!315 #expect(lo >= 37 && lo <= 60, "shortest delay \(lo) samples")316 #expect(hi <= 328 && hi >= 280, "longest delay \(hi) samples")317 }318319 @Test func phaserIsAllPassAndMovesNotches() {320 // Without feedback the wet path is a pure all-pass chain: level preserved.321 let rig = Rig(.phaser); rig.set("feedback", 0)322 let input = whiteNoise(amplitude: 0.5, seconds: 2)323 let wet = rig.run(input).l324 #expect(abs(db(rms(wet[24000...])) - db(rms(input[24000...]))) < 0.5)325 // At 50 % mix the notches appear and move: the level of a fixed tone is modulated at the LFO rate.326 let mixed = Rig(.phaser, mix: 0.5); mixed.set("feedback", 0); mixed.set("rate", 2); mixed.set("depth", 1)327 let out = mixed.run(sine(800, amplitude: 0.5, seconds: 2)).l328 let levels = stride(from: 24000, to: 96000 - 1200, by: 1200).map { rms(out[$0 ..< $0 + 1200]) }329 #expect(levels.max()! / max(levels.min()!, 1e-9) > 4, "notch depth")330 }331332 @Test func chorusDetunesAndStaysBounded() {333 let rig = Rig(.chorus); rig.set("depth", 1); rig.set("rate", 0.8)334 let input = sine(1000, amplitude: 0.5, seconds: 2)335 let out = rig.run(input)336 let tail = out.l[48000...]337 #expect(peak(tail) <= 0.5 * 1.7321 + 0.01)338 #expect(rms(tail) > 0.05)339 // Modulated taps spread energy around the carrier: the exact 1 kHz bin no longer holds all the energy.340 let carrier = amplitude(tail, at: 1000)341 #expect(Double(carrier * carrier) / 2 < 0.98 * energy(tail) / Double(tail.count))342 #expect(out.l != out.r)343 let still = Rig(.chorus); still.set("depth", 0)344 let fixed = still.run(input).l[48000...]345 let c0 = amplitude(fixed, at: 1000)346 #expect(Double(c0 * c0) / 2 > 0.999 * energy(fixed) / Double(fixed.count), "depth 0 leaves the pitch alone")347 }348}349350@Suite struct DistortionEffectTests {351 @Test(arguments: [Float(1), 0.5]) func distortionPeakDoesNotGrowWithDrive(level: Float) {352 var peaks: [Float] = [], levels: [Float] = []353 for drive in stride(from: Float(0), through: 36, by: 6) {354 let rig = Rig(.distortion); rig.set("drive", drive); rig.set("tone", 16000)355 let out = rig.run(sine(220, amplitude: level, seconds: 0.5)).l[12000...]356 peaks.append(peak(out)); levels.append(rms(out))357 }358 for k in 1 ..< peaks.count { #expect(peaks[k] <= peaks[k - 1] * 1.005, "peak grew at step \(k): \(peaks)") }359 #expect(peaks.max()! <= level * 1.005)360 #expect(levels.last! > levels.first! * 1.2 || level == 1, "more drive is denser")361 }362363 @Test func distortionIsNearlyTransparentWithoutDriveAndAddsOddHarmonics() {364 let clean = Rig(.distortion); clean.set("drive", 0); clean.set("tone", 16000)365 let quiet = clean.run(sine(220, amplitude: 0.1, seconds: 0.5)).l[12000...]366 #expect(abs(db(amplitude(quiet, at: 220)) - db(0.1)) < 1)367 let hot = Rig(.distortion); hot.set("drive", 24); hot.set("tone", 16000)368 let out = hot.run(sine(220, amplitude: 0.5, seconds: 0.5)).l[12000...]369 #expect(amplitude(out, at: 660) > 0.05) // third harmonic370 #expect(amplitude(out, at: 440) < 0.002) // symmetric clipper: no even harmonics371 // Tone control darkens.372 let dark = Rig(.distortion); dark.set("drive", 24); dark.set("tone", 500)373 let d = dark.run(sine(220, amplitude: 0.5, seconds: 0.5)).l[12000...]374 #expect(amplitude(d, at: 1540) < amplitude(out, at: 1540) * 0.6)375 }376377 @Test(arguments: [Float(2), 3, 4, 6, 8]) func bitcrusherLevelCount(bits: Float) {378 let rig = Rig(.bitcrusher); rig.set("bits", bits); rig.set("downsample", 1)379 let input = zip(sine(97, amplitude: 1.2, seconds: 1), whiteNoise(amplitude: 0.3, seconds: 1)).map { $0 + $1 }380 let out = rig.run(input).l[4800...]381 let levels = Set(out.map { Int(($0 * 65536).rounded()) }).count // the base mixer adds rounding noise at 1e-7382 #expect(levels <= Int(powf(2, bits)))383 #expect(levels >= Int(powf(2, bits)) - 1, "the quantiser should use its codes (\(levels))")384 #expect(peak(out) <= 1)385 #expect(rig.run(silence(0.1)).l.suffix(100).allSatisfy { $0 == 0 }, "silence stays silent")386 }387388 @Test func bitcrusherSampleAndHold() {389 let rig = Rig(.bitcrusher); rig.set("bits", 16); rig.set("downsample", 8)390 let out = rig.run(whiteNoise(amplitude: 0.8, seconds: 0.5)).l[4800...]391 var runs: [Int] = [], length = 1, previous = out.first!392 for v in out.dropFirst() { if abs(v - previous) < 1e-6 { length += 1 } else { runs.append(length); length = 1; previous = v } }393 #expect(runs.dropFirst().allSatisfy { $0 % 8 == 0 }, "held runs are multiples of the factor")394 #expect(runs.count > 1000)395 }396}397398@Suite struct FilterEffectTests {399 /// Steady-state gain of the unit at `frequency`, in dB.400 func gain(_ kind: EffectKind, cutoff: Float, q: Float, at frequency: Double) -> Float {401 let rig = Rig(kind); rig.set("cutoff", cutoff); rig.set("resonance", q)402 rig.runSilence(seconds: 0.3)403 let out = rig.run(sine(frequency, amplitude: 0.5, seconds: 1)).l404 return db(amplitude(out[24000...], at: frequency) / 0.5)405 }406407 @Test func lowpassIsTwelveDecibelsPerOctave() {408 #expect(abs(gain(.lowpass, cutoff: 200, q: 0.7071, at: 200) + 3.01) < 0.3)409 #expect(abs(gain(.lowpass, cutoff: 200, q: 0.7071, at: 20)) < 0.1)410 #expect(abs(gain(.lowpass, cutoff: 200, q: 0.7071, at: 2000) + 40) < 1.5)411 #expect(abs(gain(.lowpass, cutoff: 200, q: 0.7071, at: 400) - gain(.lowpass, cutoff: 200, q: 0.7071, at: 800) - 12) < 1.5)412 #expect(abs(gain(.lowpass, cutoff: 1000, q: 4, at: 1000) - 12.04) < 0.3, "gain at cutoff equals Q")413 }414415 @Test func highpassIsTwelveDecibelsPerOctave() {416 #expect(abs(gain(.highpass, cutoff: 2000, q: 0.7071, at: 2000) + 3.01) < 0.3)417 #expect(abs(gain(.highpass, cutoff: 2000, q: 0.7071, at: 20000)) < 0.2)418 #expect(abs(gain(.highpass, cutoff: 2000, q: 0.7071, at: 200) + 40) < 1.5)419 #expect(abs(gain(.highpass, cutoff: 2000, q: 0.7071, at: 1000) - gain(.highpass, cutoff: 2000, q: 0.7071, at: 500) - 12) < 1.5)420 #expect(abs(gain(.highpass, cutoff: 1000, q: 4, at: 1000) - 12.04) < 0.3)421 }422423 @Test func bandpassMatchesTheAnalogueResponse() {424 let q: Float = 1.2425 func ideal(_ ratio: Float) -> Float { db(1 / sqrtf(1 + q * q * (ratio - 1 / ratio) * (ratio - 1 / ratio))) }426 #expect(abs(gain(.bandpass, cutoff: 500, q: q, at: 500)) < 0.2)427 #expect(abs(gain(.bandpass, cutoff: 500, q: q, at: 50) - ideal(0.1)) < 1)428 #expect(abs(gain(.bandpass, cutoff: 500, q: q, at: 5000) - ideal(10)) < 1.5)429 #expect(gain(.bandpass, cutoff: 500, q: 10, at: 1000) < gain(.bandpass, cutoff: 500, q: q, at: 1000) - 10, "higher Q is narrower")430 }431432 @Test func cutoffSweepIsSmooth() {433 // A full-range jump of the cutoff on a steady tone must not produce a step.434 let rig = Rig(.lowpass); rig.set("cutoff", 20000)435 let tone = sine(300, amplitude: 0.5, seconds: 1)436 let a = rig.run(Array(tone[..<24000])).l437 rig.set("cutoff", 20)438 let b = rig.run(Array(tone[24000...])).l439 #expect(maxDelta((a.suffix(1) + b)[...]) <= maxDelta(a[12000...]) * 1.5)440 #expect(rms(b.suffix(4800)) < 0.01)441 }442}443444@Suite struct RhythmEffectTests {445 @Test(arguments: [(120.0, Float(0.25), 0.0), (128.0, Float(0.5), 0.37), (90.0, Float(1), 10.2)])446 func tremoloFollowsTheGrid(bpm: Double, rate: Float, startBeat: Double) {447 let rig = Rig(.tremolo, bpm: bpm, beat: startBeat)448 rig.set("rate", rate); rig.set("depth", 0.8); rig.set("shape", 0)449 let out = rig.run(constant(1, 2)).l450 let period = Double(rate) * 60 / bpm * testRate451 var worst: Float = 0452 for i in stride(from: 2000, to: out.count, by: 7) {453 let beat = startBeat + Double(i) * bpm / 60 / testRate454 let phase = (beat / Double(rate)).truncatingRemainder(dividingBy: 1)455 let expected = 1 - 0.8 * (0.5 - 0.5 * Float(cos(2 * Double.pi * phase)))456 worst = max(worst, abs(out[i] - expected))457 }458 #expect(worst < 0.03, "deviation from the beat-locked LFO: \(worst)")459 // Period measured from the minima (gain 0.2 half-way through each cycle).460 let minima = (2000 ..< out.count - 1).filter { out[$0] < out[$0 - 1] && out[$0] <= out[$0 + 1] && out[$0] < 0.25 }461 #expect(minima.count >= 2)462 let measured = Double(minima.last! - minima.first!) / Double(minima.count - 1)463 #expect(abs(measured - period) < 2, "period \(measured) vs \(period) samples")464 }465466 @Test func tremoloPhaseJumpsWithTheTransport() {467 // After a seek, the LFO takes the phase of the new beat position (within the 1 ms de-click ramp).468 let rig = Rig(.tremolo, bpm: 120, beat: 0)469 rig.set("rate", 1); rig.set("depth", 1)470 _ = rig.run(constant(1, 0.3))471 rig.beat = 8.5 // half-way through a cycle: gain 0472 let out = rig.run(constant(1, 0.05)).l473 #expect(out[480] < 0.02)474 rig.beat = 16 // on the beat: gain 1475 #expect(rig.run(constant(1, 0.05)).l[480] > 0.98)476 }477478 @Test func tremoloSquareShape() {479 let rig = Rig(.tremolo, bpm: 120); rig.set("rate", 1); rig.set("depth", 1); rig.set("shape", 1)480 let out = rig.run(constant(1, 2)).l[24000...] // one cycle = 24000 samples, open around the beat481 let high = out.filter { $0 > 0.99 }.count, low = out.filter { $0 < 0.01 }.count482 #expect(Double(high + low) / Double(out.count) > 0.97, "square: almost always fully open or closed")483 #expect(abs(Double(high) / Double(out.count) - 0.5) < 0.02)484 }485486 @Test(arguments: [(120.0, Float(0.25), Float(0.5), 0.0), (140.0, Float(0.5), Float(0.25), 3.3), (100.0, Float(1), Float(0.8), 0.0)])487 func gateFollowsTheGrid(bpm: Double, rate: Float, duty: Float, startBeat: Double) {488 let rig = Rig(.gate, bpm: bpm, beat: startBeat)489 rig.set("rate", rate); rig.set("duty", duty); rig.set("depth", 1)490 let out = rig.run(constant(1, 2)).l491 var wrong = 0, checked = 0492 for i in 1000 ..< out.count {493 let phase = ((startBeat + Double(i) * bpm / 60 / testRate) / Double(rate)).truncatingRemainder(dividingBy: 1)494 let fromEdge = min(phase, abs(phase - Double(duty)), 1 - phase) * Double(rate) * 60 / bpm // seconds to the nearest edge495 if fromEdge < 0.008 { continue } // inside the de-click ramp496 checked += 1497 if abs(out[i] - (phase < Double(duty) ? 1 : 0)) > 0.01 { wrong += 1 }498 }499 #expect(wrong == 0 && checked > 40000)500 let opens = (1000 ..< out.count).filter { out[$0 - 1] < 0.5 && out[$0] >= 0.5 }501 let period = Double(rate) * 60 / bpm * testRate502 #expect(abs(Double(opens.last! - opens.first!) / Double(opens.count - 1) - period) < 1.5)503 let openShare = Double(out[opens.first! ..< opens.last!].filter { $0 >= 0.5 }.count) / Double(opens.last! - opens.first!)504 #expect(abs(openShare - Double(duty)) < 0.02)505 // Depth 0.5 leaves half the level while closed.506 let half = Rig(.gate, bpm: bpm); half.set("depth", 0.5)507 #expect(abs(half.run(constant(1, 1)).l.min()! - 0.5) < 0.01)508 }509510 @Test func autopanFollowsTheGrid() {511 let rig = Rig(.autopan, bpm: 120); rig.set("rate", 1); rig.set("depth", 1)512 let out = rig.run(constant(1, 2)), cycle = 24000513 // Quarter cycle: fully right; three quarters: fully left; on the beat: centred.514 #expect(out.l[cycle + cycle / 4] < 0.02 && out.r[cycle + cycle / 4] > 0.98)515 #expect(out.r[cycle + 3 * cycle / 4] < 0.02 && out.l[cycle + 3 * cycle / 4] > 0.98)516 #expect(out.l[2 * cycle] > 0.97 && out.r[2 * cycle] > 0.97)517 #expect(zip(out.l, out.r).allSatisfy { $0 <= 1.0001 && $1 <= 1.0001 && max($0, $1) > 0.98 }, "no boost, one side always at unity")518 for i in stride(from: cycle, to: 2 * cycle, by: 97) { #expect(abs(out.l[i] - out.l[i + cycle]) < 1e-3) }519 }520521 @Test(arguments: [(120.0, Float(0.25)), (128.0, Float(1)), (174.0, Float(0.0625)), (60.0, Float(4))])522 func beatRepeatLoopsTheLastSlice(bpm: Double, beats: Float) {523 let rig = Rig(.beatrepeat, bpm: bpm, enabled: false)524 rig.set("length", beats)525 let slice = Int((Double(beats) * 60 / bpm * testRate).rounded())526 let before = testSignal(seconds: 4.6, seed: 11)527 #expect(rig.run(before).l == before, "bypassed while capturing")528 rig.fx.setEnabled(true)529 let cycles = max(3, 30000 / slice + 2)530 let out = rig.run(testSignal(seconds: Double(slice * cycles + 2000) / testRate, seed: 12)).l531 // Exactly periodic once the enable fade (576 samples) is over.532 var worst: Float = 0533 for i in 600 ..< (out.count - slice) { worst = max(worst, abs(out[i] - out[i + slice])) }534 #expect(worst < 1e-6, "not periodic: \(worst)")535 // The loop content is the last `slice` samples heard before enabling (outside the seam crossfade).536 let source = before.suffix(slice), fade = min(240, slice / 4)537 var mismatch: Float = 0538 for k in 0 ..< (slice - fade) { mismatch = max(mismatch, abs(out[slice + k] - source[source.startIndex + k])) }539 #expect(mismatch < 1e-6, "loop is not the captured slice: \(mismatch)")540 // The seam is crossfaded: no step larger than the material itself contains.541 #expect(maxDelta(out[slice ..< 3 * slice]) <= maxDelta(before[...]) * 1.05)542 // The incoming audio does not leak into the loop.543 #expect(rms(out[600...]) > 0.05)544 }545546 @Test func beatRepeatSeamIsCrossfadedOnATone() {547 // 100 Hz tone, slice of 6000 samples = 12.5 periods: an unfaded loop would jump by a full swing at the seam.548 let rig = Rig(.beatrepeat, bpm: 120, enabled: false); rig.set("length", 0.25)549 let tone = sine(100, amplitude: 0.5, seconds: 1.013)550 _ = rig.run(tone)551 rig.fx.setEnabled(true)552 let out = rig.run(silence(1)).l553 #expect(maxDelta(out[1000...]) < 0.02)554 #expect(peak(out[1000...]) > 0.45)555 }556557 @Test func beatRepeatRefreezesOnEveryEnable() {558 let rig = Rig(.beatrepeat, bpm: 120, enabled: false); rig.set("length", 0.25)559 _ = rig.run(constant(0.25, 1))560 rig.fx.setEnabled(true); let first = rig.run(constant(-0.5, 0.5)).l561 #expect(abs(first.last! - 0.25) < 1e-6)562 rig.fx.setEnabled(false); _ = rig.run(constant(-0.5, 0.5))563 rig.fx.setEnabled(true); let second = rig.run(constant(0.1, 0.5)).l564 #expect(abs(second.last! + 0.5) < 1e-6, "second freeze holds the audio played in between")565 }566}567568@Suite struct DynamicsEffectTests {569 @Test(arguments: [(Float(-18), Float(4), Float(0)), (Float(-30), Float(2), Float(-6)), (Float(-12), Float(20), Float(0)), (Float(-24), Float(8), Float(-3)), (Float(-10), Float(4), Float(-20))])570 func compressorStaticCurve(threshold: Float, ratio: Float, inputDB: Float) {571 let rig = Rig(.compressor); rig.set("threshold", threshold); rig.set("ratio", ratio)572 let a = powf(10, inputDB / 20)573 let out = rig.run(sine(1000, amplitude: a, seconds: 2)).l574 let measured = db(peak(out[72000...])) - inputDB575 let expected = inputDB > threshold ? (inputDB - threshold) * (1 / ratio - 1) : 0576 #expect(abs(measured - expected) < 1, "gain \(measured) dB, expected \(expected) dB")577 }578579 @Test func compressorMakeupAndTiming() {580 let rig = Rig(.compressor); rig.set("threshold", 0); rig.set("makeup", 12)581 let out = rig.run(sine(1000, amplitude: 0.1, seconds: 1)).l582 #expect(abs(db(peak(out[24000...])) - (-20 + 12)) < 0.5)583 // Attack: a burst above threshold is reduced progressively; a slower attack lets more through at first.584 func early(_ attack: Float) -> Float {585 let r = Rig(.compressor); r.set("threshold", -30); r.set("ratio", 10); r.set("attack", attack)586 r.runSilence(seconds: 0.1)587 return peak(r.run(sine(1000, amplitude: 1, seconds: 0.5)).l[480 ..< 960])588 }589 #expect(early(100) > early(1) * 2)590 // Release: after the burst the gain recovers.591 let r = Rig(.compressor); r.set("threshold", -30); r.set("ratio", 10); r.set("release", 50)592 _ = r.run(sine(1000, amplitude: 1, seconds: 0.5))593 let quiet = r.run(sine(1000, amplitude: 0.01, seconds: 1)).l594 #expect(peak(quiet[0 ..< 480]) < 0.006)595 #expect(abs(peak(quiet[40000...]) - 0.01) < 0.0005)596 }597598 @Test(arguments: [Float(-1), -6, -24, 0]) func limiterNeverExceedsTheCeiling(ceiling: Float) {599 let rig = Rig(.limiter); rig.set("ceiling", ceiling)600 // +12 dB programme: tone, noise and isolated full-scale-times-four spikes.601 var input = zip(sine(220, amplitude: 2.5, seconds: 3), whiteNoise(amplitude: 1.5, seconds: 3)).map { $0 + $1 }602 for i in stride(from: 5000, to: input.count, by: 9973) { input[i] = i % 2 == 0 ? 4 : -4 }603 let out = rig.run(input)604 let limit = powf(10, (ceiling + 0.1) / 20)605 // The first 12 ms are the enable crossfade from the (unlimited) dry signal: that is the base mixer, not the limiter.606 #expect(peak(out.l[600...]) <= limit && peak(out.r[600...]) <= limit)607 #expect(peak(out.l[48000...]) > powf(10, (ceiling - 3) / 20), "the limiter should not over-reduce")608 }609610 @Test func limiterIsCleanGainReductionWithFiveMillisecondsOfLatency() {611 // Steady +12 dB sine: the gain settles to a constant, so the output is a pure sine at the ceiling (no clipping).612 let rig = Rig(.limiter); rig.set("ceiling", -1)613 let out = rig.run(sine(1000, amplitude: 4, seconds: 1)).l[24000...]614 let c = powf(10, -1.0 / 20), fundamental = amplitude(out, at: 1000)615 #expect(abs(db(fundamental) - db(c)) < 0.1)616 #expect(amplitude(out, at: 3000) < fundamental * 0.003, "third harmonic means the safety clamp is clipping")617 // Below the ceiling the unit is a pure 240-sample delay.618 let quiet = Rig(.limiter); let input = testSignal(seconds: 0.5)619 let delayed = quiet.run(input).l620 var worst: Float = 0621 for i in 1000 ..< 24000 { worst = max(worst, abs(delayed[i] - input[i - 240])) }622 #expect(worst < 1e-5)623 // A single spike is anticipated: the gain is already down when it leaves the delay line, then recovers.624 let spike = Rig(.limiter); spike.set("ceiling", -6); spike.set("release", 50)625 var s = constant(0.25, 1); s[24000] = 4626 let o = spike.run(s).l627 #expect(o[24000 + 240] <= 0.5012 && o[24000 + 240] > 0.49)628 #expect(o[24000 + 120] < 0.2 && o[24000 + 120] > 0.03, "gain ramps down ahead of the spike")629 #expect(abs(o[47000] - 0.25) < 0.001, "gain recovered")630 }631}632633@Suite struct NoiseEffectTests {634 @Test(arguments: [Float(300), 1000, 5000]) func noiseIsAddedAroundTheCutoff(cutoff: Float) {635 let rig = Rig(.noise); rig.set("cutoff", cutoff); rig.set("resonance", 10); rig.set("level", 0)636 let input = sine(60, amplitude: 0.25, seconds: 2)637 let out = rig.run(input)638 let added = zip(out.l, input).map { $0 - $1 }.suffix(48000).map { $0 }639 #expect(rms(added) > 0.02, "noise present")640 let at = bandEnergy(added, centre: cutoff)641 #expect(at > 8 * bandEnergy(added, centre: cutoff / 5))642 #expect(at > 8 * bandEnergy(added, centre: min(cutoff * 5, 20000)))643 #expect(at > 0.5 * energy(added) * 0.5, "most of the noise energy sits in the band")644 #expect(out.l != out.r, "stereo noise")645 // The input itself is untouched: removing the noise leaves the tone.646 #expect(abs(amplitude(out.l[48000...], at: 60) - 0.25) < 0.01)647 }648649 @Test func noiseLevel() {650 func level(_ dbValue: Float) -> Float {651 let rig = Rig(.noise); rig.set("level", dbValue)652 return rms(rig.run(silence(1)).l[24000...])653 }654 #expect(level(-60) < 1e-6, "-60 dB is the silence floor")655 #expect(abs(db(level(-6)) - db(level(-26)) - 20) < 0.5)656 #expect(level(0) < 1)657 }658}659