fix(output,gate): unity mono output + RMS noise-gate detector
Two fixes from the guitar-input analysis: - Mono board output no longer loses 3 dB. BoardOutputMaster panned a mono board to stereo centre with an equal-power Pan2 (×0.707 per channel). A mono rig should come out at the level it went in, so the signal is now written to both hardware buses directly at unity. - Noise Gate gains a Peak/RMS detector switch (defaults to RMS). The peak follower (|x|) rides the waveform's peaks, so the gate's threshold decision tracked instantaneous peaks rather than loudness; the RMS detector (√ symmetric-average of x²) follows perceived level, so the gate opens and closes where the note actually is. Implemented as a rebuildsOnChange switch that builds only the chosen follower. Serialization-safe: a gate saved before the switch (empty switchValues) loads with the RMS default. Tests cover the detector switch, RMS default (incl. legacy load), state round-trip, and RMS closing earlier than Peak on a sustained tail. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -82,9 +82,6 @@ final class BoardOutputMaster: SynthesizerBase {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board.
|
||||
private let stereoPan: Double = 0.0
|
||||
|
||||
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
|
||||
/// transitions to prevent clicks. Matches the per-pedal bypass lag.
|
||||
private let bypassLagTime: Double = 0.02
|
||||
@@ -137,8 +134,12 @@ final class BoardOutputMaster: SynthesizerBase {
|
||||
output(bus: 0, source: gainedLeft)
|
||||
output(bus: 1, source: gainedRight)
|
||||
} else {
|
||||
// Mono board: Pan2 spreads the mono output to stereo hardware buses 0 + 1.
|
||||
output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan))
|
||||
// Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an
|
||||
// equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct
|
||||
// for a true pan, but a mono guitar rig should come out at the same level it went in, so
|
||||
// the signal is copied to left and right directly instead.
|
||||
output(bus: 0, source: gainedLeft)
|
||||
output(bus: 1, source: gainedLeft)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,13 @@ import LyrebirdUI
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry ─┬─────────────────────────────────────────────────────────┐
|
||||
/// └→ AmplitudeFollower → Schmidt(lo: thr, hi: thr×ratio) │
|
||||
/// → LinLin(0…1 → floor…1) │
|
||||
/// → LagUpDown(fast open/slow close) × ─┴→ mono out
|
||||
/// dry ─┬───────────────────────────────────────────────────────────┐
|
||||
/// └→ detector → Schmidt(lo: thr, hi: thr×ratio) │
|
||||
/// (Peak: AmplitudeFollower |x|, → LinLin(0…1 → floor…1) │
|
||||
/// RMS: √Lag(x²)) → LagUpDown(fast/slow) × ─┴→ mono out
|
||||
/// ```
|
||||
///
|
||||
/// An `AmplitudeFollower` tracks the dry signal level. A Schmitt trigger turns that
|
||||
/// The **detector** tracks the dry signal level — either peak (`|x|`) or RMS (√mean-square). A Schmitt trigger turns that
|
||||
/// envelope into an open/closed gate with hysteresis (opens above `threshold × openRatio`,
|
||||
/// closes below `threshold`) so the gate does not chatter around the threshold. The 0/1
|
||||
/// gate is mapped to a gain in `[floor, 1]` and smoothed **asymmetrically** — opening fast so a
|
||||
@@ -63,17 +63,33 @@ public final class NoiseGatePedal: Pedal {
|
||||
/// out chatter at the threshold). Range `[0.01, 0.5]`. Surfaced in the advanced pop-over.
|
||||
@UIParam public var release: Double = 0.08
|
||||
|
||||
/// Detector mode: `0` = **Peak** (tracks `|x|`), `1` = **RMS** (tracks √mean-square). RMS follows
|
||||
/// perceived loudness, so the threshold decision — and the level at which the gate closes — lines
|
||||
/// up with how loud the note actually is, instead of riding the waveform's peaks. Defaults to RMS.
|
||||
@UIParam public var detector: Double = 1.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the gate sits in-line.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// `detector` value selecting the peak follower.
|
||||
private let detectorPeakValue: Double = 0.0
|
||||
|
||||
/// `detector` value selecting the RMS follower.
|
||||
private let detectorRMSValue: Double = 1.0
|
||||
|
||||
/// Envelope-follower attack time, in seconds — fast so the gate opens promptly on a note.
|
||||
private let detectAttack: Double = 0.002
|
||||
|
||||
/// Envelope-follower release time, in seconds — slower so the gate holds through decay.
|
||||
private let detectRelease: Double = 0.05
|
||||
|
||||
/// RMS integration window (one-pole averaging time, in seconds) for the RMS detector. Long enough
|
||||
/// to average out the waveform's per-cycle ripple so the envelope reflects mean-square level, not
|
||||
/// instantaneous peaks.
|
||||
private let rmsWindow: Double = 0.02
|
||||
|
||||
/// Open-threshold multiplier. The gate opens above `threshold × openRatio` and closes
|
||||
/// below `threshold`, giving hysteresis that prevents chatter near the threshold.
|
||||
private let openRatio: Double = 2.0
|
||||
@@ -122,6 +138,23 @@ public final class NoiseGatePedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
/// Detector-mode switch (Peak / RMS). Appended as the gate's only switch, so a gate saved before
|
||||
/// it existed (empty `switchValues`) loads with the RMS default — no migration.
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Detector",
|
||||
node: $detector,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Peak", value: detectorPeakValue),
|
||||
PedalSwitch.Option(title: "RMS", value: detectorRMSValue),
|
||||
],
|
||||
// Switching detector changes which follower is instantiated, so rebuild the board.
|
||||
rebuildsOnChange: true
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a noise-gate pedal.
|
||||
@@ -150,12 +183,26 @@ public final class NoiseGatePedal: Pedal {
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Gated mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Track the dry signal's amplitude envelope.
|
||||
let envelope: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: dry,
|
||||
attackTime: detectAttack,
|
||||
releaseTime: detectRelease
|
||||
)
|
||||
// Build the chosen detector only. `detector` is a `rebuildsOnChange` switch, so it is read
|
||||
// here as a plain value at build time (the board rebuilds when it is toggled) — no live
|
||||
// node-select in the graph.
|
||||
let envelope: any ValidGeneratorInput
|
||||
if detector >= detectorRMSValue {
|
||||
// RMS detector: √(symmetric one-pole average of x²). The averaging window must be
|
||||
// symmetric — a fast attack would track the *squared peaks* and collapse back to peak
|
||||
// detection — so a plain `Lag` over `rmsWindow` recovers the mean square, giving a
|
||||
// loudness-tracking envelope roughly 3 dB below the peak for a steady tone.
|
||||
let squared: any ValidGeneratorInput = dry * dry
|
||||
let meanSquare: Lag.Audio = Lag.Audio(input: squared, time: rmsWindow)
|
||||
envelope = Sqrt.Audio(meanSquare)
|
||||
} else {
|
||||
// Peak detector: a one-pole follower of |x| (fast attack, slower release).
|
||||
envelope = AmplitudeFollower.Audio(
|
||||
in: dry,
|
||||
attackTime: detectAttack,
|
||||
releaseTime: detectRelease
|
||||
)
|
||||
}
|
||||
|
||||
// Hysteretic open/closed gate: opens above threshold×openRatio, closes below threshold.
|
||||
let gate: Schmidt.Audio = Schmidt.Audio(
|
||||
|
||||
@@ -170,4 +170,69 @@ struct NoiseGatePedalTests {
|
||||
#expect(pedal.threshold == 0.03 && pedal.floor == 0.4, "legacy Threshold/Floor mis-mapped")
|
||||
#expect(pedal.attack == 0.005 && pedal.release == 0.08, "legacy gate should default Attack/Release")
|
||||
}
|
||||
|
||||
@Test func exposesDetectorSwitch() throws {
|
||||
let switches: [PedalSwitch] = NoiseGatePedal().effectSwitches
|
||||
#expect(switches.map { $0.label } == ["Detector"])
|
||||
#expect(switches.first?.options.map { $0.title } == ["Peak", "RMS"])
|
||||
}
|
||||
|
||||
@Test func defaultsToRMSAndLegacyGateGetsRMS() throws {
|
||||
#expect(NoiseGatePedal().detector == 1.0, "new gate should default to RMS")
|
||||
// A gate saved before the detector switch (empty switchValues) loads with the RMS default.
|
||||
let legacy: PedalState = PedalState(
|
||||
id: UUID(), type: "Noise Gate",
|
||||
knobValues: [0.03, 0.4, 1.0, 1.0], switchValues: [], advancedValues: [], bypass: 0.0)
|
||||
let pedal: NoiseGatePedal = NoiseGatePedal()
|
||||
pedal.applyState(legacy)
|
||||
#expect(pedal.detector == 1.0, "legacy gate should default to the RMS detector")
|
||||
}
|
||||
|
||||
@Test func detectorRoundTripsThroughState() throws {
|
||||
let pedal: NoiseGatePedal = NoiseGatePedal()
|
||||
pedal.detector = 0.0 // Peak
|
||||
let restored: NoiseGatePedal = NoiseGatePedal()
|
||||
restored.applyState(pedal.captureState())
|
||||
#expect(restored.detector == 0.0)
|
||||
}
|
||||
|
||||
@Test func rmsDetectorClosesEarlierThanPeak() throws {
|
||||
// On a note held just above threshold, the RMS envelope (≈ 3 dB below the peak envelope for a
|
||||
// steady tone) drops under the close threshold sooner than the peak envelope does — so the
|
||||
// RMS gate shuts earlier and passes less of the sustained tail than the Peak gate. The source
|
||||
// steps to a constant 0.03 (peak env ≈ 0.03, RMS env ≈ 0.021); with threshold 0.025 the Peak
|
||||
// gate stays open on the tail while the RMS gate closes.
|
||||
func tailEnergy(detector: Double) throws -> Double {
|
||||
let sr: Double = 48000.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.6, sampleRate: sr)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
let source: DecaySineSource = DecaySineSource(bus: srcBus.index)
|
||||
let gate: NoiseGatePedal = NoiseGatePedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
gate.sampleRate = sr
|
||||
gate.threshold = 0.025
|
||||
gate.floor = 0.0
|
||||
gate.detector = detector
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(source)
|
||||
try engine.add(gate, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(gate))
|
||||
try engine.start()
|
||||
let inter: [Float] = readStereoCAF(url: url, sampleRate: sr)
|
||||
let mono: [Double] = stride(from: 0, to: inter.count, by: 2).map { Double(inter[$0]) }
|
||||
let start: Int = Int(0.15 * sr) // the sustained, below-peak-threshold tail
|
||||
var energy: Double = 0.0
|
||||
for i: Int in start..<mono.count { energy += mono[i] * mono[i] }
|
||||
return energy
|
||||
}
|
||||
let peakTail: Double = try tailEnergy(detector: 0.0)
|
||||
let rmsTail: Double = try tailEnergy(detector: 1.0)
|
||||
#expect(peakTail > rmsTail * 2.0,
|
||||
"RMS should close earlier than Peak on the sustained tail (peak=\(peakTail) rms=\(rmsTail))")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user