Files
Lyrebird/Sources/LyrebirdUI/LyrebirdSpectrumView.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

499 lines
19 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
#if canImport(SwiftUI)
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)))
}
}
#else
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdSpectrumView`: a real-time
// spectrum / waterfall analyzer. The SwiftUI `GraphicsContext`/`Path` drawing is
// rewritten to imperative `DrawingContext` (Cairo) calls. Polling moves off
// SwiftOpenUI's `.task` (which runs OFF the main thread) onto a Foundation
// `Timer` on `RunLoop.main` inside an `@Observable` model — the same pattern as
// `LyrebirdStatusView` / `LyrebirdScopeModel`.
//
// No axis/frequency text is drawn (`DrawingContext` has no text primitive) — the
// Apple side draws none either, so there is no feature loss.
//
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
import SwiftOpenUI
import BackendGTK4
import LyrebirdSynth
import Observation
import Foundation
/// Poll interval for the spectrum model (~30 Hz).
private let linuxSpectrumPollIntervalSeconds: TimeInterval = 1.0 / 30.0
/// Polls a `SpectrumCapture` on a main-thread timer and publishes the current
/// magnitude frame (plus a bounded history for waterfall mode) for
/// ``LyrebirdSpectrumView`` to draw. Internal — only the view is public.
///
/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on
/// `RunLoop.main`), but `Timer`'s block is `@Sendable`, so the capture requires
/// the conformance — same rationale as `LyrebirdScopeModel`.
@Observable
final class LinuxSpectrumModel: @unchecked Sendable {
var magnitudes: [Float] = []
var history: [[Float]] = []
@ObservationIgnored private var timer: Timer?
@ObservationIgnored private let capture: SpectrumCapture
@ObservationIgnored private let waterfallRows: Int
init(capture: SpectrumCapture, waterfallRows: Int) {
self.capture = capture
self.waterfallRows = waterfallRows
}
deinit {
timer?.invalidate()
}
func start() {
guard timer == nil else { return }
let t: Timer = Timer.scheduledTimer(
withTimeInterval: linuxSpectrumPollIntervalSeconds,
repeats: true
) { [weak self] _ in
guard let self else { return }
let snap: [Float] = self.capture.snapshot()
self.magnitudes = snap
if self.waterfallRows > 0 {
var h: [[Float]] = self.history
h.insert(snap, at: 0)
if h.count > self.waterfallRows { h.removeLast() }
self.history = h
}
}
timer = t
}
func stop() {
timer?.invalidate()
timer = nil
}
}
/// A real-time spectrum analyzer / waterfall for the Linux/GTK4 UI. Mirrors
/// `LyrebirdUI.LyrebirdSpectrumView`; same public API/init as the Apple side.
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 model: LinuxSpectrumModel
// MARK: - Constants
private static let backgroundRGB: (r: Double, g: Double, b: Double) = (0.08, 0.08, 0.08)
private static let spectrumRGB: (r: Double, g: Double, b: Double) = (0.0, 0.667, 0.0) // green
private static let spectrumLineWidth: Double = 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
let rows: Int = max(0, waterfallRows)
self.waterfallRows = rows
_model = State(wrappedValue: LinuxSpectrumModel(capture: capture, waterfallRows: rows))
}
// MARK: - Body
public var body: some View {
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
let w: Double = Double(size.width)
let h: Double = Double(size.height)
let bg: (r: Double, g: Double, b: Double) = Self.backgroundRGB
ctx.setColor(r: bg.r, g: bg.g, b: bg.b)
ctx.rectangle(x: 0, y: 0, width: w, height: h)
ctx.fill()
guard model.magnitudes.count > 1 else { return }
if waterfallRows > 0 {
_drawWaterfall(ctx: ctx, width: w, height: h)
} else {
_drawSpectrum(ctx: ctx, width: w, height: h)
}
})
.onAppear { model.start() }
.onDisappear { model.stop() }
}
// MARK: - Spectrum line
private func _drawSpectrum(ctx: DrawingContext, width: Double, height: Double) {
let mags: [Float] = model.magnitudes
// Zero-dB guide line.
let zeroY: Double = height * (1.0 - _dbFrac(Float(1.0)))
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: Self.zeroLineOpacity)
ctx.setLineWidth(0.5)
ctx.moveTo(x: 0, y: zeroY)
ctx.lineTo(x: width, y: zeroY)
ctx.stroke()
let halfSize: Int = capture.fftSize / 2
let line: (r: Double, g: Double, b: Double) = Self.spectrumRGB
ctx.setColor(r: line.r, g: line.g, b: line.b)
ctx.setLineWidth(Self.spectrumLineWidth)
var started: Bool = false
for k: Int in 0...halfSize {
guard k < mags.count else { break }
let xFrac: Double = _xFrac(bin: k)
guard xFrac >= 0 && xFrac <= 1 else { continue }
let x: Double = xFrac * width
let y: Double = height * (1.0 - _dbFrac(mags[k]))
if !started {
ctx.moveTo(x: x, y: y)
started = true
} else {
ctx.lineTo(x: x, y: y)
}
}
ctx.stroke()
}
// MARK: - Waterfall
private func _drawWaterfall(ctx: DrawingContext, width: Double, height: Double) {
let hist: [[Float]] = model.history
guard !hist.isEmpty else { return }
let rowH: Double = height / Double(waterfallRows)
let halfSize: Int = capture.fftSize / 2
// Number of horizontal pixel columns to iterate over.
let cols: Int = max(1, Int(width))
for (rowIdx, rowMags) in hist.enumerated() {
guard rowIdx < waterfallRows else { break }
let y: Double = Double(rowIdx) * rowH
var prevX: Double = 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: Double = Double(col)
let dbFrac: Double = _dbFrac(rowMags[bin])
if x > prevX {
let brightness: Double = dbFrac
let color: Color = Color(
hue: Self.waterfallHue,
saturation: min(1.0, brightness * Self.waterfallSaturationBoost),
brightness: brightness
)
ctx.setColor(r: color.red, g: color.green, b: color.blue)
ctx.rectangle(x: prevX, y: y, width: x - prevX, height: rowH)
ctx.fill()
}
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)))
}
}
#endif