|
| 1 | +// |
| 2 | +// AudioRingBuffer.swift |
| 3 | +// allonet2 |
| 4 | +// |
| 5 | +// Created by Nevyn Bengtsson on 2025-09-16. |
| 6 | +// ... mostly written by ChatGPT though. |
| 7 | + |
| 8 | +import Foundation |
| 9 | +import AVFoundation |
| 10 | +import Atomics |
| 11 | +import AudioToolbox |
| 12 | +import OpenCombineShim |
| 13 | + |
| 14 | +/// Lock-free SPSC ring buffer for deinterleaved Float32 audio. |
| 15 | +/// |
| 16 | +/// - One writer thread (producer), one reader thread (consumer), no blocking. |
| 17 | +/// - Format: Float32, non-interleaved; `channels` in [1, 8]. |
| 18 | +/// - Capacity is in frames; per-channel storage has that many samples per channel. |
| 19 | +public final class AudioRingBuffer: Cancellable, CustomStringConvertible |
| 20 | +{ |
| 21 | + public let channels: Int |
| 22 | + public let capacityFrames: Int |
| 23 | + |
| 24 | + // Per-channel storage (contiguous) to simplify wrap logic. |
| 25 | + private var channelPtrs: [UnsafeMutablePointer<Float32>] |
| 26 | + private let deallocator: () -> Void |
| 27 | + |
| 28 | + // Lock-free indices (SPSC). |
| 29 | + // `writeIndex` is advanced by producer; `readIndex` by consumer. |
| 30 | + private let writeIndex: ManagedAtomic<Int> |
| 31 | + private let readIndex: ManagedAtomic<Int> |
| 32 | + |
| 33 | + public init(channels: Int, capacityFrames: Int, canceller: @escaping () -> ()) { |
| 34 | + precondition(channels > 0 && channels <= 8, "1...8 channels supported") |
| 35 | + precondition(capacityFrames > 0) |
| 36 | + |
| 37 | + self.channels = channels |
| 38 | + // Use power-of-two capacity for cheap modulo if you like; we keep general case. |
| 39 | + self.capacityFrames = capacityFrames |
| 40 | + |
| 41 | + let bytesPerChannel = capacityFrames * MemoryLayout<Float32>.stride |
| 42 | + |
| 43 | + var pointers: [UnsafeMutablePointer<Float32>] = [] |
| 44 | + pointers.reserveCapacity(channels) |
| 45 | + |
| 46 | + // Allocate one contiguous block for all channels to be cache-friendly. |
| 47 | + let totalBytes = bytesPerChannel * channels |
| 48 | + let base = UnsafeMutableRawPointer.allocate(byteCount: totalBytes, alignment: MemoryLayout<Float32>.alignment) as! UnsafeMutableRawPointer |
| 49 | + |
| 50 | + // Zero out once. |
| 51 | + base.initializeMemory(as: UInt8.self, repeating: 0, count: totalBytes) |
| 52 | + |
| 53 | + for ch in 0..<channels { |
| 54 | + let ptr = base.advanced(by: ch * bytesPerChannel).bindMemory(to: Float32.self, capacity: capacityFrames) |
| 55 | + pointers.append(ptr) |
| 56 | + } |
| 57 | + |
| 58 | + self.channelPtrs = pointers |
| 59 | + self.deallocator = { |
| 60 | + base.deallocate() |
| 61 | + } |
| 62 | + |
| 63 | + self.writeIndex = ManagedAtomic(0) |
| 64 | + self.readIndex = ManagedAtomic(0) |
| 65 | + self.canceller = canceller |
| 66 | + } |
| 67 | + |
| 68 | + deinit { |
| 69 | + deallocator() |
| 70 | + } |
| 71 | + |
| 72 | + public var description: String { |
| 73 | + "<AudioRingBuffer@{\(Unmanaged.passUnretained(self).toOpaque())} buffered frames: \(availableToRead()), write capacity \(availableToWrite())>" |
| 74 | + } |
| 75 | + |
| 76 | + /// Frames available to read. |
| 77 | + @inline(__always) |
| 78 | + public func availableToRead() -> Int { |
| 79 | + let w = writeIndex.load(ordering: .acquiring) |
| 80 | + let r = readIndex.load(ordering: .acquiring) |
| 81 | + let diff = w - r |
| 82 | + return diff >= 0 ? diff : diff + capacityFrames |
| 83 | + } |
| 84 | + |
| 85 | + /// Free space for writing. |
| 86 | + @inline(__always) |
| 87 | + public func availableToWrite() -> Int { |
| 88 | + // We leave one frame empty to disambiguate full vs empty. |
| 89 | + return capacityFrames - 1 - availableToRead() |
| 90 | + } |
| 91 | + |
| 92 | + /// Write up to `pcm.frameLength` frames from a non-interleaved Float32 AVAudioPCMBuffer. |
| 93 | + /// Returns frames accepted (may be less than requested if full). |
| 94 | + @discardableResult |
| 95 | + public func write(_ pcm: AVAudioPCMBuffer) -> Int { |
| 96 | + guard let src = pcm.floatChannelData else { return 0 } |
| 97 | + let frames = Int(pcm.frameLength) |
| 98 | + let ch = Int(pcm.format.channelCount) |
| 99 | + guard ch == channels else { return 0 } |
| 100 | + return writeDeinterleaved(source: UnsafePointer(src), frames: frames) |
| 101 | + } |
| 102 | + |
| 103 | + /// Write from deinterleaved channel pointers. |
| 104 | + /// `source` is an array-like pointer set (Float32* per channel). |
| 105 | + @discardableResult |
| 106 | + public func writeDeinterleaved(source: UnsafePointer<UnsafeMutablePointer<Float32>>, frames: Int) -> Int { |
| 107 | + if frames == 0 { return 0 } |
| 108 | + let writable = availableToWrite() |
| 109 | + if writable == 0 { return 0 } |
| 110 | + |
| 111 | + let toWrite = min(frames, writable) |
| 112 | + var w = writeIndex.load(ordering: .relaxed) |
| 113 | + |
| 114 | + // First segment: up to ring end. |
| 115 | + let first = min(toWrite, capacityFrames - w) |
| 116 | + let second = toWrite - first |
| 117 | + |
| 118 | + for c in 0..<channels { |
| 119 | + let srcCh = source[c] |
| 120 | + let dstCh = channelPtrs[c] |
| 121 | + |
| 122 | + // segment 1 |
| 123 | + dstCh.advanced(by: w).assign(from: srcCh, count: first) |
| 124 | + // segment 2 (wrap) |
| 125 | + if second > 0 { |
| 126 | + dstCh.assign(from: srcCh.advanced(by: first), count: second) |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + // Publish new write index with release ordering. |
| 131 | + w = (w + toWrite) % capacityFrames |
| 132 | + writeIndex.store(w, ordering: .releasing) |
| 133 | + return toWrite |
| 134 | + } |
| 135 | + |
| 136 | + /// Read up to `frames` frames into an AudioBufferList (expects non-interleaved Float32). |
| 137 | + /// Returns frames actually read (<= requested and <= available). |
| 138 | + @discardableResult |
| 139 | + public func read(into abl: UnsafeMutableAudioBufferListPointer, frames: Int) -> Int { |
| 140 | + if frames == 0 { return 0 } |
| 141 | + let readable = availableToRead() |
| 142 | + if readable == 0 { return 0 } |
| 143 | + |
| 144 | + let toRead = min(frames, readable) |
| 145 | + var r = readIndex.load(ordering: .relaxed) |
| 146 | + |
| 147 | + let first = min(toRead, capacityFrames - r) |
| 148 | + let second = toRead - first |
| 149 | + |
| 150 | + // Validate abl matches our channel count and format. |
| 151 | + guard abl.count >= channels else { return 0 } |
| 152 | + for c in 0..<channels { |
| 153 | + let dst = abl[c] |
| 154 | + guard dst.mNumberChannels == 1 else { return 0 } // non-interleaved |
| 155 | + guard dst.mDataByteSize >= UInt32(toRead * MemoryLayout<Float32>.stride) else { return 0 } |
| 156 | + } |
| 157 | + |
| 158 | + for c in 0..<channels { |
| 159 | + let srcCh = channelPtrs[c] |
| 160 | + let dstBuf = abl[c] |
| 161 | + guard let dstPtr = dstBuf.mData?.assumingMemoryBound(to: Float32.self) else { continue } |
| 162 | + |
| 163 | + // segment 1 |
| 164 | + dstPtr.assign(from: srcCh.advanced(by: r), count: first) |
| 165 | + // segment 2 (wrap) |
| 166 | + if second > 0 { |
| 167 | + dstPtr.advanced(by: first).assign(from: srcCh, count: second) |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + // Publish new read index. |
| 172 | + r = (r + toRead) % capacityFrames |
| 173 | + readIndex.store(r, ordering: .releasing) |
| 174 | + return toRead |
| 175 | + } |
| 176 | + |
| 177 | + /// Convenience: zero-fill ABL for frames where ring underflowed. |
| 178 | + public func readOrSilence(into abl: UnsafeMutableAudioBufferListPointer, frames: Int) { |
| 179 | + let got = read(into: abl, frames: frames) |
| 180 | + if got < frames { |
| 181 | + let deficit = frames - got |
| 182 | + for c in 0..<channels { |
| 183 | + let dst = abl[c] |
| 184 | + if let ptr = dst.mData?.assumingMemoryBound(to: Float32.self) { |
| 185 | + ptr.advanced(by: got).initialize(repeating: 0, count: deficit) |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + var canceller: () -> () |
| 192 | + public func cancel() { canceller() } |
| 193 | +} |
0 commit comments