Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/Capture/SPSCRingBuffer.swift4// Description: Wait-free single-producer / single-consumer ring buffer of Float samples with overflow accounting.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation10import Synchronization1112/// Bounded FIFO shared by exactly one writer thread and one reader thread. Neither side locks or allocates.13/// When the reader falls behind, `write` stores what fits and reports the rest as dropped (back-pressure is explicit).14public final class SPSCRingBuffer: @unchecked Sendable {15 public let capacity: Int16 private let mask: Int17 private let storage: UnsafeMutablePointer<Float>18 private let head = Atomic<Int>(0) // next write position (monotonic)19 private let tail = Atomic<Int>(0) // next read position (monotonic)20 private let dropped = Atomic<Int>(0)2122 /// Capacity is rounded up to a power of two.23 public init(minimumCapacity: Int) {24 var c = 102425 while c < minimumCapacity { c <<= 1 }26 capacity = c; mask = c - 127 storage = .allocate(capacity: c)28 storage.initialize(repeating: 0, count: c)29 }3031 deinit { storage.deallocate() }3233 public var availableToRead: Int { head.load(ordering: .acquiring) - tail.load(ordering: .acquiring) }34 public var droppedSamples: Int { dropped.load(ordering: .relaxed) }3536 /// Producer side. Returns the number of samples stored.37 @discardableResult38 public func write(_ source: UnsafePointer<Float>, count: Int) -> Int {39 let h = head.load(ordering: .relaxed), t = tail.load(ordering: .acquiring)40 let n = min(count, capacity - (h - t))41 if n < count { dropped.add(count - n, ordering: .relaxed) }42 guard n > 0 else { return 0 }43 let start = h & mask, first = min(n, capacity - start)44 (storage + start).update(from: source, count: first)45 if first < n { storage.update(from: source + first, count: n - first) }46 head.store(h + n, ordering: .releasing)47 return n48 }4950 /// Consumer side. Returns the number of samples copied into `destination`.51 @discardableResult52 public func read(into destination: UnsafeMutablePointer<Float>, maxCount: Int) -> Int {53 let t = tail.load(ordering: .relaxed), h = head.load(ordering: .acquiring)54 let n = min(maxCount, h - t)55 guard n > 0 else { return 0 }56 let start = t & mask, first = min(n, capacity - start)57 destination.update(from: storage + start, count: first)58 if first < n { (destination + first).update(from: storage, count: n - first) }59 tail.store(t + n, ordering: .releasing)60 return n61 }62}63