Files
Lyrebird/Sources/LyrebirdUI/LyrebirdSpectrumView.swift
T
2026-06-01 18:27:40 -07:00

233 lines
8.7 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdSpectrumView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
/// A real-time spectrum analyzer / spectrogram view.
///
/// Polls `SpectrumCapture` at ~30 Hz and renders magnitude data using `Canvas`.
///
/// **Spectrum mode** (`waterfallRows == 0`, default):
/// Draws the current magnitude frame as a line plot. The X axis uses a logarithmic
/// frequency scale from `minHz` to `maxHz`. The Y axis shows magnitude in dB from
/// `floorDB` to `ceilDB`, with high-magnitude (loud) signals drawn near the top.
///
/// **Waterfall mode** (`waterfallRows > 0`):
/// Displays a scrolling spectrogram. Each row is one captured frame; new frames appear
/// at the top and older frames scroll down. Frequency is on the X axis (log scale);
/// time scrolls on the Y axis. Magnitude is encoded as color brightness on a
/// black-to-green gradient.
///
/// ```swift
/// // Spectrum only
/// LyrebirdSpectrumView(capture: specCapture, sampleRate: 44100)
/// .frame(height: 120)
///
/// // Waterfall spectrogram (80 history rows)
/// LyrebirdSpectrumView(capture: specCapture, sampleRate: 44100, waterfallRows: 80)
/// .frame(height: 200)
/// ```
public struct LyrebirdSpectrumView: View {
// MARK: - Configuration
/// The spectrum capture object to poll.
public let capture: SpectrumCapture
/// Audio sample rate in Hz, used to map bin indices to frequencies.
public let sampleRate: Double
/// Minimum displayed frequency in Hz. Default: 20 Hz.
public let minHz: Double
/// Maximum displayed frequency in Hz. Default: 20 000 Hz.
public let maxHz: Double
/// Lower dB bound for the magnitude axis. Default: −80 dB.
public let floorDB: Double
/// Upper dB bound for the magnitude axis. Default: 0 dB.
public let ceilDB: Double
/// Number of history rows shown in waterfall mode.
/// `0` (default) selects spectrum-line mode; any positive value selects waterfall mode.
public let waterfallRows: Int
// MARK: - State
@State private var magnitudes: [Float] = []
@State private var history: [[Float]] = []
// MARK: - Constants
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
private static let backgroundColor: Color = Color(white: 0.08)
private static let spectrumColor: Color = Color.green
private static let spectrumLineWidth: CGFloat = 1.0
private static let zeroLineOpacity: Double = 0.2
/// Prevent log(0) in dB conversion.
private static let magnitudeFloor: Double = 1e-10
private static let waterfallHue: Double = 0.33 // green
private static let waterfallSaturationBoost: Double = 1.5
// MARK: - Init
/// - Parameters:
/// - capture: The `SpectrumCapture` registered as a processor on a `SpectralChain.Audio`.
/// - sampleRate: Audio sample rate in Hz. Used to compute bin-to-frequency mapping.
/// - minHz: Minimum frequency displayed on the X axis. Default: 20 Hz.
/// - maxHz: Maximum frequency displayed on the X axis. Default: 20 000 Hz.
/// - floorDB: Minimum dB level displayed on the Y axis. Default: −80 dB.
/// - ceilDB: Maximum dB level displayed on the Y axis. Default: 0 dB.
/// - waterfallRows: Number of waterfall history rows. `0` = spectrum line, `> 0` = waterfall spectrogram.
public init(
capture: SpectrumCapture,
sampleRate: Double,
minHz: Double = 20,
maxHz: Double = 20_000,
floorDB: Double = -80,
ceilDB: Double = 0,
waterfallRows: Int = 0
) {
precondition(sampleRate > 0,
"LyrebirdSpectrumView: sampleRate must be > 0, got \(sampleRate)")
precondition(minHz > 0 && minHz < maxHz,
"LyrebirdSpectrumView: minHz must be > 0 and < maxHz")
precondition(floorDB < ceilDB,
"LyrebirdSpectrumView: floorDB must be < ceilDB")
self.capture = capture
self.sampleRate = sampleRate
self.minHz = minHz
self.maxHz = maxHz
self.floorDB = floorDB
self.ceilDB = ceilDB
self.waterfallRows = max(0, waterfallRows)
}
// MARK: - Body
public var body: some View {
Canvas { ctx, size in
ctx.fill(
Path(CGRect(origin: .zero, size: size)),
with: .color(Self.backgroundColor)
)
guard magnitudes.count > 1 else { return }
if waterfallRows > 0 {
_drawWaterfall(ctx: ctx, size: size)
} else {
_drawSpectrum(ctx: ctx, size: size)
}
}
.background(Self.backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 4))
.task {
while !Task.isCancelled {
let snap: [Float] = capture.snapshot()
magnitudes = snap
if waterfallRows > 0 {
var h: [[Float]] = history
h.insert(snap, at: 0)
if h.count > waterfallRows { h.removeLast() }
history = h
}
try? await Task.sleep(nanoseconds: Self.pollIntervalNs)
}
}
}
// MARK: - Spectrum line
private func _drawSpectrum(ctx: GraphicsContext, size: CGSize) {
// Zero-dB guide line
let zeroY: Double = size.height * (1.0 - _dbFrac(Float(1.0)))
var guide: Path = Path()
guide.move(to: CGPoint(x: 0, y: zeroY))
guide.addLine(to: CGPoint(x: size.width, y: zeroY))
ctx.stroke(guide,
with: .color(.white.opacity(Self.zeroLineOpacity)),
lineWidth: 0.5)
let halfSize: Int = capture.fftSize / 2
var path: Path = Path()
var started: Bool = false
for k: Int in 0...halfSize {
guard k < magnitudes.count else { break }
let xFrac: Double = _xFrac(bin: k)
guard xFrac >= 0 && xFrac <= 1 else { continue }
let x: Double = xFrac * size.width
let y: CGFloat = size.height * (1.0 - _dbFrac(magnitudes[k]))
let pt: CGPoint = CGPoint(x: x, y: y)
if !started {
path.move(to: pt)
started = true
} else {
path.addLine(to: pt)
}
}
ctx.stroke(path, with: .color(Self.spectrumColor), lineWidth: Self.spectrumLineWidth)
}
// MARK: - Waterfall
private func _drawWaterfall(ctx: GraphicsContext, size: CGSize) {
guard !history.isEmpty else { return }
let rowH: CGFloat = size.height / CGFloat(waterfallRows)
let halfSize: Int = capture.fftSize / 2
// Number of horizontal pixel columns to iterate over.
let cols: Int = max(1, Int(size.width))
for (rowIdx, rowMags) in history.enumerated() {
guard rowIdx < waterfallRows else { break }
let y: CGFloat = CGFloat(rowIdx) * rowH
var prevX: CGFloat = 0
for col: Int in 0..<cols {
let xFrac: Double = Double(col) / Double(cols)
// Invert log scale: freq = minHz × (maxHz/minHz)^xFrac
let freq: Double = minHz * pow(maxHz / minHz, xFrac)
let bin: Int = min(halfSize, Int(freq * Double(capture.fftSize) / sampleRate))
guard bin >= 0 && bin < rowMags.count else { continue }
let x: CGFloat = CGFloat(col)
let dbFrac: Double = _dbFrac(rowMags[bin])
if x > prevX {
let brightness: CGFloat = CGFloat(dbFrac)
let color: Color = Color(
hue: Self.waterfallHue,
saturation: min(1.0, brightness * Self.waterfallSaturationBoost),
brightness: brightness
)
ctx.fill(
Path(CGRect(x: prevX, y: y, width: x - prevX, height: rowH)),
with: .color(color)
)
}
prevX = x
}
}
}
// MARK: - Coordinate helpers
/// Normalized X position [0, 1] for `bin` on a log-frequency axis.
/// Returns values outside [0, 1] for bins outside [minHz, maxHz].
private func _xFrac(bin: Int) -> Double {
let freq: Double = Double(bin) * sampleRate / Double(capture.fftSize)
guard freq > 0 else { return -1 }
return log(freq / minHz) / log(maxHz / minHz)
}
/// Normalized Y position [0, 1] for a linear magnitude value.
/// 0 = `floorDB`, 1 = `ceilDB`.
private func _dbFrac(_ mag: Float) -> Double {
let db: Double = 20.0 * log10(max(Self.magnitudeFloor, Double(mag)))
return max(0, min(1, (db - floorDB) / (ceilDB - floorDB)))
}
}