From 009a8ba870fb9f5ab07931b1a73b5ce765122014 Mon Sep 17 00:00:00 2001 From: Yannic Charlon <52761674+JustYannicc@users.noreply.github.com> Date: Fri, 3 Jul 2026 21:17:32 +0200 Subject: [PATCH] fix: avoid idle audio buffer conversion --- src/native/audio-capturer.swift | 113 ++++++++++++++++++++++++++++---- 1 file changed, 99 insertions(+), 14 deletions(-) diff --git a/src/native/audio-capturer.swift b/src/native/audio-capturer.swift index 752b6e3c..72ec9efc 100644 --- a/src/native/audio-capturer.swift +++ b/src/native/audio-capturer.swift @@ -279,6 +279,16 @@ class AudioCapturer { // MARK: Buffer processing private func processBuffer(_ buffer: AVAudioPCMBuffer) { + let now = Date() + let shouldUpdateMeter = now.timeIntervalSince(lastMeterAt) >= meterInterval + + guard isRecording || shouldUpdateMeter else { return } + + if !isRecording { + updateMeter(fromInputBuffer: buffer, now: now) + return + } + guard let converted = convertBuffer(buffer), converted.frameLength > 0, let samples = converted.floatChannelData?[0] @@ -290,20 +300,8 @@ class AudioCapturer { ringBuffer.append(UnsafeBufferPointer(start: samples, count: sampleCount)) } - // Compute meter - let now = Date() - if now.timeIntervalSince(lastMeterAt) >= meterInterval { - var sumSquares: Float = 0 - var peak: Float = 0 - for i in 0.. 0 else { return } + + let channelStride = buffer.format.isInterleaved ? Int(max(1, buffer.format.channelCount)) : 1 + + switch buffer.format.commonFormat { + case .pcmFormatFloat32: + guard let samples = buffer.floatChannelData?[0] else { return } + updateMeter(samples: samples, sampleCount: sampleCount, stride: channelStride, now: now) + case .pcmFormatFloat64: + guard let rawSamples = buffer.audioBufferList.pointee.mBuffers.mData else { return } + updateMeter( + samples: rawSamples.assumingMemoryBound(to: Double.self), + sampleCount: sampleCount, + stride: channelStride, + now: now + ) + case .pcmFormatInt16: + guard let samples = buffer.int16ChannelData?[0] else { return } + updateMeter(samples: samples, sampleCount: sampleCount, stride: channelStride, divisor: Float(Int16.max), now: now) + case .pcmFormatInt32: + guard let samples = buffer.int32ChannelData?[0] else { return } + updateMeter(samples: samples, sampleCount: sampleCount, stride: channelStride, divisor: Float(Int32.max), now: now) + case .otherFormat: + return + @unknown default: + return + } + } + + private func updateMeter( + samples: UnsafePointer, + sampleCount: Int, + stride: Int, + now: Date + ) { + var sumSquares: Float = 0 + var peak: Float = 0 + for i in 0.., + sampleCount: Int, + stride: Int, + now: Date + ) { + var sumSquares: Float = 0 + var peak: Float = 0 + for i in 0..( + samples: UnsafePointer, + sampleCount: Int, + stride: Int, + divisor: Float, + now: Date + ) { + var sumSquares: Float = 0 + var peak: Float = 0 + for i in 0.. AVAudioPCMBuffer? {