Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

feat(overlay): drive waveform from voice spectrum

altic-dev9aded314c20d
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 840aa20a..60d9cb37 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -6345,6 +6345,7 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
}
if recordingEnabled == false {
self.lock.unlock()
+ AudioSpectrumMeter.shared.ingest(samples)
self.onLevel(self.measureAudioLevel(samples).level)
return
}
@@ -6432,6 +6433,7 @@ private final nonisolated class AudioCapturePipeline: @unchecked Sendable {
}
self.lock.unlock()
let measurement = self.measureAudioLevel(mono16k)
+ AudioSpectrumMeter.shared.ingest(mono16k)
self.onLevel(measurement.level)
if let health = self.captureHealthDiagnostic(
sampleCount: mono16k.count,
diff --git a/Sources/Fluid/Services/AudioSpectrumMeter.swift b/Sources/Fluid/Services/AudioSpectrumMeter.swift
new file mode 100644
index 00000000..c6dd341b
--- /dev/null
+++ b/Sources/Fluid/Services/AudioSpectrumMeter.swift
@@ -0,0 +1,121 @@
+import Accelerate
+import Foundation
+
+/// Splits the most recent microphone audio into log-spaced frequency bands for the
+/// overlay visualizer. Read-only tap: it never alters or delays the captured samples.
+final class AudioSpectrumMeter: @unchecked Sendable {
+ static let shared = AudioSpectrumMeter()
+ static let bandCount = 11
+
+ private static let log2n: vDSP_Length = 9
+ private static let frameSize = 1 << 9
+ private static let sampleRate: Float = 16_000
+ private static let lowestFrequency: Float = 120
+ private static let highestFrequency: Float = 6000
+ private static let floorDecibels: Float = -62
+ private static let rangeDecibels: Float = 50
+ /// Speech energy falls off with pitch; lift higher bands so consonants register.
+ private static let tiltDecibelsPerOctave: Float = 3
+
+ private let lock = NSLock()
+ private let setup: FFTSetup?
+ private let window: [Float]
+ private let bandEdges: [Int]
+ private var ring = [Float](repeating: 0, count: AudioSpectrumMeter.frameSize)
+ private var ringIndex = 0
+ private var frame = [Float](repeating: 0, count: AudioSpectrumMeter.frameSize)
+ private var real = [Float](repeating: 0, count: AudioSpectrumMeter.frameSize / 2)
+ private var imaginary = [Float](repeating: 0, count: AudioSpectrumMeter.frameSize / 2)
+ private var magnitudes = [Float](repeating: 0, count: AudioSpectrumMeter.frameSize / 2)
+ private var latest = [Float](repeating: 0, count: AudioSpectrumMeter.bandCount)
+
+ private init() {
+ self.setup = vDSP_create_fftsetup(Self.log2n, FFTRadix(kFFTRadix2))
+ var window = [Float](repeating: 0, count: Self.frameSize)
+ vDSP_hann_window(&window, vDSP_Length(Self.frameSize), Int32(vDSP_HANN_NORM))
+ self.window = window
+
+ let binWidth = Self.sampleRate / Float(Self.frameSize)
+ let ratio = Self.highestFrequency / Self.lowestFrequency
+ var edges: [Int] = []
+ for band in 0...Self.bandCount {
+ let frequency = Self.lowestFrequency * pow(ratio, Float(band) / Float(Self.bandCount))
+ let bin = Int((frequency / binWidth).rounded())
+ // Low bands are narrower than one bin; keep every band at least one bin wide.
+ edges.append(max(bin, (edges.last ?? 0) + 1))
+ }
+ self.bandEdges = edges
+ }
+
+ deinit {
+ if let setup { vDSP_destroy_fftsetup(setup) }
+ }
+
+ /// Feed 16 kHz mono samples. Called from the capture pipeline.
+ func ingest(_ samples: [Float]) {
+ guard let setup, samples.isEmpty == false else { return }
+ self.lock.lock()
+ defer { self.lock.unlock() }
+
+ for sample in samples.suffix(Self.frameSize) {
+ self.ring[self.ringIndex] = sample
+ self.ringIndex = (self.ringIndex + 1) % Self.frameSize
+ }
+ for index in 0..<Self.frameSize {
+ self.frame[index] = self.ring[(self.ringIndex + index) % Self.frameSize] * self.window[index]
+ }
+
+ let halfSize = Self.frameSize / 2
+ self.real.withUnsafeMutableBufferPointer { realPointer in
+ self.imaginary.withUnsafeMutableBufferPointer { imaginaryPointer in
+ var split = DSPSplitComplex(realp: realPointer.baseAddress!, imagp: imaginaryPointer.baseAddress!)
+ self.frame.withUnsafeBufferPointer { framePointer in
+ framePointer.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complex in
+ vDSP_ctoz(complex, 2, &split, 1, vDSP_Length(halfSize))
+ }
+ }
+ vDSP_fft_zrip(setup, &split, 1, Self.log2n, FFTDirection(FFT_FORWARD))
+ vDSP_zvabs(&split, 1, &self.magnitudes, 1, vDSP_Length(halfSize))
+ }
+ }
+
+ // zrip output is scaled by 2; the normalized Hann window halves amplitude again.
+ let amplitudeScale = 2 / Float(Self.frameSize)
+ for band in 0..<Self.bandCount {
+ let lower = min(self.bandEdges[band], halfSize - 1)
+ let upper = min(max(self.bandEdges[band + 1], lower + 1), halfSize)
+ var peak: Float = 0
+ self.magnitudes.withUnsafeBufferPointer { pointer in
+ vDSP_maxv(pointer.baseAddress! + lower, 1, &peak, vDSP_Length(upper - lower))
+ }
+ let octave = Float(band) / Float(Self.bandCount) * log2(Self.highestFrequency / Self.lowestFrequency)
+ let decibels = 20 * log10(max(peak * amplitudeScale, 1e-9)) + octave * Self.tiltDecibelsPerOctave
+ let value = min(max((decibels - Self.floorDecibels) / Self.rangeDecibels, 0), 1)
+ // Single FFT frames flicker; ease toward each new reading.
+ self.latest[band] += (value - self.latest[band]) * 0.45
+ }
+ }
+
+ func reset() {
+ self.lock.lock()
+ defer { self.lock.unlock() }
+ for index in self.ring.indices { self.ring[index] = 0 }
+ for index in self.latest.indices { self.latest[index] = 0 }
+ }
+
+ /// Band levels in 0...1, low frequencies first, resampled to `count` bars.
+ func bands(count: Int) -> [CGFloat] {
+ guard count > 0 else { return [] }
+ self.lock.lock()
+ let snapshot = self.latest
+ self.lock.unlock()
+ guard count != snapshot.count else { return snapshot.map { CGFloat($0) } }
+ return (0..<count).map { index in
+ let position = Float(index) / Float(max(count - 1, 1)) * Float(snapshot.count - 1)
+ let lower = Int(position)
+ let upper = min(lower + 1, snapshot.count - 1)
+ let fraction = position - Float(lower)
+ return CGFloat(snapshot[lower] * (1 - fraction) + snapshot[upper] * fraction)
+ }
+ }
+}
diff --git a/Sources/Fluid/Views/BottomWaveformView.swift b/Sources/Fluid/Views/BottomWaveformView.swift
index 5e444431..97b57b88 100644
--- a/Sources/Fluid/Views/BottomWaveformView.swift
+++ b/Sources/Fluid/Views/BottomWaveformView.swift
@@ -13,8 +13,7 @@ struct BottomWaveformView: View {
!self.audioLevel.isLive && !self.contentState.isProcessing && !self.isReleaseAnimationActive
}
- // Initialize with max possible bar count (11 for large) to prevent index-out-of-range before onAppear
- @State private var barHeights: [CGFloat] = Array(repeating: 6, count: 11)
+ @State private var simulation = WaveformSimulation()
@State private var noiseThreshold: CGFloat = .init(SettingsStore.shared.visualizerNoiseThreshold)
private var barCount: Int {
@@ -70,14 +69,6 @@ struct BottomWaveformView: View {
self.contentState.isBottomOverlayReleaseTransitioning || self.contentState.isBottomOverlayDismissing
}
- /// Safe accessor for bar heights to prevent index-out-of-range crashes
- private func safeBarHeight(at index: Int) -> CGFloat {
- guard index >= 0 && index < self.barHeights.count else {
- return self.minHeight
- }
- return self.barHeights[index]
- }
-
var body: some View {
ZStack {
self.barsView
@@ -93,40 +84,6 @@ struct BottomWaveformView: View {
}
.opacity(self.isWaitingForMicrophone ? 0.45 : 1)
.animation(.easeOut(duration: 0.22), value: self.isWaitingForMicrophone)
- .onChange(of: self.audioLevel.level) { _, level in
- guard !self.isReleaseAnimationActive else { return }
- if !self.contentState.isProcessing {
- self.updateBars(level: level)
- }
- }
- .onChange(of: self.contentState.isProcessing) { _, processing in
- guard !self.isReleaseAnimationActive else { return }
- if processing {
- self.setFlatProcessingBars()
- } else {
- // Resume from silence; next audio tick will animate up.
- self.updateBars(level: 0)
- }
- }
- .onChange(of: self.layout.barCount) { _, newCount in
- self.barHeights = Array(repeating: self.minHeight, count: newCount)
- }
- .onAppear {
- // Ensure bar count matches current layout
- if self.barHeights.count != self.barCount {
- self.barHeights = Array(repeating: self.minHeight, count: self.barCount)
- }
- if self.isReleaseAnimationActive {
- self.barHeights = Array(repeating: self.minHeight, count: self.barCount)
- } else if self.contentState.isProcessing {
- self.setFlatProcessingBars()
- } else {
- self.updateBars(level: 0)
- }
- }
- .onDisappear {
- // No timers to clean up.
- }
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when user changes sensitivity setting
let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
@@ -136,65 +93,107 @@ struct BottomWaveformView: View {
}
}
+ /// Drawn at display rate so the bars move on springs instead of stepping with each level tick.
+ @ViewBuilder
private var barsView: some View {
- HStack(spacing: self.barSpacing) {
- ForEach(0..<self.barCount, id: \.self) { index in
- RoundedRectangle(cornerRadius: self.barWidth / 2)
- .frame(width: self.barWidth, height: self.displayHeight(at: index))
- .shadow(
- color: self.color.opacity(self.isReleaseAnimationActive ? 0 : self.currentGlowIntensity),
- radius: self.isReleaseAnimationActive ? 0 : self.currentGlowRadius,
- x: 0,
- y: 0
- )
+ // The panel stays alive while hidden; never tick the simulation unless it is on screen.
+ if !self.contentState.isBottomOverlayPresented || self.isReleaseAnimationActive || self.contentState.isProcessing {
+ self.bars(heights: Array(repeating: self.minHeight, count: self.barCount))
+ } else {
+ TimelineView(.animation(minimumInterval: 1.0 / 50.0)) { timeline in
+ self.bars(heights: self.simulation.step(
+ at: timeline.date,
+ barCount: self.barCount,
+ minHeight: self.minHeight,
+ maxHeight: self.maxHeight,
+ level: self.audioLevel.isLive ? OverlayAudioLevelState.shared.level : 0,
+ noiseThreshold: self.noiseThreshold,
+ isIdleWaveEnabled: self.audioLevel.isLive
+ ))
}
}
}
- private func displayHeight(at index: Int) -> CGFloat {
- if self.isReleaseAnimationActive || self.contentState.isProcessing {
- return self.minHeight
- }
- return self.safeBarHeight(at: index)
- }
-
- private func visualizerPeakHeight(at index: Int) -> CGFloat {
- let centerDistance = abs(CGFloat(index) - CGFloat(self.barCount - 1) / 2)
- let maxDistance = max(CGFloat(self.barCount - 1) / 2, 1)
- let normalizedDistance = min(centerDistance / maxDistance, 1)
- let factor = max(0.18, 0.96 - normalizedDistance * 0.78)
- return self.minHeight + (self.maxHeight - self.minHeight) * factor
- }
-
- private func setFlatProcessingBars() {
- // Ensure array is properly sized before modifying
- guard self.barHeights.count >= self.barCount else { return }
-
- // During AI processing we want the visualizer to settle to silence (flat).
- withAnimation(.easeOut(duration: 0.18)) {
- for i in 0..<self.barCount {
- self.barHeights[i] = self.minHeight
+ private func bars(heights: [CGFloat]) -> some View {
+ Canvas { context, size in
+ let count = heights.count
+ let totalWidth = CGFloat(count) * self.barWidth + CGFloat(max(count - 1, 0)) * self.barSpacing
+ var x = (size.width - totalWidth) / 2
+ for height in heights {
+ let rect = CGRect(x: x, y: (size.height - height) / 2, width: self.barWidth, height: height)
+ context.fill(Path(roundedRect: rect, cornerRadius: self.barWidth / 2), with: .foreground)
+ x += self.barWidth + self.barSpacing
}
}
+ .shadow(
+ color: self.color.opacity(self.isReleaseAnimationActive ? 0 : self.currentGlowIntensity),
+ radius: self.isReleaseAnimationActive ? 0 : self.currentGlowRadius
+ )
}
+}
- private func updateBars(level: CGFloat) {
- // Ensure array is properly sized before modifying
- guard self.barHeights.count >= self.barCount else { return }
-
- let normalizedLevel = min(max(level, 0), 1)
- let denominator = max(1.0 - self.noiseThreshold, 0.001)
- let adjustedLevel = max(min((normalizedLevel - self.noiseThreshold) / denominator, 1.0), 0.0)
- // Lower exponent => normal speech pushes the bars higher (taller "waves" while talking).
- let amplifiedLevel = pow(adjustedLevel, 0.55)
-
- withAnimation(.easeOut(duration: 0.08)) {
- for i in 0..<self.barCount {
- let peakHeight = self.visualizerPeakHeight(at: i)
- let variation = 0.92 + 0.08 * cos(CGFloat(i) * 1.45)
- let nextHeight = self.minHeight + (peakHeight - self.minHeight) * amplifiedLevel * variation
- self.barHeights[i] = min(self.maxHeight, max(self.minHeight, nextHeight))
- }
+/// Per-bar spring physics for the overlay visualizer. Voice energy lands on the center bars
+/// first and ripples outward, the spectrum tilts the shape, and a slow idle wave keeps the
+/// bars breathing while the user is quiet.
+final class WaveformSimulation {
+ private var heights: [CGFloat] = []
+ private var velocities: [CGFloat] = []
+ private var energyHistory: [CGFloat] = Array(repeating: 0, count: 32)
+ private var historyIndex = 0
+ private var energy: CGFloat = 0
+ private var lastDate: Date?
+ private var clock: TimeInterval = 0
+
+ func step(
+ at date: Date,
+ barCount: Int,
+ minHeight: CGFloat,
+ maxHeight: CGFloat,
+ level: CGFloat,
+ noiseThreshold: CGFloat,
+ isIdleWaveEnabled: Bool
+ ) -> [CGFloat] {
+ if self.heights.count != barCount {
+ self.heights = Array(repeating: minHeight, count: barCount)
+ self.velocities = Array(repeating: 0, count: barCount)
+ }
+ let dt = CGFloat(min(max(date.timeIntervalSince(self.lastDate ?? date), 0), 1.0 / 30.0))
+ self.lastDate = date
+ self.clock += TimeInterval(dt)
+ guard dt > 0 else { return self.heights }
+
+ let adjusted = max(min((min(max(level, 0), 1) - noiseThreshold) / max(1 - noiseThreshold, 0.001), 1), 0)
+ let gate = pow(adjusted, 0.5)
+ // Level arrives at ~20 Hz; glide toward it so the ripple source is continuous.
+ self.energy += (gate - self.energy) * min(dt * 18, 1)
+ self.historyIndex = (self.historyIndex + 1) % self.energyHistory.count
+ self.energyHistory[self.historyIndex] = self.energy
+
+ let bands = AudioSpectrumMeter.shared.bands(count: barCount)
+ let half = max(CGFloat(barCount - 1) / 2, 1)
+ let range = maxHeight - minHeight
+
+ for i in 0..<barCount {
+ let distance = abs(CGFloat(i) - half) / half
+ // Outer bars hear the voice a few frames later than the center.
+ let delayFrames = Int((distance * 0.09 / max(dt, 0.001)).rounded())
+ let delayed = self.energyHistory[
+ (self.historyIndex - min(delayFrames, self.energyHistory.count - 1) + self.energyHistory.count) % self.energyHistory.count
+ ]
+ let envelope = 0.34 + 0.66 * cos(distance * .pi / 2)
+ let band = i < bands.count ? bands[i] : 0
+ let wobble = 0.9 + 0.1 * sin(CGFloat(self.clock) * 9 + CGFloat(i) * 2.1)
+ let voice = delayed * (0.5 + 0.5 * band) * wobble * envelope
+ let idle = isIdleWaveEnabled
+ ? (1 - self.energy) * 0.13 * (0.5 + 0.5 * sin(CGFloat(self.clock) * 2.4 - CGFloat(i) * 0.75))
+ : 0
+ let target = minHeight + range * min(voice + idle, 1)
+
+ // Slightly underdamped spring: lively on the way up, settles without buzzing.
+ let acceleration = 260 * (target - self.heights[i]) - 21 * self.velocities[i]
+ self.velocities[i] += acceleration * dt
+ self.heights[i] = min(maxHeight, max(minHeight, self.heights[i] + self.velocities[i] * dt))
}
+ return self.heights
}
}