|
| 1 | +import Accelerate |
| 2 | +@preconcurrency import AVFoundation |
| 3 | +import ElevenLabs |
| 4 | + |
| 5 | +/// Tracks a normalized loudness level for one conversation audio stream. |
| 6 | +/// |
| 7 | +/// Pull-based: `didReceive` runs on the audio thread and only holds the loudest |
| 8 | +/// level seen. Reading drains it, which is also what paces the decay, so the |
| 9 | +/// level keeps falling once a stream goes quiet and stops delivering buffers. |
| 10 | +final class ConversationAudioLevelMonitor: ConversationAudioObserver, @unchecked Sendable { |
| 11 | + /// Fraction of the level kept per read: fast attack, slow release. |
| 12 | + private static let release: Float = 0.75 |
| 13 | + |
| 14 | + private let lock = NSLock() |
| 15 | + private var storedLevel: Float = 0 |
| 16 | + /// Only touched from the audio thread, which delivers buffers serially. |
| 17 | + private var scratch: [Float] = [] |
| 18 | + |
| 19 | + /// The loudest level since the last read, leaving one release step behind. |
| 20 | + func sample() -> Float { |
| 21 | + lock.withLock { |
| 22 | + defer { storedLevel *= Self.release } |
| 23 | + return storedLevel |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + func didReceive(_ buffer: AVAudioPCMBuffer) { |
| 28 | + guard let level = normalizedRMS(of: buffer) else { return } |
| 29 | + lock.withLock { storedLevel = max(level, storedLevel) } |
| 30 | + } |
| 31 | + |
| 32 | + func reset() { |
| 33 | + lock.withLock { storedLevel = 0 } |
| 34 | + } |
| 35 | + |
| 36 | + /// RMS of the first channel, mapped from the top 60 dB of headroom onto 0...1. |
| 37 | + private func normalizedRMS(of buffer: AVAudioPCMBuffer) -> Float? { |
| 38 | + let frames = Int(buffer.frameLength) |
| 39 | + guard frames > 0 else { return nil } |
| 40 | + let stride = buffer.format.isInterleaved ? vDSP_Stride(buffer.format.channelCount) : 1 |
| 41 | + |
| 42 | + var rms: Float = 0 |
| 43 | + if let channel = buffer.floatChannelData?[0] { |
| 44 | + vDSP_rmsqv(channel, stride, &rms, vDSP_Length(frames)) |
| 45 | + } else if let channel = buffer.int16ChannelData?[0] { |
| 46 | + // Grown, never reallocated per buffer: this is the audio thread. |
| 47 | + if scratch.count < frames { scratch = [Float](repeating: 0, count: frames) } |
| 48 | + scratch.withUnsafeMutableBufferPointer { floats in |
| 49 | + guard let samples = floats.baseAddress else { return } |
| 50 | + vDSP_vflt16(channel, stride, samples, 1, vDSP_Length(frames)) |
| 51 | + var scale = 1 / Float(Int16.max) |
| 52 | + vDSP_vsmul(samples, 1, &scale, samples, 1, vDSP_Length(frames)) |
| 53 | + vDSP_rmsqv(samples, 1, &rms, vDSP_Length(frames)) |
| 54 | + } |
| 55 | + } else { |
| 56 | + return nil |
| 57 | + } |
| 58 | + |
| 59 | + let decibels = 20 * log10(max(rms, 0.000_001)) |
| 60 | + return min(max((decibels + 60) / 60, 0), 1) |
| 61 | + } |
| 62 | +} |
0 commit comments