Jotley / app · jotley.ai / iOS / Views / RecordingView+Waveform.swift
| 1 | import SwiftUI |
| 2 | import UIKit |
| 3 | // MARK: - Live Transcription Waveform |
| 4 | |
| 5 | enum LiveWaveformResponse { |
| 6 | static let restingLevel: Float = 0.04 |
| 7 | |
| 8 | static func level(for peak: Float) -> Float { |
| 9 | guard peak.isFinite else { return restingLevel } |
| 10 | let noiseFloor: Float = 0.002 |
| 11 | let input = max(0, min(1, peak) - noiseFloor) |
| 12 | // Lift quiet speech while leaving room for louder syllables. |
| 13 | return restingLevel + 0.88 * log1p(170 * input) / log1p(170 * (1 - noiseFloor)) |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /// Core Animation interpolates bars on the render server. Transcript updates |
| 18 | /// do not publish waveform state or require SwiftUI to render every frame. |
| 19 | struct LiveTranscriptionWaveformView: View { |
| 20 | let levelProvider: () -> Float |
| 21 | let isTranscribing: Bool |
| 22 | var isPaused = false |
| 23 | @Environment(\.scenePhase) private var scenePhase |
| 24 | var body: some View { |
| 25 | LiveWaveformSurface(levelProvider: levelProvider, |
| 26 | listening: isTranscribing && scenePhase == .active, paused: isPaused, |
| 27 | color: isTranscribing ? UIColor(Color.themePrimaryAccent) : UIColor.gray.withAlphaComponent(isPaused ? 0.5 : 0.4)) |
| 28 | .accessibilityLabel(isTranscribing ? "Live microphone waveform" : "Paused waveform") |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | private struct LiveWaveformSurface: UIViewRepresentable { |
| 33 | let levelProvider: () -> Float |
| 34 | let listening: Bool |
| 35 | let paused: Bool |
| 36 | let color: UIColor |
| 37 | func makeUIView(context: Context) -> LiveWaveformLayerView { LiveWaveformLayerView() } |
| 38 | func updateUIView(_ view: LiveWaveformLayerView, context: Context) { |
| 39 | view.update(levelProvider: levelProvider, listening: listening, paused: paused, color: color) |
| 40 | } |
| 41 | static func dismantleUIView(_ view: LiveWaveformLayerView, coordinator: ()) { view.stopTimer() } |
| 42 | } |
| 43 | |
| 44 | final class LiveWaveformLayerView: UIView { |
| 45 | private static let updateInterval = 1 / LiveTranscriptionManager.waveformSamplesPerSecond |
| 46 | private static let minimumBarHeight: CGFloat = 3 |
| 47 | private let bars = (0..<50).map { _ in CALayer() } |
| 48 | private var levels = Array(repeating: LiveWaveformResponse.restingLevel, count: 50) |
| 49 | private var smoothedLevel = LiveWaveformResponse.restingLevel |
| 50 | private var levelProvider: (() -> Float)? |
| 51 | private var listening = false |
| 52 | private var timer: Timer? |
| 53 | override init(frame: CGRect) { |
| 54 | super.init(frame: frame) |
| 55 | isUserInteractionEnabled = false |
| 56 | for bar in bars { layer.addSublayer(bar) } |
| 57 | } |
| 58 | required init?(coder: NSCoder) { fatalError("init(coder:) is unsupported") } |
| 59 | func update(levelProvider: @escaping () -> Float, listening: Bool, paused: Bool, color: UIColor) { |
| 60 | self.levelProvider = levelProvider; self.listening = listening |
| 61 | CATransaction.begin(); CATransaction.setDisableActions(true) |
| 62 | for bar in bars { bar.backgroundColor = color.cgColor } |
| 63 | CATransaction.commit() |
| 64 | if !listening && !paused { |
| 65 | levels = Array(repeating: LiveWaveformResponse.restingLevel, count: bars.count) |
| 66 | smoothedLevel = LiveWaveformResponse.restingLevel |
| 67 | for bar in bars { bar.removeAllAnimations() } |
| 68 | setNeedsLayout() |
| 69 | } |
| 70 | updateTimer() |
| 71 | } |
| 72 | override func didMoveToWindow() { super.didMoveToWindow(); updateTimer() } |
| 73 | private func updateTimer() { |
| 74 | guard listening && window != nil else { stopTimer(); return } |
| 75 | guard timer == nil else { return } |
| 76 | let timer = Timer(timeInterval: Self.updateInterval, repeats: true) { [weak self] _ in |
| 77 | MainActor.assumeIsolated { self?.advanceWaveform() } |
| 78 | } |
| 79 | timer.tolerance = 0.004 |
| 80 | RunLoop.main.add(timer, forMode: .common) |
| 81 | self.timer = timer |
| 82 | } |
| 83 | func stopTimer() { timer?.invalidate(); timer = nil } |
| 84 | override func layoutSubviews() { |
| 85 | super.layoutSubviews() |
| 86 | let spacing: CGFloat = 2 |
| 87 | let width = max(1, floor((bounds.width - CGFloat(bars.count - 1) * spacing) / CGFloat(bars.count))) |
| 88 | let left = floor((bounds.width - CGFloat(bars.count) * width - CGFloat(bars.count - 1) * spacing) / 2) |
| 89 | CATransaction.begin(); CATransaction.setDisableActions(true) |
| 90 | for (index, bar) in bars.enumerated() { |
| 91 | bar.bounds = CGRect(x: 0, y: 0, width: width, height: barHeight(at: index)) |
| 92 | bar.position = CGPoint(x: left + CGFloat(index) * (width + spacing) + width / 2, y: bounds.midY) |
| 93 | bar.cornerRadius = width / 2 |
| 94 | } |
| 95 | CATransaction.commit() |
| 96 | } |
| 97 | func advanceWaveform() { |
| 98 | guard listening else { return } |
| 99 | let input = LiveWaveformResponse.level(for: levelProvider?() ?? 0) |
| 100 | smoothedLevel += (input - smoothedLevel) * (input > smoothedLevel ? 0.9 : 0.65) |
| 101 | levels.removeFirst(); levels.append(smoothedLevel) |
| 102 | CATransaction.begin(); CATransaction.setDisableActions(true) |
| 103 | for (index, bar) in bars.enumerated() { |
| 104 | let current = bar.presentation()?.bounds.height ?? bar.bounds.height |
| 105 | let target = barHeight(at: index) |
| 106 | bar.bounds.size.height = target |
| 107 | let animation = CABasicAnimation(keyPath: "bounds.size.height") |
| 108 | animation.fromValue = current; animation.toValue = target |
| 109 | animation.duration = Self.updateInterval |
| 110 | animation.timingFunction = CAMediaTimingFunction(name: .linear) |
| 111 | bar.add(animation, forKey: "liveLevel") |
| 112 | } |
| 113 | CATransaction.commit() |
| 114 | } |
| 115 | |
| 116 | private func barHeight(at index: Int) -> CGFloat { |
| 117 | max(Self.minimumBarHeight, CGFloat(levels[index]) * bounds.height) |
| 118 | } |
| 119 | } |