SPB Git

Repository Public License

SpectrumPlot.swift 10.8 KB 186 lines swift

1//2//  ORIX Audio3//  File: ORIXAudio/Features/Visuals/SpectrumPlot.swift4//  Description: Spectrum analyzer plot: calibrated dB grid, linear / log frequency axis, peak hold, band strip and a draggable frequency cursor.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import ORIXAudioCore10import SwiftUI1112struct SpectrumPlot: View {13    let frame: SpectrumFrame?14    let axis: FrequencyAxis15    var showPeakHold = true16    @State private var cursor: CGFloat?        // 0…1 across the plot1718    private var minFrequency: Double { axis == .logarithmic ? 20 : 0 }19    private var maxFrequency: Double { min(20_000, (frame?.sampleRate ?? 48_000) / 2) }20    /// Vertical range shown, per quantity. PSD values sit lower because they are per hertz.21    private var range: ClosedRange<Float> { frame?.scaling == .powerSpectralDensity ? -150...(-20) : -120...0 }2223    private static let logTicks: [Double] = [20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000]24    private static let linearTicks: [Double] = [0, 2000, 4000, 6000, 8000, 10_000, 12_000, 14_000, 16_000, 18_000, 20_000]2526    private func tickLabel(_ f: Double) -> String { f >= 1000 ? "\(Int(f / 1000))k" : "\(Int(f))" }2728    var body: some View {29        GeometryReader { geo in30            let plot = CGRect(x: 34, y: 8, width: max(1, geo.size.width - 42), height: max(1, geo.size.height - 30))31            ZStack(alignment: .topLeading) {32                Canvas { context, _ in33                    drawGrid(&context, plot: plot)34                    if let frame { drawSpectrum(&context, plot: plot, frame: frame) }35                    drawCursor(&context, plot: plot)36                }37                if let frame, let readout = cursorReadout(frame: frame) {38                    Text(readout).font(.orixReadout).foregroundStyle(.white)39                        .padding(.horizontal, 8).padding(.vertical, 4).background(.black.opacity(0.6), in: Capsule())40                        .padding(.leading, 40).padding(.top, 10)41                }42            }43            .contentShape(Rectangle())44            .gesture(DragGesture(minimumDistance: 0).onChanged { value in cursor = max(0, min(1, (value.location.x - plot.minX) / plot.width)) })45            .onTapGesture(count: 2) { cursor = nil }46        }47        .accessibilityElement(children: .ignore)48        .accessibilityLabel(Text("Spectrum analyzer"))49        .accessibilityValue(accessibilitySummary)50    }5152    private var accessibilitySummary: Text {53        guard let frame, let f = frame.dominantFrequency else { return Text("No signal") }54        return Text("Dominant frequency \(Int(f)) hertz at \(Int(frame.dominantLevel)) decibels full scale")55    }5657    private func x(_ f: Double, _ plot: CGRect) -> CGFloat { plot.minX + plot.width * CGFloat(axis.position(of: f, min: minFrequency, max: maxFrequency)) }58    private func y(_ dB: Float, _ plot: CGRect) -> CGFloat {59        plot.maxY - plot.height * CGFloat(max(0, min(1, (dB - range.lowerBound) / (range.upperBound - range.lowerBound))))60    }6162    private func drawGrid(_ context: inout GraphicsContext, plot: CGRect) {63        let step: Float = 2064        var level = range.upperBound65        while level >= range.lowerBound {66            let py = y(level, plot)67            context.stroke(Path { $0.move(to: CGPoint(x: plot.minX, y: py)); $0.addLine(to: CGPoint(x: plot.maxX, y: py)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: level == 0 ? 1 : 0.5)68            context.draw(Text("\(Int(level))").font(.system(size: 9, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText), at: CGPoint(x: plot.minX - 4, y: py), anchor: .trailing)69            level -= step70        }71        for f in (axis == .logarithmic ? Self.logTicks : Self.linearTicks) where f <= maxFrequency && f >= minFrequency {72            let px = x(f, plot)73            context.stroke(Path { $0.move(to: CGPoint(x: px, y: plot.minY)); $0.addLine(to: CGPoint(x: px, y: plot.maxY)) }, with: .color(ORIX.Palette.plotGrid), lineWidth: 0.5)74            context.draw(Text(tickLabel(f)).font(.system(size: 9, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText), at: CGPoint(x: px, y: plot.maxY + 9), anchor: .center)75        }76        // Band strip: the same seven bands used to colour the waveform.77        for (i, band) in FrequencyBandLayout.orix.bands.enumerated() {78            let a = x(max(band.lowerHz, minFrequency), plot), b = x(min(band.upperHz, maxFrequency), plot)79            if b > a { context.fill(Path(CGRect(x: a, y: plot.maxY + 17, width: b - a - 1, height: 3)), with: .color(ORIX.bandColors[i])) }80        }81        context.draw(Text(frame?.scaling.unit ?? "dBFS").font(.system(size: 9, weight: .semibold, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText),82                     at: CGPoint(x: plot.maxX - 2, y: plot.minY + 6), anchor: .trailing)83    }8485    private func drawSpectrum(_ context: inout GraphicsContext, plot: CGRect, frame: SpectrumFrame) {86        let columns = max(2, Int(plot.width))87        let values = axis.resample(frame.decibels, fftSize: frame.fftSize, sampleRate: frame.sampleRate, columns: columns, min: minFrequency, max: maxFrequency)88        guard values.count == columns else { return }89        var line = Path()90        for (i, v) in values.enumerated() {91            let p = CGPoint(x: plot.minX + CGFloat(i) + 0.5, y: y(v, plot))92            if i == 0 { line.move(to: p) } else { line.addLine(to: p) }93        }94        var fill = line95        fill.addLine(to: CGPoint(x: plot.maxX, y: plot.maxY)); fill.addLine(to: CGPoint(x: plot.minX, y: plot.maxY)); fill.closeSubpath()96        // Horizontal gradient: each x position takes the colour of the band it belongs to.97        var stops: [Gradient.Stop] = []98        for (i, band) in FrequencyBandLayout.orix.bands.enumerated() {99            let centre = (band.lowerHz * band.upperHz).squareRoot()100            stops.append(.init(color: ORIX.bandColors[i], location: CGFloat(max(0, min(1, axis.position(of: centre, min: minFrequency, max: maxFrequency))))))101        }102        stops.sort { $0.location < $1.location }103        let gradient = Gradient(stops: stops)104        context.drawLayer { layer in105            layer.clip(to: fill)106            layer.fill(Path(plot), with: .linearGradient(gradient, startPoint: CGPoint(x: plot.minX, y: 0), endPoint: CGPoint(x: plot.maxX, y: 0)))107            layer.fill(Path(plot), with: .linearGradient(Gradient(colors: [.clear, ORIX.Palette.plot.opacity(0.85)]), startPoint: CGPoint(x: 0, y: plot.minY), endPoint: CGPoint(x: 0, y: plot.maxY)))108        }109        context.stroke(line, with: .linearGradient(gradient, startPoint: CGPoint(x: plot.minX, y: 0), endPoint: CGPoint(x: plot.maxX, y: 0)), lineWidth: 1.5)110        if showPeakHold {111            let peaks = axis.resample(frame.peakHold, fftSize: frame.fftSize, sampleRate: frame.sampleRate, columns: columns, min: minFrequency, max: maxFrequency)112            var hold = Path()113            for (i, v) in peaks.enumerated() {114                let p = CGPoint(x: plot.minX + CGFloat(i) + 0.5, y: y(v, plot))115                if i == 0 { hold.move(to: p) } else { hold.addLine(to: p) }116            }117            context.stroke(hold, with: .color(.white.opacity(0.45)), lineWidth: 0.8)118        }119        if let f = frame.dominantFrequency, f >= minFrequency, f <= maxFrequency {120            let px = x(f, plot)121            context.stroke(Path { $0.move(to: CGPoint(x: px, y: plot.minY)); $0.addLine(to: CGPoint(x: px, y: plot.maxY)) }, with: .color(.white.opacity(0.3)), style: StrokeStyle(lineWidth: 1, dash: [3, 3]))122        }123    }124125    private func drawCursor(_ context: inout GraphicsContext, plot: CGRect) {126        guard let cursor else { return }127        let px = plot.minX + plot.width * cursor128        context.stroke(Path { $0.move(to: CGPoint(x: px, y: plot.minY)); $0.addLine(to: CGPoint(x: px, y: plot.maxY)) }, with: .color(.white), lineWidth: 1)129    }130131    private func cursorReadout(frame: SpectrumFrame) -> String? {132        guard let cursor else {133            guard let f = frame.dominantFrequency else { return nil }134            return "▲ \(Formatters.frequency(f))  \(Formatters.dB(Double(frame.dominantLevel), unit: "dBFS"))"135        }136        let f = axis.frequency(at: Double(cursor), min: minFrequency, max: maxFrequency)137        let bin = frame.bin(forFrequency: f)138        return "\(Formatters.frequency(f))  \(Formatters.dB(Double(frame.decibels[bin]), unit: frame.scaling.unit))"139    }140}141142/// Seven bars showing the measured power in each ORIX band (dBFS RMS), labelled so colour is never the only cue.143struct BandMeter: View {144    let bandPower: [Float]145    var body: some View {146        HStack(alignment: .bottom, spacing: 6) {147            ForEach(0..<FrequencyBandLayout.bandCount, id: \.self) { i in148                let dB = i < bandPower.count ? Decibels.fromPower(bandPower[i]) : Decibels.floor149                VStack(spacing: 3) {150                    GeometryReader { geo in151                        let h = geo.size.height * CGFloat(max(0, min(1, (dB + 90) / 90)))152                        VStack { Spacer(minLength: 0); RoundedRectangle(cornerRadius: 3).fill(ORIX.bandColors[i]).frame(height: max(2, h)) }153                    }154                    Text(ORIX.bandShortNames[i]).font(.system(size: 8, weight: .semibold, design: .monospaced)).foregroundStyle(ORIX.Palette.plotText).lineLimit(1).minimumScaleFactor(0.6)155                }156                .accessibilityElement(children: .ignore)157                .accessibilityLabel(Text(CoreText.bandName(i)))158                .accessibilityValue(Text("\(Int(dB)) decibels"))159            }160        }161    }162}163164struct SpectrumSettingsMenu: View {165    @Binding var configuration: SpectrumConfiguration166    @Binding var axis: FrequencyAxis167    var body: some View {168        Menu {169            Picker("FFT size", selection: $configuration.fftSize) {170                ForEach([1024, 2048, 4096, 8192, 16_384], id: \.self) { Text("\($0) points").tag($0) }171            }172            Picker("Window", selection: $configuration.window) { ForEach(WindowFunction.allCases) { Text(CoreText.name($0)).tag($0) } }173            Picker("Quantity", selection: $configuration.scaling) { ForEach(SpectrumScaling.allCases) { Text(verbatim: "\(CoreText.name($0)) (\($0.unit))").tag($0) } }174            Picker("Frequency axis", selection: $axis) { Text("Logarithmic").tag(FrequencyAxis.logarithmic); Text("Linear").tag(FrequencyAxis.linear) }175            Picker("Smoothing", selection: $configuration.smoothing) {176                Text("No smoothing").tag(Float(0)); Text("Low smoothing").tag(Float(0.4)); Text("Medium smoothing").tag(Float(0.6)); Text("High smoothing").tag(Float(0.85))177            }178            Picker("Peak hold", selection: $configuration.peakDecayDBPerSecond) {179                Text("Fast decay").tag(Float(24)); Text("Slow decay").tag(Float(12)); Text("Hold").tag(Float(0))180            }181        } label: {182            Label("Analyzer settings", systemImage: "slider.horizontal.3").labelStyle(.iconOnly)183        }184    }185}186
Files main
Menu

Theme