diff --git a/CLAUDE.md b/CLAUDE.md index 5a62302..c7b1bac 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -354,6 +354,8 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th - `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`) - `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`). +- `RTScratchBuffer` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`. + Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here. ## Code Review diff --git a/RELEASES.md b/RELEASES.md index a949891..b9b9a08 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,30 @@ functionality in a backward-compatible way. --- +## 2.1.0 — Swift 6.4 modernization + +An internal-hardening release adopting modern Swift on the 6.4 toolchain. No +behavioral change, and the public surface stays source-compatible. + +**Typed throws.** The closed-error-set APIs now declare their concrete error +type instead of untyped `throws`, so a caller gets an exhaustive `catch` with no +downcast: OSC (`OSCDecodeError` / `OSCServerError`), MIDI (`MIDIError`, on both +the CoreMIDI and ALSA backends), the engine's bus / config / parameter setters, +the public node-add surface — `add` / `schedule` — (`EngineAddError`), and the +self-contained file codecs (`WavFileError` / `RF64WriterError` / +`SpectralFileError`). Narrowing an API from `throws` to `throws(E)` is +source-compatible — existing `try` call sites are unaffected. The WAV and +Spectral codecs gain an `.ioFailure` case that funnels an underlying +`FileHandle` failure into the typed error. + +**Concurrency & memory hardening (internal).** NSLock-guarded state in the +scheduling and MIDI classes moved into `Mutex` for compiler-enforced lock +discipline, and the Spectral/FFT scratch owners moved from hand-managed raw +pointers to a `~Copyable` `RTScratchBuffer` (compiler-guaranteed single free, no +ARC on the handle). No API or behavioral change. + +--- + ## 2.0.0 — Linux support The major release: Lyrebird now runs on **Linux**, in addition to macOS and iOS. diff --git a/Sources/Lyrebird/Buffers/RF64Writer.swift b/Sources/Lyrebird/Buffers/RF64Writer.swift index 00aa1e4..acff136 100644 --- a/Sources/Lyrebird/Buffers/RF64Writer.swift +++ b/Sources/Lyrebird/Buffers/RF64Writer.swift @@ -81,7 +81,7 @@ public final class RF64Writer { format: AudioFileFormat, sampleRate: Double, channels: Int - ) throws { + ) throws(RF64WriterError) { guard format == .rf64Float32 || format == .rf64Int24 else { throw RF64WriterError.unsupportedFormat(format) } @@ -173,7 +173,7 @@ public final class RF64Writer { /// Append `frames` interleaved frames of native Float32 samples, converting to the /// file encoding. `samples` must contain at least `frames * channels` values. - public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer, frames: Int) throws { + public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer, frames: Int) throws(RF64WriterError) { guard frames > 0 else { return } let sampleCount: Int = frames * channels @@ -212,7 +212,7 @@ public final class RF64Writer { /// /// The `FileHandle` is closed unconditionally (even if patching throws) so a failed /// finalise never leaks the descriptor. - public func close() throws { + public func close() throws(RF64WriterError) { guard !closed else { return } closed = true defer { try? fileHandle.close() } diff --git a/Sources/Lyrebird/Buffers/RTScratchBuffer.swift b/Sources/Lyrebird/Buffers/RTScratchBuffer.swift new file mode 100644 index 0000000..e986954 --- /dev/null +++ b/Sources/Lyrebird/Buffers/RTScratchBuffer.swift @@ -0,0 +1,111 @@ +// RTScratchBuffer.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// A single-owner, heap-allocated scratch buffer with compiler-enforced lifetime. +/// +/// `RTScratchBuffer` replaces the hand-paired `UnsafeMutablePointer.allocate` / +/// `deinitialize` / `deallocate` dance that scratch-owning generators (the +/// Spectral / FFT family) repeat across many buffers. Because the type is +/// `~Copyable`, the compiler guarantees: +/// +/// - it is freed **exactly once**, at `deinit`, with the correct element count — +/// no forgotten free, no double free, no count mismatch; +/// - it cannot be copied, so two owners can never alias the same allocation. +/// +/// It carries no ARC: the handle is a raw pointer, so reading or writing an +/// element is a plain load/store with no retain/release traffic. Every accessor +/// is `@inline(__always)`, so a generator's hot loop compiles to the same code +/// as the raw-pointer form it replaces. +/// +/// **RT usage.** Allocation happens in `init` (off the render thread, at +/// generator setup); `deinit` runs when the owning generator is freed, which the +/// engine does off the RT thread via its free queue. Element access +/// (`subscript`, ``baseAddress``) is RT-safe — no allocation, no locking, no ARC. +/// Pass ``baseAddress`` to Accelerate / vDSP calls exactly as with a raw pointer. +/// +/// ```swift +/// // In a generator: +/// private let _scratch: RTScratchBuffer +/// init(size: Int) { +/// _scratch = RTScratchBuffer(count: size) // allocated + zero-filled +/// } +/// // deinit is automatic — no teardown code needed. +/// +/// func process(count: Int) { +/// vDSP_vsq(input, 1, _scratch.baseAddress, 1, vDSP_Length(count)) +/// let peak: Float = _scratch[0] +/// } +/// ``` +@_spi(LyrebirdExtensions) +public struct RTScratchBuffer: ~Copyable { + + @usableFromInline let _base: UnsafeMutablePointer + @usableFromInline let _count: Int + + /// Allocates `count` elements, each initialised to `value`. + /// + /// Use this when the buffer needs a non-zero initial fill (e.g. a unity gain + /// table initialised to `1`), where the zero-filling ``init(count:)`` would + /// silently seed the wrong value. + /// + /// - Parameters: + /// - count: Element capacity. Must be `> 0`. + /// - value: Value written to every element. + @inlinable + public init(count: Int, repeating value: Element) { + precondition(count > 0, "RTScratchBuffer requires count > 0") + _count = count + _base = UnsafeMutablePointer.allocate(capacity: count) + _base.initialize(repeating: value, count: count) + } + + /// Allocates `count` elements, zero-filled. Convenience for numeric buffers. + /// + /// - Parameter count: Element capacity. Must be `> 0`. + @inlinable + public init(count: Int) where Element: Numeric { + self.init(count: count, repeating: .zero) + } + + /// Base pointer, for Accelerate / vDSP interop and raw indexing. Valid only + /// for the duration of the call — never persist it beyond the lifetime of the + /// buffer (i.e. of the generator that owns it), exactly as with the raw + /// `UnsafeMutablePointer` this replaces. + @inlinable @inline(__always) + public var baseAddress: UnsafeMutablePointer { _base } + + /// Element capacity. + @inlinable @inline(__always) + public var count: Int { _count } + + /// Element access. No bounds check — callers stay within `count`, exactly as + /// they must with the raw pointer this replaces. + /// + /// The setter is `nonmutating`: writing an element stores through the base + /// pointer and leaves the struct's own fields untouched, so a buffer held as a + /// `let` (the usual case in a generator) is still writable — matching the raw + /// `UnsafeMutablePointer` this replaces. + @inlinable @inline(__always) + public subscript(_ index: Int) -> Element { + get { + #if DEBUG + precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range") + #endif + return _base[index] + } + nonmutating set { + #if DEBUG + precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range") + #endif + _base[index] = newValue + } + } + + deinit { + _base.deinitialize(count: _count) + _base.deallocate() + } +} diff --git a/Sources/Lyrebird/Buffers/WavFileError.swift b/Sources/Lyrebird/Buffers/WavFileError.swift index 41cc698..6a9e031 100644 --- a/Sources/Lyrebird/Buffers/WavFileError.swift +++ b/Sources/Lyrebird/Buffers/WavFileError.swift @@ -24,4 +24,7 @@ public enum WavFileError: Error, Equatable { /// A plain WAV cannot describe more than 4 GB — its RIFF and `data` sizes /// are 32-bit. Writing past that needs RF64/W64 instead. case fileTooLarge(bytes: Int) + /// An underlying file-system operation (`FileHandle` read / seek / write) + /// failed. Associated value is the system error's description. + case ioFailure(String) } diff --git a/Sources/Lyrebird/Buffers/WavFileReader.swift b/Sources/Lyrebird/Buffers/WavFileReader.swift index 745f0e6..a499103 100644 --- a/Sources/Lyrebird/Buffers/WavFileReader.swift +++ b/Sources/Lyrebird/Buffers/WavFileReader.swift @@ -28,7 +28,7 @@ public final class WavFileReader { private var framesRemaining: Int /// Opens `url` and parses its WAVE header. - public init(url: URL) throws { + public init(url: URL) throws(WavFileError) { guard let h: FileHandle = try? FileHandle(forReadingFrom: url) else { throw WavFileError.cannotOpen(url) } @@ -51,9 +51,9 @@ public final class WavFileReader { // File length, for clamping a `data` size the file cannot back. Taken // by seeking to the end and back rather than stat-ing the path, so it // describes the handle actually being read. - let scanStart: UInt64 = try h.offset() - let fileByteCount: Int = Int(try h.seekToEnd()) - try h.seek(toOffset: scanStart) + let scanStart: UInt64 = try Self.fhOffset(h) + let fileByteCount: Int = Int(try Self.fhSeekToEnd(h)) + try Self.fhSeek(h, to: scanStart) // Walk chunks until the data chunk is located (its body is left unread // so reads stream from the current file offset). @@ -90,7 +90,7 @@ public final class WavFileReader { // and believing it yields a nonsense frame count and a // `.truncated` throw partway through a render instead of a // clean EOF. - let remaining: Int = max(0, fileByteCount - Int(try h.offset())) + let remaining: Int = max(0, fileByteCount - Int(try Self.fhOffset(h))) dataLength = min(size, remaining) foundData = true break @@ -100,10 +100,10 @@ public final class WavFileReader { // discard it, and a file with embedded artwork or a large // "LIST" ahead of `data` makes that a real allocation. let skip: Int = size + (size % 2) - let current: UInt64 = try h.offset() + let current: UInt64 = try Self.fhOffset(h) let target: UInt64 = current + UInt64(max(0, skip)) guard target <= UInt64(fileByteCount) else { break } - try h.seek(toOffset: target) + try Self.fhSeek(h, to: target) } } @@ -124,7 +124,7 @@ public final class WavFileReader { /// Reads up to `frames` frames, returning interleaved `Float` samples. The /// returned array holds `framesRead * channels` values; `framesRead` may be /// smaller than requested at end of file (and zero once exhausted). - public func read(frames: Int) throws -> [Float] { + public func read(frames: Int) throws(WavFileError) -> [Float] { let toRead: Int = min(frames, framesRemaining) guard toRead > 0 else { return [] } let byteCount: Int = toRead * bytesPerFrame @@ -169,11 +169,11 @@ public final class WavFileReader { /// end simply exhausts the reader. /// /// - Parameter frames: Frames to advance by. Non-positive values do nothing. - public func skip(frames: Int) throws { + public func skip(frames: Int) throws(WavFileError) { let toSkip: Int = min(frames, framesRemaining) guard toSkip > 0 else { return } - let current: UInt64 = try handle.offset() - try handle.seek(toOffset: current + UInt64(toSkip * bytesPerFrame)) + let current: UInt64 = try Self.fhOffset(handle) + try Self.fhSeek(handle, to: current + UInt64(toSkip * bytesPerFrame)) framesRemaining -= toSkip } @@ -202,9 +202,30 @@ public final class WavFileReader { } } - private static func readExact(_ h: FileHandle, _ count: Int) throws -> Data { + /// Wraps `FileHandle.offset()`, funneling its foreign error into `WavFileError`. + private static func fhOffset(_ h: FileHandle) throws(WavFileError) -> UInt64 { + do { return try h.offset() } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`. + private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) -> UInt64 { + do { return try h.seekToEnd() } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`. + private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) { + do { try h.seek(toOffset: offset) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + private static func readExact(_ h: FileHandle, _ count: Int) throws(WavFileError) -> Data { guard count > 0 else { return Data() } - guard let d: Data = try h.read(upToCount: count), d.count == count else { + let d: Data? + do { d = try h.read(upToCount: count) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + guard let d, d.count == count else { throw WavFileError.truncated } return d diff --git a/Sources/Lyrebird/Buffers/WavFileWriter.swift b/Sources/Lyrebird/Buffers/WavFileWriter.swift index 13d24d7..e2cb732 100644 --- a/Sources/Lyrebird/Buffers/WavFileWriter.swift +++ b/Sources/Lyrebird/Buffers/WavFileWriter.swift @@ -62,7 +62,7 @@ public final class WavFileWriter { channels: Int, sampleRate: Double, encoding: WavEncoding = .float32 - ) throws { + ) throws(WavFileError) { precondition(channels >= 1, "WavFileWriter requires at least one channel") self.channels = channels self.encoding = encoding @@ -80,8 +80,11 @@ public final class WavFileWriter { guard fm.createFile(atPath: url.path, contents: header) else { throw WavFileError.cannotCreate(url) } - self.handle = try FileHandle(forWritingTo: url) - try handle.seekToEnd() + let h: FileHandle + do { h = try FileHandle(forWritingTo: url) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + self.handle = h + try Self.fhSeekToEnd(h) } /// Appends one block of interleaved `Float` samples. @@ -89,7 +92,7 @@ public final class WavFileWriter { /// - Parameters: /// - samples: Interleaved buffer, length ≥ `frames * channels`. /// - frames: Number of frames (per-channel sample groups) to write. - public func write(interleaved samples: [Float], frames: Int) throws { + public func write(interleaved samples: [Float], frames: Int) throws(WavFileError) { let needed: Int = frames * channels precondition(samples.count >= needed, "interleaved buffer shorter than frames * channels") var out: Data = Data(capacity: needed * encoding.bytesPerSample) @@ -121,7 +124,7 @@ public final class WavFileWriter { out.append(UInt8(truncatingIfNeeded: v >> 16)) } } - try handle.write(contentsOf: out) + try Self.fhWrite(handle, out) dataBytesWritten += out.count } @@ -133,7 +136,7 @@ public final class WavFileWriter { } /// Patches the RIFF and `data` chunk sizes and closes the file. Idempotent. - public func finalize() throws { + public func finalize() throws(WavFileError) { guard !finalized else { return } // Chunks are word-aligned: an odd `data` payload (possible with int24) // needs a pad byte, which counts toward the RIFF size but not the @@ -143,8 +146,8 @@ public final class WavFileWriter { // sizing the file for one. let padByteCount: Int = dataBytesWritten % 2 if padByteCount > 0 && !padByteWritten { - try handle.seekToEnd() - try handle.write(contentsOf: [UInt8(0)]) + try Self.fhSeekToEnd(handle) + try Self.fhWrite(handle, [UInt8(0)]) padByteWritten = true } let riffChunkSize: UInt32 = try Self.riffChunkSize( @@ -153,8 +156,8 @@ public final class WavFileWriter { ) let dataChunkSize: UInt32 = UInt32(dataBytesWritten) - try handle.seek(toOffset: Self.riffChunkSizeOffset) - try handle.write(contentsOf: Self.leBytes(riffChunkSize)) + try Self.fhSeek(handle, to: Self.riffChunkSizeOffset) + try Self.fhWrite(handle, Self.leBytes(riffChunkSize)) if !encoding.isPCM { // `fact` carries the per-channel sample count, which is only known // now that writing has finished. @@ -162,12 +165,12 @@ public final class WavFileWriter { let frames: UInt32 = bytesPerFrame > 0 ? UInt32(dataBytesWritten / bytesPerFrame) : 0 - try handle.seek(toOffset: Self.factSampleCountOffset) - try handle.write(contentsOf: Self.leBytes(frames)) + try Self.fhSeek(handle, to: Self.factSampleCountOffset) + try Self.fhWrite(handle, Self.leBytes(frames)) } - try handle.seek(toOffset: dataChunkSizeOffset) - try handle.write(contentsOf: Self.leBytes(dataChunkSize)) - try handle.close() + try Self.fhSeek(handle, to: dataChunkSizeOffset) + try Self.fhWrite(handle, Self.leBytes(dataChunkSize)) + try Self.fhClose(handle) // Set last: a throw above must leave the writer retryable rather than // latching "finalized" over a file whose sizes are still zero. finalized = true @@ -181,7 +184,7 @@ public final class WavFileWriter { /// /// - Throws: ``WavFileError/fileTooLarge(bytes:)`` past `UInt32.max`. @_spi(LyrebirdExtensions) - public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws -> UInt32 { + public static func riffChunkSize(headerBytes: Int, dataBytes: Int) throws(WavFileError) -> UInt32 { let payload: Int = headerBytes - 8 + dataBytes guard payload <= Int(UInt32.max) else { throw WavFileError.fileTooLarge(bytes: payload) @@ -189,6 +192,38 @@ public final class WavFileWriter { return UInt32(payload) } + // MARK: - FileHandle wrappers (funnel foreign errors into WavFileError) + + /// Wraps `FileHandle.seekToEnd()`, funneling its foreign error into `WavFileError`. + private static func fhSeekToEnd(_ h: FileHandle) throws(WavFileError) { + do { try h.seekToEnd() } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.seek(toOffset:)`, funneling its foreign error into `WavFileError`. + private static func fhSeek(_ h: FileHandle, to offset: UInt64) throws(WavFileError) { + do { try h.seek(toOffset: offset) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.write(contentsOf:)`, funneling its foreign error into `WavFileError`. + private static func fhWrite(_ h: FileHandle, _ bytes: [UInt8]) throws(WavFileError) { + do { try h.write(contentsOf: bytes) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.write(contentsOf:)` for a `Data` payload. + private static func fhWrite(_ h: FileHandle, _ bytes: Data) throws(WavFileError) { + do { try h.write(contentsOf: bytes) } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + + /// Wraps `FileHandle.close()`, funneling its foreign error into `WavFileError`. + private static func fhClose(_ h: FileHandle) throws(WavFileError) { + do { try h.close() } + catch { throw WavFileError.ioFailure(String(describing: error)) } + } + // MARK: - Header private static func makeHeader( diff --git a/Sources/Lyrebird/Buses/BusAllocator.swift b/Sources/Lyrebird/Buses/BusAllocator.swift index b7371ab..fb30790 100644 --- a/Sources/Lyrebird/Buses/BusAllocator.swift +++ b/Sources/Lyrebird/Buses/BusAllocator.swift @@ -76,7 +76,7 @@ public final class BusAllocator: @unchecked Sendable { /// Allocates the first contiguous block of `channelCount` free audio buses. /// Throws `BusAllocatorError.noFreeBus` if no block of that size is available. - public func allocateAudioBus(channelCount: Int) throws -> AudioBus { + public func allocateAudioBus(channelCount: Int) throws(BusAllocatorError) -> AudioBus { let index: Int = try _allocate(in: &audioFreeList, channelCount: channelCount) return AudioBus(index: index, channelCount: channelCount) } @@ -94,7 +94,7 @@ public final class BusAllocator: @unchecked Sendable { /// Allocates the first contiguous block of `channelCount` free control buses. /// Throws `BusAllocatorError.noFreeBus` if no block of that size is available. - public func allocateControlBus(channelCount: Int = 1) throws -> ControlBus { + public func allocateControlBus(channelCount: Int = 1) throws(BusAllocatorError) -> ControlBus { let index: Int = try _allocate(in: &controlFreeList, channelCount: channelCount) return ControlBus(index: index, channelCount: channelCount) } @@ -113,13 +113,15 @@ public final class BusAllocator: @unchecked Sendable { private func _allocate( in freeList: inout [Bool], channelCount: Int - ) throws -> Int { + ) throws(BusAllocatorError) -> Int { precondition(channelCount >= 1, "BusAllocator: channelCount must be >= 1") - return try _lock.withLock { + // The search runs under the lock and returns the start index, or `nil` + // when no block of the requested size is free; the throw happens outside + // the lock because `NSLock.withLock` is `rethrows` and does not narrow to + // the closure's typed error. + let allocated: Int? = _lock.withLock { () -> Int? in let n: Int = freeList.count - guard channelCount <= n else { - throw BusAllocatorError.noFreeBus(channelCount: channelCount) - } + guard channelCount <= n else { return nil } var start: Int = 0 outer: while start <= n - channelCount { for i: Int in start..<(start + channelCount) { @@ -133,8 +135,12 @@ public final class BusAllocator: @unchecked Sendable { } return start } + return nil + } + guard let index: Int = allocated else { throw BusAllocatorError.noFreeBus(channelCount: channelCount) } + return index } /// Marks `[startIndex, startIndex + channelCount)` slots back to free. When diff --git a/Sources/Lyrebird/Engine/SynthesisEngine.swift b/Sources/Lyrebird/Engine/SynthesisEngine.swift index 6b81ca8..1ede646 100644 --- a/Sources/Lyrebird/Engine/SynthesisEngine.swift +++ b/Sources/Lyrebird/Engine/SynthesisEngine.swift @@ -41,6 +41,30 @@ import Synchronization /// it is callable from any non-RT thread. From a `LyrebirdRoutine` / `LyrebirdTask` body, go /// through the context (``LyrebirdRoutineContext/add(_:)``, which dispatches to main) rather /// than calling the engine directly. See `ARCHITECTURE.md` §1 and §9. +/// +/// **Deliberately NOT `Sendable`.** This was evaluated and rejected on purpose: +/// - *Checked* `Sendable` is infeasible — the engine holds mutable per-block RT +/// state (node tree, bus memory, block cursors) whose safety comes from the +/// architecture (single-producer `pendingQueue`, atomics, the render-callback +/// happens-before barrier), not from the type system. Those fields cannot be +/// made Sendable-clean without dismantling the RT design. +/// - *`@unchecked`* `Sendable` would be a blanket "safe to share across threads" +/// assertion that is only true for *specific* access patterns (main-thread +/// mutation via the queue; RT-thread reads in `processBlock`) and false for +/// others (mutating config while running, or touching the engine from the RT +/// thread). Declaring it would erase the compiler friction that currently +/// forces each genuine cross-thread transfer to be spelled `nonisolated(unsafe)` +/// at the call site — and those few sites (e.g. `LyrebirdAudioUnit` config +/// hand-off, a UI closure capture) are a *feature*: each is a visible, reviewed +/// "verified safe here" marker on the most concurrency-sensitive object in the +/// system. +/// +/// The cost of staying non-Sendable is tiny (a handful of `nonisolated(unsafe)` +/// captures) and the benefit is real (no false safety guarantee, every transfer +/// stays auditable). Classes that hold an engine reference therefore remain +/// `@unchecked Sendable` themselves, keeping their own mutable state in a `Mutex` +/// and naming the engine reference as the sole hand-verified item. Do not add a +/// `Sendable` conformance here without re-opening that trade-off. public final class SynthesisEngine { /// Process-unique identity. Used by the engine ownership-binding system @@ -960,7 +984,7 @@ public final class SynthesisEngine { /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` if the engine is /// currently running; ``SynthesisEngineConfigError/invalidValue(_:)`` if /// `rate` is non-finite or `<= 0`. - public func setSampleRate(_ rate: Double) throws { + public func setSampleRate(_ rate: Double) throws(SynthesisEngineConfigError) { guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard rate.isFinite, rate > 0 else { throw SynthesisEngineConfigError.invalidValue( @@ -982,7 +1006,7 @@ public final class SynthesisEngine { /// `numAudioBuses`. /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` / /// ``SynthesisEngineConfigError/invalidValue(_:)``. - public func setNumOutputChannels(_ count: Int) throws { + public func setNumOutputChannels(_ count: Int) throws(SynthesisEngineConfigError) { guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard count >= 1 else { throw SynthesisEngineConfigError.invalidValue( @@ -1013,7 +1037,7 @@ public final class SynthesisEngine { /// `numAudioBuses` together with `numOutputChannels`. /// - Throws: ``SynthesisEngineConfigError/engineIsRunning`` / /// ``SynthesisEngineConfigError/invalidValue(_:)``. - public func setNumInputChannels(_ count: Int) throws { + public func setNumInputChannels(_ count: Int) throws(SynthesisEngineConfigError) { guard !isRunning else { throw SynthesisEngineConfigError.engineIsRunning } guard count >= 0 else { throw SynthesisEngineConfigError.invalidValue( @@ -1410,7 +1434,7 @@ public final class SynthesisEngine { @MainActor public func schedule( _ synth: any Synthesizer, at time: SampleTime - ) throws { + ) throws(EngineAddError) { precondition( synth !== rootGroup && synth !== mainGroup, "Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" @@ -1439,7 +1463,7 @@ public final class SynthesisEngine { @MainActor public func schedule( _ synth: any Synthesizer, after seconds: Double - ) throws { + ) throws(EngineAddError) { precondition( synth !== rootGroup && synth !== mainGroup, "Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" @@ -1509,7 +1533,7 @@ public final class SynthesisEngine { /// Equivalent to `schedule(_:at:currentTime)`. The synthesizer lands at the head of /// `mainGroup` — newest-first order. Safe to call from the main thread. /// - Throws: `EngineAddError` — see `schedule(_:at:)` for cases. - @MainActor public func add(_ synth: any Synthesizer) throws { + @MainActor public func add(_ synth: any Synthesizer) throws(EngineAddError) { try schedule(synth, at: currentTime) } @@ -1526,7 +1550,7 @@ public final class SynthesisEngine { @MainActor public func add( _ synth: any Synthesizer, position: NodePosition - ) throws { + ) throws(EngineAddError) { precondition( synth !== rootGroup && synth !== mainGroup, "Cannot add the engine's persistent rootGroup or mainGroup as a child Synthesizer" diff --git a/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift b/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift index b1add78..c2e1c81 100644 --- a/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift +++ b/Sources/Lyrebird/Generators/Spectral/AdditiveSynthesizer.swift @@ -61,10 +61,10 @@ public final class Audio: GeneratorBase, AudioGenerator { // MARK: - RT-only working storage (UnsafeMutablePointer — no CoW, no ARC) - private let _interpMag: UnsafeMutablePointer // [halfSize]; index 0 unused - private let _phases: UnsafeMutablePointer // [halfSize]; index 0 unused - private let _phaseIncrements: UnsafeMutablePointer // [halfSize]; index 0 unused - private let _sinBuf: UnsafeMutablePointer // [halfSize]; scratch for vvsinf + private let _interpMag: RTScratchBuffer // [halfSize]; index 0 unused + private let _phases: RTScratchBuffer // [halfSize]; index 0 unused + private let _phaseIncrements: RTScratchBuffer // [halfSize]; index 0 unused + private let _sinBuf: RTScratchBuffer // [halfSize]; scratch for vvsinf // MARK: - Generator output buffer @@ -103,29 +103,15 @@ public final class Audio: GeneratorBase, AudioGenerator { let cappedPartials: Int = maxPartials > 0 ? min(maxPartials, binCount) : binCount _activePartials = cappedPartials - _interpMag = UnsafeMutablePointer.allocate(capacity: hs) - _phases = UnsafeMutablePointer.allocate(capacity: hs) - _phaseIncrements = UnsafeMutablePointer.allocate(capacity: hs) - _sinBuf = UnsafeMutablePointer.allocate(capacity: hs) + _interpMag = RTScratchBuffer(count: hs) + _phases = RTScratchBuffer(count: hs) + _phaseIncrements = RTScratchBuffer(count: hs) + _sinBuf = RTScratchBuffer(count: hs) - _interpMag.initialize(repeating: 0, count: hs) - _phases.initialize(repeating: 0, count: hs) - _phaseIncrements.initialize(repeating: 0, count: hs) - _sinBuf.initialize(repeating: 0, count: hs) _mulAdd = MulAddSpec(mul: mul, add: add) } - deinit { - let hs: Int = _halfSize - _interpMag.deinitialize(count: hs) - _interpMag.deallocate() - _phases.deinitialize(count: hs) - _phases.deallocate() - _phaseIncrements.deinitialize(count: hs) - _phaseIncrements.deallocate() - _sinBuf.deinitialize(count: hs) - _sinBuf.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - AudioGenerator public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] { @@ -164,7 +150,7 @@ public final class Audio: GeneratorBase, AudioGenerator { // Magnitude interpolation once per block — not per sample. _frameBuffer.interpolateMagnitudes( - into: _interpMag, + into: _interpMag.baseAddress, frameA: frameA, frameB: frameB, frac: frac @@ -191,19 +177,19 @@ public final class Audio: GeneratorBase, AudioGenerator { for i: Int in 0.. - private let _prevPhase: UnsafeMutablePointer - private let _prevPrevPhase: UnsafeMutablePointer + private let _prevMag: RTScratchBuffer + private let _prevPhase: RTScratchBuffer + private let _prevPrevPhase: RTScratchBuffer /// Scratch buffers for vectorised complex-domain trig. Allocated only when /// `method == .complexDomain` (zero-overhead pointer when unused). Each /// buffer is `halfSize` long; complex bins live at indices `1.. - private let _predPhaseScratch: UnsafeMutablePointer - private let _curCosBuf: UnsafeMutablePointer - private let _curSinBuf: UnsafeMutablePointer - private let _predCosBuf: UnsafeMutablePointer - private let _predSinBuf: UnsafeMutablePointer - private let _trigScratchCount: Int // 0 when unused, halfSize when method == .complexDomain + private let _curPhaseScratch: RTScratchBuffer + private let _predPhaseScratch: RTScratchBuffer + private let _curCosBuf: RTScratchBuffer + private let _curSinBuf: RTScratchBuffer + private let _predCosBuf: RTScratchBuffer + private let _predSinBuf: RTScratchBuffer // MARK: - Median ring (RT thread only) - private let _odfRing: UnsafeMutablePointer - private let _medianScratch: UnsafeMutablePointer + private let _odfRing: RTScratchBuffer + private let _medianScratch: RTScratchBuffer private var _odfRingIndex: Int = 0 // MARK: - Counters (RT thread only) @@ -197,7 +195,6 @@ public final class OnsetDetector: SpectralProcessor { "OnsetDetector: minHopsBetweenOnsets must be >= 0, got \(minHopsBetweenOnsets)") let halfSize: Int = fftSize / 2 - _halfSize = halfSize _binCount = halfSize - 1 _method = method _medianWindowFrames = medianWindowFrames @@ -208,34 +205,22 @@ public final class OnsetDetector: SpectralProcessor { _lastMedianAtomic = Atomic(Float(0)) _onsetSerial = Atomic(0) - _prevMag = UnsafeMutablePointer.allocate(capacity: halfSize) - _prevMag.initialize(repeating: 0, count: halfSize) - _prevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _prevPhase.initialize(repeating: 0, count: halfSize) - _prevPrevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _prevPrevPhase.initialize(repeating: 0, count: halfSize) + _prevMag = RTScratchBuffer(count: halfSize) + _prevPhase = RTScratchBuffer(count: halfSize) + _prevPrevPhase = RTScratchBuffer(count: halfSize) - _odfRing = UnsafeMutablePointer.allocate(capacity: medianWindowFrames) - _odfRing.initialize(repeating: 0, count: medianWindowFrames) - _medianScratch = UnsafeMutablePointer.allocate(capacity: medianWindowFrames) - _medianScratch.initialize(repeating: 0, count: medianWindowFrames) + _odfRing = RTScratchBuffer(count: medianWindowFrames) + _medianScratch = RTScratchBuffer(count: medianWindowFrames) // Trig scratch is only required for `.complexDomain`. Allocate one slot - // when unused so the stored properties always reference valid memory. + // when unused so the stored buffers always reference valid memory. let trigCount: Int = (method == .complexDomain) ? halfSize : 1 - _trigScratchCount = (method == .complexDomain) ? halfSize : 0 - _curPhaseScratch = UnsafeMutablePointer.allocate(capacity: trigCount) - _curPhaseScratch.initialize(repeating: 0, count: trigCount) - _predPhaseScratch = UnsafeMutablePointer.allocate(capacity: trigCount) - _predPhaseScratch.initialize(repeating: 0, count: trigCount) - _curCosBuf = UnsafeMutablePointer.allocate(capacity: trigCount) - _curCosBuf.initialize(repeating: 0, count: trigCount) - _curSinBuf = UnsafeMutablePointer.allocate(capacity: trigCount) - _curSinBuf.initialize(repeating: 0, count: trigCount) - _predCosBuf = UnsafeMutablePointer.allocate(capacity: trigCount) - _predCosBuf.initialize(repeating: 0, count: trigCount) - _predSinBuf = UnsafeMutablePointer.allocate(capacity: trigCount) - _predSinBuf.initialize(repeating: 0, count: trigCount) + _curPhaseScratch = RTScratchBuffer(count: trigCount) + _predPhaseScratch = RTScratchBuffer(count: trigCount) + _curCosBuf = RTScratchBuffer(count: trigCount) + _curSinBuf = RTScratchBuffer(count: trigCount) + _predCosBuf = RTScratchBuffer(count: trigCount) + _predSinBuf = RTScratchBuffer(count: trigCount) _warmupRemaining = medianWindowFrames // Init high so the first post-warmup onset is never blocked by the @@ -243,32 +228,8 @@ public final class OnsetDetector: SpectralProcessor { _hopsSinceLastOnset = Int.max / 2 } - deinit { - _prevMag.deinitialize(count: _halfSize) - _prevMag.deallocate() - _prevPhase.deinitialize(count: _halfSize) - _prevPhase.deallocate() - _prevPrevPhase.deinitialize(count: _halfSize) - _prevPrevPhase.deallocate() - _odfRing.deinitialize(count: _medianWindowFrames) - _odfRing.deallocate() - _medianScratch.deinitialize(count: _medianWindowFrames) - _medianScratch.deallocate() - - let trigCount: Int = max(_trigScratchCount, 1) - _curPhaseScratch.deinitialize(count: trigCount) - _curPhaseScratch.deallocate() - _predPhaseScratch.deinitialize(count: trigCount) - _predPhaseScratch.deallocate() - _curCosBuf.deinitialize(count: trigCount) - _curCosBuf.deallocate() - _curSinBuf.deinitialize(count: trigCount) - _curSinBuf.deallocate() - _predCosBuf.deinitialize(count: trigCount) - _predCosBuf.deallocate() - _predSinBuf.deinitialize(count: trigCount) - _predSinBuf.deallocate() - } + // No deinit: each `RTScratchBuffer` frees its own allocation exactly once when + // this object is deallocated (off the RT thread, via the engine's free queue). // MARK: - SpectralProcessor @@ -371,8 +332,8 @@ public final class OnsetDetector: SpectralProcessor { } var n: Int32 = Int32(binCount) - vvsincosf(_curSinBuf, _curCosBuf, _curPhaseScratch, &n) - vvsincosf(_predSinBuf, _predCosBuf, _predPhaseScratch, &n) + vvsincosf(_curSinBuf.baseAddress, _curCosBuf.baseAddress, _curPhaseScratch.baseAddress, &n) + vvsincosf(_predSinBuf.baseAddress, _predCosBuf.baseAddress, _predPhaseScratch.baseAddress, &n) for i: Int in 0.. + private let _delayFramesScratch: RTScratchBuffer /// Pre-allocated scratch for the per-hop snapshot of feedbacks. - private let _feedbackScratch: UnsafeMutablePointer + private let _feedbackScratch: RTScratchBuffer /// Conversion factor: hop-frames per second of delay time. `sampleRate / hopSize`. private let _framesPerSecond: Double // MARK: - Ring storage (rectangular) - private let _ringReal: UnsafeMutablePointer - private let _ringImag: UnsafeMutablePointer + private let _ringReal: RTScratchBuffer + private let _ringImag: RTScratchBuffer /// Head index in the ring. Decrements (with wrap) once per `process()` call; /// matches SC's `m_curFrame` convention so `delFrame = head + offset` reads @@ -149,29 +149,15 @@ public final class SpectralBinDelay: SpectralProcessor { _framesPerSecond = framesPerSecond _head = 0 - _delayFramesScratch = UnsafeMutablePointer.allocate(capacity: halfSize) - _delayFramesScratch.initialize(repeating: 0, count: halfSize) - _feedbackScratch = UnsafeMutablePointer.allocate(capacity: halfSize) - _feedbackScratch.initialize(repeating: 0, count: halfSize) + _delayFramesScratch = RTScratchBuffer(count: halfSize) + _feedbackScratch = RTScratchBuffer(count: halfSize) let ringCells: Int = halfSize * numFrames - _ringReal = UnsafeMutablePointer.allocate(capacity: ringCells) - _ringReal.initialize(repeating: 0, count: ringCells) - _ringImag = UnsafeMutablePointer.allocate(capacity: ringCells) - _ringImag.initialize(repeating: 0, count: ringCells) + _ringReal = RTScratchBuffer(count: ringCells) + _ringImag = RTScratchBuffer(count: ringCells) } - deinit { - _delayFramesScratch.deinitialize(count: _halfSize) - _delayFramesScratch.deallocate() - _feedbackScratch.deinitialize(count: _halfSize) - _feedbackScratch.deallocate() - let ringCells: Int = _halfSize * _numFrames - _ringReal.deinitialize(count: ringCells) - _ringReal.deallocate() - _ringImag.deinitialize(count: ringCells) - _ringImag.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - SpectralProcessor diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift index 85934a0..4d3a614 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBlur.swift @@ -32,7 +32,7 @@ public final class SpectralBlur: SpectralProcessor { private let _binCount: Int private let _radius: Atomic - private let _blurOut: UnsafeMutablePointer // [_binCount] + private let _blurOut: RTScratchBuffer // [_binCount] /// Half-window radius in bins. Updates take effect on the next hop. Clamped /// to `[0, halfSize / 2]`. @@ -62,15 +62,10 @@ public final class SpectralBlur: SpectralProcessor { _radius = Atomic(clamped) let allocCount: Int = max(_binCount, 1) - _blurOut = UnsafeMutablePointer.allocate(capacity: allocCount) - _blurOut.initialize(repeating: 0, count: allocCount) + _blurOut = RTScratchBuffer(count: allocCount) } - deinit { - let allocCount: Int = max(_binCount, 1) - _blurOut.deinitialize(count: allocCount) - _blurOut.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. public func process(spectral: SpectralBuffer, engine: SynthesisEngine) { guard spectral.fftSize == _fftSize else { return } @@ -106,7 +101,7 @@ public final class SpectralBlur: SpectralProcessor { _blurOut[i] = sum / Float(count) } // Copy averaged result back. - mp.update(from: _blurOut, count: n) + mp.update(from: _blurOut.baseAddress, count: n) } // DC and Nyquist are not blurred — they have no neighbours in this layout. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift b/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift index 1ef63a0..3907a90 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralBufferRead.swift @@ -69,10 +69,9 @@ public final class SpectralBufferRead: GeneratorBase, AudioGenerator, SpectralBu // MARK: - Working storage (all [halfSize]; index 0 unused) - private let _halfSize: Int private let _binCount: Int // halfSize - 1 - private let _interpMag: UnsafeMutablePointer // interpolated magnitude scratch - private let _interpPhase: UnsafeMutablePointer // interpolated phase scratch + private let _interpMag: RTScratchBuffer // interpolated magnitude scratch + private let _interpPhase: RTScratchBuffer // interpolated phase scratch // MARK: - Generator protocol storage @@ -103,24 +102,16 @@ public final class SpectralBufferRead: GeneratorBase, AudioGenerator, SpectralBu _position = resolvedPosition let hs: Int = fftSize / 2 - _halfSize = hs _binCount = hs - 1 spectralBuffer = SpectralBuffer(fftSize: fftSize) let ptrSize: Int = hs - _interpMag = UnsafeMutablePointer.allocate(capacity: ptrSize) - _interpPhase = UnsafeMutablePointer.allocate(capacity: ptrSize) - _interpMag.initialize(repeating: 0, count: ptrSize) - _interpPhase.initialize(repeating: 0, count: ptrSize) + _interpMag = RTScratchBuffer(count: ptrSize) + _interpPhase = RTScratchBuffer(count: ptrSize) } - deinit { - _interpMag.deinitialize(count: _halfSize) - _interpMag.deallocate() - _interpPhase.deinitialize(count: _halfSize) - _interpPhase.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - AudioGenerator public func _computeSamples( @@ -161,13 +152,13 @@ public final class SpectralBufferRead: GeneratorBase, AudioGenerator, SpectralBu // Interpolate magnitudes using vDSP_vintb. _frameBuffer.interpolateMagnitudes( - into: _interpMag, + into: _interpMag.baseAddress, frameA: frameA, frameB: frameB, frac: frac ) // Interpolate stored analysis phases using shortest-path lerp. _frameBuffer.interpolatePhases( - into: _interpPhase, + into: _interpPhase.baseAddress, frameA: frameA, frameB: frameB, frac: frac ) @@ -182,10 +173,10 @@ public final class SpectralBufferRead: GeneratorBase, AudioGenerator, SpectralBu // Write magnitudes and phases into spectralBuffer. spectralBuffer.withUnsafeMutableMagnitudePointer { dst in - dst.update(from: _interpMag + 1, count: _binCount) + dst.update(from: _interpMag.baseAddress + 1, count: _binCount) } spectralBuffer.withUnsafeMutablePhasePointer { dst in - dst.update(from: _interpPhase + 1, count: _binCount) + dst.update(from: _interpPhase.baseAddress + 1, count: _binCount) } } } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift index 67801cf..91607d9 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralComplexClosure.swift @@ -163,8 +163,8 @@ public final class SpectralComplexClosure: SpectralProcessor { // Pre-allocated split-complex scratch. Length = halfSize each. // Used as the mutable Cartesian buffers exposed in SpectralComplexContext. - private let _real: UnsafeMutablePointer - private let _imag: UnsafeMutablePointer + private let _real: RTScratchBuffer + private let _imag: RTScratchBuffer /// - Parameters: /// - fftSize: Must match the paired `SpectralChain.Audio.fftSize`. @@ -189,18 +189,11 @@ public final class SpectralComplexClosure: SpectralProcessor { _halfSize = fftSize / 2 _body = body - _real = UnsafeMutablePointer.allocate(capacity: _halfSize) - _imag = UnsafeMutablePointer.allocate(capacity: _halfSize) - _real.initialize(repeating: 0, count: _halfSize) - _imag.initialize(repeating: 0, count: _halfSize) + _real = RTScratchBuffer(count: _halfSize) + _imag = RTScratchBuffer(count: _halfSize) } - deinit { - _real.deinitialize(count: _halfSize) - _real.deallocate() - _imag.deinitialize(count: _halfSize) - _imag.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. /// RT-safe. Converts `spectral` from polar to split-complex, invokes the /// closure, then converts back to polar and writes the result into `spectral`. @@ -220,11 +213,11 @@ public final class SpectralComplexClosure: SpectralProcessor { // Step 1: polar → split-complex into pre-allocated scratch. // _readToRectangular writes DC to _real[0], Nyquist to _imag[0], and // complex bin data to _real[1.. = UnsafeMutableBufferPointer(start: _real, count: _halfSize) - let imagBuf: UnsafeMutableBufferPointer = UnsafeMutableBufferPointer(start: _imag, count: _halfSize) + let realBuf: UnsafeMutableBufferPointer = UnsafeMutableBufferPointer(start: _real.baseAddress, count: _halfSize) + let imagBuf: UnsafeMutableBufferPointer = UnsafeMutableBufferPointer(start: _imag.baseAddress, count: _halfSize) let ctx: SpectralComplexContext = SpectralComplexContext( real: realBuf, @@ -240,7 +233,7 @@ public final class SpectralComplexClosure: SpectralProcessor { // Step 3: split-complex → polar, writing result back into spectral. // _writeFromRectangular reads DC from _real[0], Nyquist from _imag[0], // and reconstructs polar magnitudes + phases for all complex bins. - spectral._writeFromRectangular(_real, imagp: _imag) + spectral._writeFromRectangular(_real.baseAddress, imagp: _imag.baseAddress) _frameIndex += 1 } diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift b/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift index 59d6138..4629631 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralCrossMap.swift @@ -96,7 +96,7 @@ public final class SpectralCrossMap: SpectralProcessor2 { // MARK: - Captured template /// Per-bin template gain captured (or held while frozen). RT thread only. - private let _templateMag: UnsafeMutablePointer + private let _templateMag: RTScratchBuffer // MARK: - Initialisation @@ -140,14 +140,10 @@ public final class SpectralCrossMap: SpectralProcessor2 { _floor = Atomic(Float(floor)) _mode = Atomic(Float(mode)) - _templateMag = UnsafeMutablePointer.allocate(capacity: _halfSize) - _templateMag.initialize(repeating: 0, count: _halfSize) + _templateMag = RTScratchBuffer(count: _halfSize) } - deinit { - _templateMag.deinitialize(count: _halfSize) - _templateMag.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - SpectralProcessor2 diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift index 1ea986b..2cb90ab 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFormantShift.swift @@ -96,17 +96,17 @@ public final class SpectralFormantShift: SpectralProcessor { /// Working magnitude buffer (`|DC|`, complex-bin mags, `|Nyquist|`). /// Length `halfSize + 1`. - private let _magSource: UnsafeMutablePointer + private let _magSource: RTScratchBuffer /// Smooth envelope produced by the estimator. Length `halfSize + 1`. - private let _envelope: UnsafeMutablePointer + private let _envelope: RTScratchBuffer /// Whitened residual `magSource / (envelope + ε)`. Length `halfSize + 1`. - private let _residual: UnsafeMutablePointer + private let _residual: RTScratchBuffer /// Envelope resampled along the bin axis by `shiftRatio`. Length /// `halfSize + 1`. - private let _newEnvelope: UnsafeMutablePointer + private let _newEnvelope: RTScratchBuffer /// - Parameters: /// - fftSize: Must match the paired `SpectralChain.Audio.fftSize`. Power of two ≥ 4. @@ -153,27 +153,13 @@ public final class SpectralFormantShift: SpectralProcessor { } let n: Int = _halfSize + 1 - _magSource = UnsafeMutablePointer.allocate(capacity: n) - _envelope = UnsafeMutablePointer.allocate(capacity: n) - _residual = UnsafeMutablePointer.allocate(capacity: n) - _newEnvelope = UnsafeMutablePointer.allocate(capacity: n) - _magSource.initialize(repeating: 0, count: n) - _envelope.initialize(repeating: 0, count: n) - _residual.initialize(repeating: 0, count: n) - _newEnvelope.initialize(repeating: 0, count: n) + _magSource = RTScratchBuffer(count: n) + _envelope = RTScratchBuffer(count: n) + _residual = RTScratchBuffer(count: n) + _newEnvelope = RTScratchBuffer(count: n) } - deinit { - let n: Int = _halfSize + 1 - _magSource.deinitialize(count: n) - _magSource.deallocate() - _envelope.deinitialize(count: n) - _envelope.deallocate() - _residual.deinitialize(count: n) - _residual.deallocate() - _newEnvelope.deinitialize(count: n) - _newEnvelope.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. public func process(spectral: SpectralBuffer, engine: SynthesisEngine) { guard spectral.fftSize == _fftSize else { return } @@ -202,9 +188,9 @@ public final class SpectralFormantShift: SpectralProcessor { // Estimate the smooth envelope. if let estimator: CepstralEnvelopeEstimator = _estimator { - estimator.estimate(magnitudes: _magSource, into: _envelope) + estimator.estimate(magnitudes: _magSource.baseAddress, into: _envelope.baseAddress) } else { - _boxSmooth(_magSource, into: _envelope, n: n, radius: _smoothingRadius) + _boxSmooth(_magSource.baseAddress, into: _envelope.baseAddress, n: n, radius: _smoothingRadius) } // Whiten: residual = magSource / (envelope + ε). diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift index 4151e4a..a4a6667 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralFreeze.swift @@ -48,10 +48,10 @@ public final class SpectralFreeze: SpectralProcessor { private let _halfSize: Int private let _binCount: Int // halfSize − 1 (complex bins 1..halfSize-1) - private let _prevPhase: UnsafeMutablePointer // [halfSize] — phase at previous hop - private let _phaseDelta: UnsafeMutablePointer// [halfSize] — principal phase increment per hop - private let _frozenMag: UnsafeMutablePointer // [halfSize] — frozen magnitudes (index 1+) - private let _frozenPhase: UnsafeMutablePointer// [halfSize] — running phase accumulator + private let _prevPhase: RTScratchBuffer // [halfSize] — phase at previous hop + private let _phaseDelta: RTScratchBuffer// [halfSize] — principal phase increment per hop + private let _frozenMag: RTScratchBuffer // [halfSize] — frozen magnitudes (index 1+) + private let _frozenPhase: RTScratchBuffer// [halfSize] — running phase accumulator // MARK: - Public state @@ -71,27 +71,14 @@ public final class SpectralFreeze: SpectralProcessor { _isFrozen = Atomic(false) _freezeRequested = Atomic(false) - _prevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _phaseDelta = UnsafeMutablePointer.allocate(capacity: halfSize) - _frozenMag = UnsafeMutablePointer.allocate(capacity: halfSize) - _frozenPhase = UnsafeMutablePointer.allocate(capacity: halfSize) + _prevPhase = RTScratchBuffer(count: halfSize) + _phaseDelta = RTScratchBuffer(count: halfSize) + _frozenMag = RTScratchBuffer(count: halfSize) + _frozenPhase = RTScratchBuffer(count: halfSize) - _prevPhase.initialize(repeating: 0, count: halfSize) - _phaseDelta.initialize(repeating: 0, count: halfSize) - _frozenMag.initialize(repeating: 0, count: halfSize) - _frozenPhase.initialize(repeating: 0, count: halfSize) } - deinit { - _prevPhase.deinitialize(count: _halfSize) - _prevPhase.deallocate() - _phaseDelta.deinitialize(count: _halfSize) - _phaseDelta.deallocate() - _frozenMag.deinitialize(count: _halfSize) - _frozenMag.deallocate() - _frozenPhase.deinitialize(count: _halfSize) - _frozenPhase.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - Non-RT control @@ -206,9 +193,9 @@ public final class SpectralFreeze: SpectralProcessor { let n: vDSP_Length = vDSP_Length(_binCount) // All three pointers pre-advanced past index 0 (unused); fp[i]/pd[i]/fm[i] == bin (i+1). - let fp: UnsafeMutablePointer = _frozenPhase.advanced(by: 1) - let pd: UnsafeMutablePointer = _phaseDelta.advanced(by: 1) - let fm: UnsafeMutablePointer = _frozenMag.advanced(by: 1) + let fp: UnsafeMutablePointer = _frozenPhase.baseAddress.advanced(by: 1) + let pd: UnsafeMutablePointer = _phaseDelta.baseAddress.advanced(by: 1) + let fm: UnsafeMutablePointer = _frozenMag.baseAddress.advanced(by: 1) // Advance phase: frozenPhase[k] += phaseDelta[k] vDSP_vadd(fp, 1, pd, 1, fp, 1, n) diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift b/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift index 18411ed..5e82138 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralNoiseFilter.swift @@ -65,8 +65,8 @@ public final class SpectralNoiseFilter: SpectralProcessor { // MARK: - Per-bin state - private let _prevPhase: UnsafeMutablePointer - private let _history: UnsafeMutablePointer + private let _prevPhase: RTScratchBuffer + private let _history: RTScratchBuffer private var _curFrame: Int = 0 private var _warmupRemaining: Int @@ -107,22 +107,15 @@ public final class SpectralNoiseFilter: SpectralProcessor { _threshold = Atomic(Float(threshold)) - _prevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _prevPhase.initialize(repeating: 0, count: halfSize) + _prevPhase = RTScratchBuffer(count: halfSize) let historyCount: Int = halfSize * numFrames - _history = UnsafeMutablePointer.allocate(capacity: historyCount) - _history.initialize(repeating: 0, count: historyCount) + _history = RTScratchBuffer(count: historyCount) _warmupRemaining = numFrames } - deinit { - _prevPhase.deinitialize(count: _halfSize) - _prevPhase.deallocate() - _history.deinitialize(count: _halfSize * _numFrames) - _history.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - SpectralProcessor diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift index 625c32c..8916216 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPartialFilter.swift @@ -77,12 +77,12 @@ public final class SpectralPartialFilter: SpectralProcessor { // MARK: - Per-bin state (RT thread only) /// Phase at the previous hop. `[halfSize]`, index 0 unused. - private let _prevPhase: UnsafeMutablePointer + private let _prevPhase: RTScratchBuffer /// Ring of per-bin metric history. Layout: `_history[bin * numFrames + frame]` /// where `bin ∈ 1.. + private let _history: RTScratchBuffer /// Ring write index. Advanced once per `process()` call. private var _curFrame: Int = 0 @@ -133,22 +133,15 @@ public final class SpectralPartialFilter: SpectralProcessor { _threshold = Atomic(Float(threshold)) - _prevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _prevPhase.initialize(repeating: 0, count: halfSize) + _prevPhase = RTScratchBuffer(count: halfSize) let historyCount: Int = halfSize * numFrames - _history = UnsafeMutablePointer.allocate(capacity: historyCount) - _history.initialize(repeating: 0, count: historyCount) + _history = RTScratchBuffer(count: historyCount) _warmupRemaining = numFrames } - deinit { - _prevPhase.deinitialize(count: _halfSize) - _prevPhase.deallocate() - _history.deinitialize(count: _halfSize * _numFrames) - _history.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - SpectralProcessor diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift index 2a4079d..c9b2bf7 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPitchShift.swift @@ -60,16 +60,16 @@ public final class SpectralPitchShift: SpectralProcessor { // MARK: - Per-bin state (all [halfSize], index 0 unused; bins 1 ..< halfSize) /// Phase at the previous hop — used to compute instantaneous frequency deviation. - private let _prevPhase: UnsafeMutablePointer + private let _prevPhase: RTScratchBuffer /// Synthesis phase accumulator — advanced by the true-frequency-scaled step each hop. - private let _synthPhase: UnsafeMutablePointer + private let _synthPhase: RTScratchBuffer /// Scratch buffer for remapped magnitudes. Zeroed before each hop's accumulation pass. - private let _shiftedMag: UnsafeMutablePointer + private let _shiftedMag: RTScratchBuffer /// True-frequency bin `k + deviation / (2π/hop)` computed in Pass 1 and read in Pass 2. - private let _trueFreqBin: UnsafeMutablePointer + private let _trueFreqBin: RTScratchBuffer // MARK: - Initialisation @@ -96,27 +96,13 @@ public final class SpectralPitchShift: SpectralProcessor { _pitchRatio = Atomic(Float(pitchRatio)) - _prevPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _synthPhase = UnsafeMutablePointer.allocate(capacity: halfSize) - _shiftedMag = UnsafeMutablePointer.allocate(capacity: halfSize) - _trueFreqBin = UnsafeMutablePointer.allocate(capacity: halfSize) - - _prevPhase.initialize(repeating: 0, count: halfSize) - _synthPhase.initialize(repeating: 0, count: halfSize) - _shiftedMag.initialize(repeating: 0, count: halfSize) - _trueFreqBin.initialize(repeating: 0, count: halfSize) + _prevPhase = RTScratchBuffer(count: halfSize) + _synthPhase = RTScratchBuffer(count: halfSize) + _shiftedMag = RTScratchBuffer(count: halfSize) + _trueFreqBin = RTScratchBuffer(count: halfSize) } - deinit { - _prevPhase.deinitialize(count: _halfSize) - _prevPhase.deallocate() - _synthPhase.deinitialize(count: _halfSize) - _synthPhase.deallocate() - _shiftedMag.deinitialize(count: _halfSize) - _shiftedMag.deallocate() - _trueFreqBin.deinitialize(count: _halfSize) - _trueFreqBin.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - SpectralProcessor @@ -131,7 +117,7 @@ public final class SpectralPitchShift: SpectralProcessor { let twoPi: Float = 2 * Float.pi // Zero the magnitude scratch so out-of-range bins stay silent. - vDSP_vclr(_shiftedMag, 1, vDSP_Length(_halfSize)) + vDSP_vclr(_shiftedMag.baseAddress, 1, vDSP_Length(_halfSize)) // Pass 1: compute true-frequency bins and remap magnitudes. // pp[i] == _phase[i+1] == bin (i+1) phase; mp[i] == _mag[i+1] == bin (i+1) magnitude. @@ -182,10 +168,10 @@ public final class SpectralPitchShift: SpectralProcessor { // Write remapped magnitudes and synthesis phases back to spectral buffer. spectral.withUnsafeMutableMagnitudePointer { mp in - mp.update(from: _shiftedMag.advanced(by: 1), count: _binCount) + mp.update(from: _shiftedMag.baseAddress.advanced(by: 1), count: _binCount) } spectral.withUnsafeMutablePhasePointer { pp in - pp.update(from: _synthPhase.advanced(by: 1), count: _binCount) + pp.update(from: _synthPhase.baseAddress.advanced(by: 1), count: _binCount) } // DC and Nyquist: pitch shift moves them out of their fixed-frequency slots, // so pass them through as zero (avoids spectral splatter at DC / Nyquist). diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift b/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift index 37e2cb1..20d0621 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralPlayBuffer.swift @@ -93,9 +93,9 @@ public final class SpectralPlayBuffer: GeneratorBase, AudioGenerator, SpectralBu private let _halfSize: Int private let _binCount: Int // halfSize - 1 - private let _synthPhase: UnsafeMutablePointer // synthesis phase accumulator - private let _interpMag: UnsafeMutablePointer // interpolated magnitudes scratch - private let _phaseDelta: UnsafeMutablePointer // inter-frame phase delta scratch + private let _synthPhase: RTScratchBuffer // synthesis phase accumulator + private let _interpMag: RTScratchBuffer // interpolated magnitudes scratch + private let _phaseDelta: RTScratchBuffer // inter-frame phase delta scratch // MARK: - Generator protocol storage @@ -143,26 +143,16 @@ public final class SpectralPlayBuffer: GeneratorBase, AudioGenerator, SpectralBu spectralBuffer = SpectralBuffer(fftSize: fftSize) let ptrSize: Int = hs - _synthPhase = UnsafeMutablePointer.allocate(capacity: ptrSize) - _interpMag = UnsafeMutablePointer.allocate(capacity: ptrSize) - _phaseDelta = UnsafeMutablePointer.allocate(capacity: ptrSize) - _synthPhase.initialize(repeating: 0, count: ptrSize) - _interpMag.initialize(repeating: 0, count: ptrSize) - _phaseDelta.initialize(repeating: 0, count: ptrSize) + _synthPhase = RTScratchBuffer(count: ptrSize) + _interpMag = RTScratchBuffer(count: ptrSize) + _phaseDelta = RTScratchBuffer(count: ptrSize) _playPos = startPos super.init() _registerAutoFreeIfNeeded(doneAction) } - deinit { - _synthPhase.deinitialize(count: _halfSize) - _synthPhase.deallocate() - _interpMag.deinitialize(count: _halfSize) - _interpMag.deallocate() - _phaseDelta.deinitialize(count: _halfSize) - _phaseDelta.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - Non-RT API @@ -233,22 +223,22 @@ public final class SpectralPlayBuffer: GeneratorBase, AudioGenerator, SpectralBu // Step 1: interpolate magnitudes → _interpMag[1..halfSize-1] _frameBuffer.interpolateMagnitudes( - into: _interpMag, + into: _interpMag.baseAddress, frameA: frameA, frameB: frameB, frac: frac ) // Step 2: inter-frame phase delta → _phaseDelta[1..halfSize-1] - _frameBuffer.phaseDelta(frameA: frameA, frameB: frameB, into: _phaseDelta) + _frameBuffer.phaseDelta(frameA: frameA, frameB: frameB, into: _phaseDelta.baseAddress) // Step 3: scale delta by rate var rateF: Float = Float(rate) - vDSP_vsmul(_phaseDelta + 1, 1, &rateF, _phaseDelta + 1, 1, vDSP_Length(_binCount)) + vDSP_vsmul(_phaseDelta.baseAddress + 1, 1, &rateF, _phaseDelta.baseAddress + 1, 1, vDSP_Length(_binCount)) // Step 4: accumulate into synthesis phase vDSP_vadd( - _synthPhase + 1, 1, - _phaseDelta + 1, 1, - _synthPhase + 1, 1, + _synthPhase.baseAddress + 1, 1, + _phaseDelta.baseAddress + 1, 1, + _synthPhase.baseAddress + 1, 1, vDSP_Length(_binCount) ) @@ -270,10 +260,10 @@ public final class SpectralPlayBuffer: GeneratorBase, AudioGenerator, SpectralBu // Step 7: write magnitudes and phases into spectralBuffer. spectralBuffer.withUnsafeMutableMagnitudePointer { dst in - dst.update(from: _interpMag + 1, count: _binCount) + dst.update(from: _interpMag.baseAddress + 1, count: _binCount) } spectralBuffer.withUnsafeMutablePhasePointer { dst in - dst.update(from: _synthPhase + 1, count: _binCount) + dst.update(from: _synthPhase.baseAddress + 1, count: _binCount) } // Step 8: advance play position. diff --git a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift index e2017ca..bd1a892 100644 --- a/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift +++ b/Sources/Lyrebird/Generators/Spectral/SpectralTilt.swift @@ -33,7 +33,7 @@ public final class SpectralTilt: SpectralProcessor { /// Per-bin gain table sized `halfSize + 1`. Index 0 = DC, halfSize = Nyquist, /// 1..halfSize-1 = complex bins. Pre-computed at init. - private let _gainTable: UnsafeMutablePointer + private let _gainTable: RTScratchBuffer /// - Parameters: /// - fftSize: Must match the paired `SpectralChain.Audio.fftSize`. Power of two ≥ 4. @@ -59,8 +59,7 @@ public final class SpectralTilt: SpectralProcessor { _binCount = _halfSize - 1 let tableCount: Int = _halfSize + 1 - _gainTable = UnsafeMutablePointer.allocate(capacity: tableCount) - _gainTable.initialize(repeating: 1, count: tableCount) + _gainTable = RTScratchBuffer(count: tableCount, repeating: 1) // Build gain table. // gain(f) = 2 ^ (slope/6 · log2(f / pivot)) = (f / pivot) ^ (slope/6). @@ -78,10 +77,7 @@ public final class SpectralTilt: SpectralProcessor { } } - deinit { - _gainTable.deinitialize(count: _halfSize + 1) - _gainTable.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. public func process(spectral: SpectralBuffer, engine: SynthesisEngine) { guard spectral.fftSize == _fftSize else { return } @@ -89,7 +85,7 @@ public final class SpectralTilt: SpectralProcessor { // Complex bins: vDSP_vmul gain[1..halfSize-1] * mag[1..halfSize-1]. if _binCount > 0 { - let gainComplex: UnsafeMutablePointer = _gainTable.advanced(by: 1) + let gainComplex: UnsafeMutablePointer = _gainTable.baseAddress.advanced(by: 1) spectral.withUnsafeMutableMagnitudePointer { mp in vDSP_vmul(mp, 1, gainComplex, 1, mp, 1, vDSP_Length(_binCount)) } diff --git a/Sources/Lyrebird/MIDI/ALSAMIDI.swift b/Sources/Lyrebird/MIDI/ALSAMIDI.swift index 1376c05..c95b2e0 100644 --- a/Sources/Lyrebird/MIDI/ALSAMIDI.swift +++ b/Sources/Lyrebird/MIDI/ALSAMIDI.swift @@ -34,11 +34,12 @@ public final class MIDI: @unchecked Sendable { private let engine: SynthesisEngine private let clientName: String - // @unchecked Sendable invariant: `engine` / `clientName` are immutable. - // `seq`, `inputPort`, `outputPort`, `virtualOutputPort`, `isStarted`, and - // `pollThread` are mutated only under `stateLock`; `handlers` / `_sources` - // / `_destinations` only under `lock`; `_running` / `_abandonedThread` are - // atomic. No field is touched without one of those. + // @unchecked Sendable invariant: `engine` / `clientName` are immutable + // (`engine` is a non-Sendable shared reference — the reason this stays + // `@unchecked`). `seq`, `inputPort`, `outputPort`, `virtualOutputPort`, + // `isStarted`, and `pollThread` are mutated only under `stateLock`; the + // messaging state lives in `_messaging` (a `Mutex`); `_running` / + // `_abandonedThread` are atomic. No field is touched without one of those. // ALSA's own address sentinels for "deliver to my subscribers", used by // `sendVirtual`. Spelled out because the C macros that name them @@ -60,12 +61,21 @@ public final class MIDI: @unchecked Sendable { private var outputPort: Int32 = -1 private var virtualOutputPort: Int32 = -1 - // lock serializes handlers, _sources, and _destinations. - private let lock: NSLock = NSLock() - private var handlers: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = [] + private typealias Handler = (token: MIDIHandlerToken, + onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void) + /// Handler list and discovered source/destination lists, guarded as a unit. + /// These are all Sendable, so they migrate cleanly to a `Mutex` — unlike the + /// transport state above, whose non-Sendable ALSA handle (`OpaquePointer`) and + /// poll `Thread` must be read/stored under the lock but used OUTSIDE it, which + /// `Mutex.withLock`'s `sending` inout parameter forbids; that is why + /// `stateLock` stays an `NSLock`. + private struct Messaging { + var handlers: [Handler] = [] + var sources: [MIDISource] = [] + var destinations: [MIDIDestination] = [] + } + private let _messaging: Mutex = Mutex(Messaging()) private let nextTokenID: Atomic = Atomic(0) - private var _sources: [MIDISource] = [] - private var _destinations: [MIDIDestination] = [] private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.midi", qos: .userInteractive) private let _running: Atomic = Atomic(false) @@ -82,9 +92,9 @@ public final class MIDI: @unchecked Sendable { private let threadExited: DispatchSemaphore = DispatchSemaphore(value: 0) /// Enumerated MIDI sources at the time of last update. Thread-safe. - public var sources: [MIDISource] { lock.withLock { _sources } } + public var sources: [MIDISource] { _messaging.withLock { $0.sources } } /// Enumerated MIDI destinations at the time of last update. Thread-safe. - public var destinations: [MIDIDestination] { lock.withLock { _destinations } } + public var destinations: [MIDIDestination] { _messaging.withLock { $0.destinations } } public init( engine: SynthesisEngine, @@ -104,7 +114,7 @@ public final class MIDI: @unchecked Sendable { /// - Throws: `MIDIError.alreadyStarted` if already running; the /// `clientCreateFailed` / `portCreateFailed` cases (carrying the negative /// ALSA return code) on setup failure. - public func start() throws { + public func start() throws(MIDIError) { guard !_abandonedThread.load(ordering: .acquiring) else { // A previous poll thread never returned; its (leaked) handle is // still being read. Opening a second client would leave two threads @@ -202,7 +212,7 @@ public final class MIDI: @unchecked Sendable { // Abandon: the thread is still out there reading the handle. _abandonedThread.store(true, ordering: .releasing) } - lock.withLock { _sources = []; _destinations = [] } + _messaging.withLock { $0.sources = []; $0.destinations = [] } } // MARK: - Handlers (identical contract to the CoreMIDI backend) @@ -221,13 +231,13 @@ public final class MIDI: @unchecked Sendable { ) -> MIDIHandlerToken { let id: UInt64 = nextTokenID.add(1, ordering: .relaxed).newValue let token: MIDIHandlerToken = MIDIHandlerToken(id: id) - lock.withLock { handlers.append((token, onMessage)) } + _messaging.withLock { $0.handlers.append((token, onMessage)) } return token } /// Remove the handler identified by `token`. Thread-safe. public func removeHandler(_ token: MIDIHandlerToken) { - lock.withLock { handlers.removeAll { $0.token == token } } + _messaging.withLock { s in s.handlers.removeAll { $0.token == token } } } // MARK: - Virtual ports @@ -238,7 +248,7 @@ public final class MIDI: @unchecked Sendable { /// Each call adds a distinct named port; the ids are not tracked /// individually because `stop()`'s `snd_seq_close` frees every port the /// client owns. Call once per virtual input you want. - public func createVirtualInput(name: String) throws { + public func createVirtualInput(name: String) throws(MIDIError) { let handle: OpaquePointer? = stateLock.withLock { seq } guard let seqHandle: OpaquePointer = handle else { throw MIDIError.notStarted } let port: Int32 = snd_seq_create_simple_port( @@ -251,7 +261,7 @@ public final class MIDI: @unchecked Sendable { /// Create a virtual MIDI output (a readable sequencer port other clients can /// subscribe to). Messages sent via ``sendVirtual(_:)`` reach its subscribers. - public func createVirtualOutput(name: String) throws { + public func createVirtualOutput(name: String) throws(MIDIError) { let handle: OpaquePointer? = stateLock.withLock { seq } guard let seqHandle: OpaquePointer = handle else { throw MIDIError.notStarted } let port: Int32 = snd_seq_create_simple_port( @@ -269,7 +279,7 @@ public final class MIDI: @unchecked Sendable { /// /// - Throws: `MIDIError.notStarted` if the client is not open, or /// `MIDIError.sendFailed` (carrying the ALSA return code) on failure. - public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws { + public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws(MIDIError) { let (handle, srcPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, outputPort) } guard let seqHandle: OpaquePointer = handle, srcPort >= 0 else { throw MIDIError.notStarted } try _output(message, on: seqHandle, sourcePort: srcPort, @@ -279,7 +289,7 @@ public final class MIDI: @unchecked Sendable { /// Send `message` to the subscribers of the virtual output port created by /// ``createVirtualOutput(name:)``. - public func sendVirtual(_ message: MIDIMessage) throws { + public func sendVirtual(_ message: MIDIMessage) throws(MIDIError) { let (handle, srcPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, virtualOutputPort) } guard let seqHandle: OpaquePointer = handle, srcPort >= 0 else { throw MIDIError.notStarted } try _output(message, on: seqHandle, sourcePort: srcPort, @@ -294,7 +304,7 @@ public final class MIDI: @unchecked Sendable { sourcePort: Int32, destClient: UInt8, destPort: UInt8 - ) throws { + ) throws(MIDIError) { var ev: snd_seq_event_t = snd_seq_event_t() ev.queue = UInt8(truncatingIfNeeded: SND_SEQ_QUEUE_DIRECT) ev.source.port = UInt8(truncatingIfNeeded: sourcePort) @@ -432,7 +442,7 @@ public final class MIDI: @unchecked Sendable { } private func _dispatch(_ message: MIDIMessage, ctx: LyrebirdMessageContext) { - let snapshot: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } + let snapshot: [Handler] = _messaging.withLock { $0.handlers } handlerQueue.async { for entry in snapshot { entry.onMessage(message, ctx) } } @@ -481,7 +491,7 @@ public final class MIDI: @unchecked Sendable { } } } - lock.withLock { _sources = newSrcs; _destinations = newDests } + _messaging.withLock { $0.sources = newSrcs; $0.destinations = newDests } } /// Subscribe our input port to every enumerated source, so a controller's @@ -489,7 +499,7 @@ public final class MIDI: @unchecked Sendable { private func _connectAllSources() { let (handle, inPort): (OpaquePointer?, Int32) = stateLock.withLock { (seq, inputPort) } guard let seqHandle: OpaquePointer = handle, inPort >= 0 else { return } - let srcs: [MIDISource] = lock.withLock { _sources } + let srcs: [MIDISource] = _messaging.withLock { $0.sources } for src: MIDISource in srcs { _ = snd_seq_connect_from(seqHandle, inPort, src.client, src.port) } diff --git a/Sources/Lyrebird/MIDI/MIDI.swift b/Sources/Lyrebird/MIDI/MIDI.swift index f3ecb72..2087b94 100644 --- a/Sources/Lyrebird/MIDI/MIDI.swift +++ b/Sources/Lyrebird/MIDI/MIDI.swift @@ -40,22 +40,34 @@ public final class MIDI: @unchecked Sendable { private let engine: SynthesisEngine private let clientName: String - // stateLock serializes all reads and writes of the CoreMIDI ref vars and isStarted below. - private let stateLock: NSLock = NSLock() - private var isStarted: Bool = false - private var midiClient: MIDIClientRef = 0 - private var inputPort: MIDIPortRef = 0 - private var outputPort: MIDIPortRef = 0 - private var virtualInputEndpoint: MIDIEndpointRef = 0 - private var virtualOutputEndpoint: MIDIEndpointRef = 0 + private typealias Handler = (token: MIDIHandlerToken, + onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void) + + /// CoreMIDI transport state (client, I/O ports, virtual endpoints, started flag), + /// guarded as a unit. `stop()` captures the refs under the lock and disposes them + /// OUTSIDE it — CoreMIDI dispose calls can fire notifications. + private struct Transport { + var isStarted: Bool = false + var midiClient: MIDIClientRef = 0 + var inputPort: MIDIPortRef = 0 + var outputPort: MIDIPortRef = 0 + var virtualInputEndpoint: MIDIEndpointRef = 0 + var virtualOutputEndpoint: MIDIEndpointRef = 0 + } + private let _transport: Mutex = Mutex(Transport()) + + /// Handler list, sysex reassembly buffer, and discovered source/destination + /// lists, guarded as a unit. Touched from the CoreMIDI receive thread and from + /// `addHandler`/`removeHandler` callers — never the RT audio thread. + private struct Messaging { + var handlers: [Handler] = [] + var sysexAccumulator: [UInt8] = [] + var sources: [MIDISource] = [] + var destinations: [MIDIDestination] = [] + } + private let _messaging: Mutex = Mutex(Messaging()) - // lock serializes handlers, sysexAccumulator, _sources, and _destinations. - private let lock: NSLock = NSLock() - private var handlers: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = [] private let nextTokenID: Atomic = Atomic(0) - private var sysexAccumulator: [UInt8] = [] - private var _sources: [MIDISource] = [] - private var _destinations: [MIDIDestination] = [] private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.midi", qos: .userInteractive) @@ -69,9 +81,9 @@ public final class MIDI: @unchecked Sendable { }() /// Enumerated MIDI sources at the time of last update. Thread-safe. - public var sources: [MIDISource] { lock.withLock { _sources } } + public var sources: [MIDISource] { _messaging.withLock { $0.sources } } /// Enumerated MIDI destinations at the time of last update. Thread-safe. - public var destinations: [MIDIDestination] { lock.withLock { _destinations } } + public var destinations: [MIDIDestination] { _messaging.withLock { $0.destinations } } public init( engine: SynthesisEngine, @@ -86,11 +98,11 @@ public final class MIDI: @unchecked Sendable { /// Open the CoreMIDI client, create I/O ports, and connect to all current sources. /// /// - Throws: `MIDIError.alreadyStarted` if called while already running. - public func start() throws { - // Atomic check-and-set under stateLock prevents TOCTOU if start() is called + public func start() throws(MIDIError) { + // Atomic check-and-set under _transport prevents TOCTOU if start() is called // concurrently from two threads. var shouldProceed: Bool = false - stateLock.withLock { if !isStarted { isStarted = true; shouldProceed = true } } + _transport.withLock { if !$0.isStarted { $0.isStarted = true; shouldProceed = true } } guard shouldProceed else { throw MIDIError.alreadyStarted } var client: MIDIClientRef = 0 @@ -100,7 +112,7 @@ public final class MIDI: @unchecked Sendable { var didSucceed: Bool = false defer { if !didSucceed { - stateLock.withLock { isStarted = false } // release claim on failure + _transport.withLock { $0.isStarted = false } // release claim on failure if inPort != 0 { MIDIPortDispose(inPort) } if outPort != 0 { MIDIPortDispose(outPort) } if client != 0 { MIDIClientDispose(client) } @@ -125,10 +137,10 @@ public final class MIDI: @unchecked Sendable { let outStatus: OSStatus = MIDIOutputPortCreate(client, "LyrebirdOut" as CFString, &outPort) guard outStatus == noErr else { throw MIDIError.portCreateFailed(outStatus) } - stateLock.withLock { - midiClient = client - inputPort = inPort - outputPort = outPort + _transport.withLock { + $0.midiClient = client + $0.inputPort = inPort + $0.outputPort = outPort } _refreshEndpoints() @@ -140,12 +152,12 @@ public final class MIDI: @unchecked Sendable { public func stop() { // Atomically capture and clear all refs so concurrent send() callers // see notStarted immediately. Dispose after releasing the lock to avoid - // holding stateLock during CoreMIDI calls that may fire notifications. - let (vi, vo, ip, op, mc) = stateLock.withLock { - let refs: (MIDIEndpointRef, MIDIEndpointRef, MIDIPortRef, MIDIPortRef, MIDIClientRef) = (virtualInputEndpoint, virtualOutputEndpoint, inputPort, outputPort, midiClient) - isStarted = false - virtualInputEndpoint = 0; virtualOutputEndpoint = 0 - inputPort = 0; outputPort = 0; midiClient = 0 + // holding _transport during CoreMIDI calls that may fire notifications. + let (vi, vo, ip, op, mc) = _transport.withLock { t in + let refs: (MIDIEndpointRef, MIDIEndpointRef, MIDIPortRef, MIDIPortRef, MIDIClientRef) = (t.virtualInputEndpoint, t.virtualOutputEndpoint, t.inputPort, t.outputPort, t.midiClient) + t.isStarted = false + t.virtualInputEndpoint = 0; t.virtualOutputEndpoint = 0 + t.inputPort = 0; t.outputPort = 0; t.midiClient = 0 return refs } if vi != 0 { MIDIEndpointDispose(vi) } @@ -185,13 +197,13 @@ public final class MIDI: @unchecked Sendable { ) -> MIDIHandlerToken { let id: UInt64 = nextTokenID.add(1, ordering: .relaxed).newValue let token: MIDIHandlerToken = MIDIHandlerToken(id: id) - lock.withLock { handlers.append((token, onMessage)) } + _messaging.withLock { $0.handlers.append((token, onMessage)) } return token } /// Remove the handler identified by `token`. Thread-safe; safe to call from any queue. public func removeHandler(_ token: MIDIHandlerToken) { - lock.withLock { handlers.removeAll { $0.token == token } } + _messaging.withLock { s in s.handlers.removeAll { $0.token == token } } } // MARK: - Virtual ports @@ -199,8 +211,8 @@ public final class MIDI: @unchecked Sendable { /// Create a virtual MIDI destination visible to other apps. /// /// Incoming messages are dispatched to registered handlers, like hardware sources. - public func createVirtualInput(name: String) throws { - let client: MIDIClientRef = stateLock.withLock { midiClient } + public func createVirtualInput(name: String) throws(MIDIError) { + let client: MIDIClientRef = _transport.withLock { $0.midiClient } guard client != 0 else { throw MIDIError.notStarted } let ctx: LyrebirdMessageContext = LyrebirdMessageContext(engine: engine) let receiveBlock: MIDIReceiveBlock = { [weak self] evtListPtr, _ in @@ -211,21 +223,21 @@ public final class MIDI: @unchecked Sendable { client, name as CFString, MIDI.midi10, &endpoint, receiveBlock ) guard status == noErr else { throw MIDIError.virtualPortFailed(status) } - stateLock.withLock { virtualInputEndpoint = endpoint } + _transport.withLock { $0.virtualInputEndpoint = endpoint } } /// Create a virtual MIDI source visible to other apps. /// /// Use `sendVirtual(_:)` to publish messages on this port. - public func createVirtualOutput(name: String) throws { - let client: MIDIClientRef = stateLock.withLock { midiClient } + public func createVirtualOutput(name: String) throws(MIDIError) { + let client: MIDIClientRef = _transport.withLock { $0.midiClient } guard client != 0 else { throw MIDIError.notStarted } var endpoint: MIDIEndpointRef = 0 let status: OSStatus = MIDISourceCreateWithProtocol( client, name as CFString, MIDI.midi10, &endpoint ) guard status == noErr else { throw MIDIError.virtualPortFailed(status) } - stateLock.withLock { virtualOutputEndpoint = endpoint } + _transport.withLock { $0.virtualOutputEndpoint = endpoint } } // MARK: - Sending @@ -237,8 +249,8 @@ public final class MIDI: @unchecked Sendable { /// - destination: Target endpoint from ``destinations``. /// - Throws: `MIDIError.notStarted` if ``start()`` has not been called. /// `MIDIError.sendFailed(_:)` if CoreMIDI returns an error. - public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws { - let port: MIDIPortRef = stateLock.withLock { outputPort } + public func send(_ message: MIDIMessage, to destination: MIDIDestination) throws(MIDIError) { + let port: MIDIPortRef = _transport.withLock { $0.outputPort } guard port != 0 else { throw MIDIError.notStarted } let words: [UInt32] = message.umpWords() guard !words.isEmpty else { return } @@ -251,8 +263,8 @@ public final class MIDI: @unchecked Sendable { } /// Publish a message on a virtual output created via `createVirtualOutput(name:)`. - public func sendVirtual(_ message: MIDIMessage) throws { - let endpoint: MIDIEndpointRef = stateLock.withLock { virtualOutputEndpoint } + public func sendVirtual(_ message: MIDIMessage) throws(MIDIError) { + let endpoint: MIDIEndpointRef = _transport.withLock { $0.virtualOutputEndpoint } guard endpoint != 0 else { throw MIDIError.notStarted } let words: [UInt32] = message.umpWords() guard !words.isEmpty else { return } @@ -264,22 +276,26 @@ public final class MIDI: @unchecked Sendable { private func _sendWords( _ words: [UInt32], - via sendFn: (UnsafeMutablePointer, Int, UnsafeMutablePointer, inout [UInt32]) throws -> OSStatus - ) throws { + via sendFn: (UnsafeMutablePointer, Int, UnsafeMutablePointer, inout [UInt32]) -> OSStatus + ) throws(MIDIError) { // Buffer: MIDIEventList header + MIDIEventPacket header + word storage + alignment slack let midiEventListHeaderSize: Int = 8 // MIDIProtocolID (4) + numPackets (4) let midiEventPacketHeaderSize: Int = 12 // timeStamp (8) + wordCount (4) let umpWordStorageSlack: Int = 64 // alignment padding reserve required by MIDIEventListInit let bufSize: Int = midiEventListHeaderSize + midiEventPacketHeaderSize + words.count * 4 + umpWordStorageSlack var buffer: [UInt8] = [UInt8](repeating: 0, count: bufSize) - try buffer.withUnsafeMutableBytes { raw in - guard let base: UnsafeMutableRawPointer = raw.baseAddress else { throw MIDIError.sendFailed(lyrebirdMIDIParamError) } + // The closure stays non-throwing (returns the OSStatus, using the param-error + // sentinel for the impossible nil-base case) so the send status can be thrown + // in this function's typed-throws context — `withUnsafeMutableBytes`'s + // `rethrows` does not narrow to the closure's typed error. + let status: OSStatus = buffer.withUnsafeMutableBytes { raw -> OSStatus in + guard let base: UnsafeMutableRawPointer = raw.baseAddress else { return lyrebirdMIDIParamError } let listPtr: UnsafeMutablePointer = base.assumingMemoryBound(to: MIDIEventList.self) let pktPtr: UnsafeMutablePointer = MIDIEventListInit(listPtr, MIDI.midi10) var mutableWords: [UInt32] = words - let st: OSStatus = try sendFn(listPtr, bufSize, pktPtr, &mutableWords) - guard st == noErr else { throw MIDIError.sendFailed(st) } + return sendFn(listPtr, bufSize, pktPtr, &mutableWords) } + guard status == noErr else { throw MIDIError.sendFailed(status) } } // MARK: - Private: receive @@ -342,12 +358,12 @@ public final class MIDI: @unchecked Sendable { case 0x0: _dispatch(.sysex(bytes), ctx: ctx) case 0x1: - lock.withLock { sysexAccumulator = bytes } + _messaging.withLock { $0.sysexAccumulator = bytes } case 0x2: - lock.withLock { sysexAccumulator += bytes } + _messaging.withLock { $0.sysexAccumulator += bytes } case 0x3: var full: [UInt8] = [] - lock.withLock { full = sysexAccumulator + bytes; sysexAccumulator = [] } + _messaging.withLock { full = $0.sysexAccumulator + bytes; $0.sysexAccumulator = [] } _dispatch(.sysex(full), ctx: ctx) default: break @@ -363,9 +379,9 @@ public final class MIDI: @unchecked Sendable { _ message: MIDIMessage, ctx: LyrebirdMessageContext ) { - let snapshot: [(token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } + let snapshot: [Handler] = _messaging.withLock { $0.handlers } handlerQueue.async { - for entry: (token: MIDIHandlerToken, onMessage: @Sendable (MIDIMessage, LyrebirdMessageContext) -> Void) in snapshot { entry.onMessage(message, ctx) } + for entry: Handler in snapshot { entry.onMessage(message, ctx) } } } @@ -386,11 +402,11 @@ public final class MIDI: @unchecked Sendable { let ref: MIDIEndpointRef = MIDIGetDestination(i) newDests.append(MIDIDestination(name: _endpointName(ref), endpointRef: ref)) } - lock.withLock { _sources = newSrcs; _destinations = newDests } + _messaging.withLock { $0.sources = newSrcs; $0.destinations = newDests } } private func _connectAllSources() { - let port: MIDIPortRef = stateLock.withLock { inputPort } + let port: MIDIPortRef = _transport.withLock { $0.inputPort } guard port != 0 else { return } for i: Int in 0.. = Mutex(nil) /// - Parameters: /// - file: The parsed MIDI file. @@ -103,16 +107,15 @@ public final class MIDIFilePlayer: @unchecked Sendable { let clock: LyrebirdClock = clock // Snapshot the previous routine OUTSIDE the lock so the blocking join - // in `reset()` does not hold `_routineLock`. Holding the lock across + // in `reset()` does not hold the `_routine` Mutex. Holding it across // `reset()` would deadlock if the handler closure on the routine // thread calls back into any lock-protected method (`stop`, `reset`, // `play`, `state`). - let previous: LyrebirdRoutine? = { - _routineLock.lock(); defer { _routineLock.unlock() } - let p: LyrebirdRoutine? = _routine - _routine = nil + let previous: LyrebirdRoutine? = _routine.withLock { r in + let p: LyrebirdRoutine? = r + r = nil return p - }() + } previous?.reset() let routine: LyrebirdRoutine = LyrebirdRoutine { ctx in @@ -136,31 +139,32 @@ public final class MIDIFilePlayer: @unchecked Sendable { } } } - _routineLock.lock() - _routine = routine - _routineLock.unlock() + _routine.withLock { $0 = routine } routine.start(engine: _engine) } /// Signal the routine to stop. Returns immediately; handlers will not be /// called for any further events. public func stop() { - _routineLock.lock() - defer { _routineLock.unlock() } - _routine?.stop() + // Snapshot out of the Mutex, then stop outside it: LyrebirdRoutine.stop() + // may block on the routine thread's wind-down, and a handler on that thread + // can call back into a lock-protected method — holding the Mutex across it + // would deadlock (the same hazard play() avoids before its reset()). + let routine: LyrebirdRoutine? = _routine.withLock { $0 } + routine?.stop() } /// Stop and synchronously wait for the routine thread to exit. public func reset() { - _routineLock.lock() - defer { _routineLock.unlock() } - _routine?.reset() + // Snapshot out of the Mutex, then reset outside it — reset() joins the + // routine thread (a blocking poll), which must not run while holding the + // Mutex a routine-thread handler callback might contend for. + let routine: LyrebirdRoutine? = _routine.withLock { $0 } + routine?.reset() } /// Current routine state. `.idle` if `play` has not been called. public var state: LyrebirdRoutine.State { - _routineLock.lock() - defer { _routineLock.unlock() } - return _routine?.state ?? .idle + _routine.withLock { $0?.state ?? .idle } } } diff --git a/Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift b/Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift index 1411973..a382bca 100644 --- a/Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift +++ b/Sources/Lyrebird/MIDI/Sync/MIDIClockFollower.swift @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT import Foundation +import Synchronization /// Estimates BPM from incoming MIDI Clock (0xF8) messages and follows a `LyrebirdClock`. /// @@ -32,11 +33,15 @@ import Foundation /// - minBPM: Lower bound for the BPM estimate. Out-of-range values are clamped. /// - maxBPM: Upper bound for the BPM estimate. Out-of-range values are clamped. public final class MIDIClockFollower: @unchecked Sendable { - // Sendable invariant: configuration (`clock`, `sampleRate`, `smoothingWindowTicks`, - // `minBPM`, `maxBPM`, `_timeProvider`) are immutable lets. All mutable state - // (`_tickHistory`, `_estimatedBPM`, `_isRunning`) is serialised by `_lock`. - // BPM writes to `clock.bpm` happen outside `_lock` to avoid lock-order inversion - // against `LyrebirdClock._lock`. + // @unchecked Sendable invariant: configuration (`clock`, `sampleRate`, + // `smoothingWindowTicks`, `minBPM`, `maxBPM`, `_timeProvider`) are immutable lets. + // All mutable state lives in `_state`, a `Mutex` that serialises every access, so + // the lock discipline is compiler-enforced. BPM writes to `clock.bpm` happen + // OUTSIDE `_state.withLock` to avoid lock-order inversion against LyrebirdClock's + // own Mutex. Stays `@unchecked` (not checked) for two reasons: `clock` is an + // `@unchecked Sendable` `LyrebirdClock`, and `_timeProvider` is a non-`@Sendable` + // closure — the public init assigns `{ engine.currentTime }`, which captures the + // non-Sendable engine, so the property type cannot be tightened to `@Sendable`. // MARK: - Constants @@ -56,16 +61,20 @@ public final class MIDIClockFollower: @unchecked Sendable { /// Replaceable via the internal initialiser for unit tests. private let _timeProvider: () -> SampleTime - // MARK: - Internal state (all access under _lock) + // MARK: - Internal state (all access under _state) - private let _lock: NSLock = NSLock() - private var _tickHistory: [SampleTime] = [] - private var _estimatedBPM: Double = 0.0 - // Default `true` so free-running MIDI clock sources that emit only 0xF8 - // (no transport messages) update `clock.bpm` out-of-the-box. `.stop` sets it - // to `false` and gates subsequent ticks; `.start` / `.continue` re-enable. - private var _isRunning: Bool = true - private var _lastPushedBPM: Double = 0.0 + /// Mutable estimator state, guarded as a unit. `tickHistory` is the rolling + /// window of tick sample-times; `isRunning` defaults `true` so free-running + /// MIDI clock sources that emit only 0xF8 (no transport messages) update + /// `clock.bpm` out-of-the-box (`.stop` sets it `false` and gates subsequent + /// ticks; `.start` / `.continue` re-enable). + private struct State { + var tickHistory: [SampleTime] = [] + var estimatedBPM: Double = 0.0 + var isRunning: Bool = true + var lastPushedBPM: Double = 0.0 + } + private let _state: Mutex = Mutex(State()) // MARK: - Public init @@ -97,7 +106,7 @@ public final class MIDIClockFollower: @unchecked Sendable { // +2: history may transiently reach `smoothingWindowTicks + 2` between // `append` and the trim in `_handleClock`. Sizing for that peak avoids // a backing-buffer reallocation per tick at steady state. - _tickHistory.reserveCapacity(smoothingWindowTicks + 2) + _state.withLock { $0.tickHistory.reserveCapacity(smoothingWindowTicks + 2) } } // MARK: - Internal init (test injection) @@ -128,7 +137,7 @@ public final class MIDIClockFollower: @unchecked Sendable { self.minBPM = minBPM self.maxBPM = maxBPM self._timeProvider = timeProvider - _tickHistory.reserveCapacity(smoothingWindowTicks + 2) + _state.withLock { $0.tickHistory.reserveCapacity(smoothingWindowTicks + 2) } } // MARK: - Public interface @@ -138,7 +147,7 @@ public final class MIDIClockFollower: @unchecked Sendable { /// /// Thread-safe. public var estimatedBPM: Double { - _lock.withLock { _estimatedBPM } + _state.withLock { $0.estimatedBPM } } /// Whether the follower currently tracks incoming `.clock` ticks. Initially @@ -147,7 +156,7 @@ public final class MIDIClockFollower: @unchecked Sendable { /// /// Thread-safe. public var isRunning: Bool { - _lock.withLock { _isRunning } + _state.withLock { $0.isRunning } } /// Pass every incoming `MIDIMessage` here. Non-clock messages are silently ignored. @@ -162,19 +171,19 @@ public final class MIDIClockFollower: @unchecked Sendable { case .clock: _handleClock() case .start: - _lock.withLock { - _isRunning = true - _clearHistory() + _state.withLock { s in + s.isRunning = true + _clearHistory(&s) } case .continue: - _lock.withLock { - _isRunning = true - _clearHistory() + _state.withLock { s in + s.isRunning = true + _clearHistory(&s) } case .stop: - _lock.withLock { - _isRunning = false - _clearHistory() + _state.withLock { s in + s.isRunning = false + _clearHistory(&s) } default: break @@ -185,38 +194,38 @@ public final class MIDIClockFollower: @unchecked Sendable { /// /// Thread-safe. public func reset() { - _lock.withLock { _clearHistory() } + _state.withLock { s in _clearHistory(&s) } } // MARK: - Private helpers /// Called on `.clock` messages. Captures the current sample time, updates the /// rolling history, and recomputes the BPM estimate. The `clock.bpm` write is - /// performed *after* releasing `_lock`. + /// performed *after* the `_state.withLock` closure returns. private func _handleClock() { let now: SampleTime = _timeProvider() var newBPM: Double? = nil - _lock.withLock { + _state.withLock { s in // After `.stop`, ignore clock ticks until `.start` or `.continue` // re-enables tracking. Honors the docstring contract: `.stop` → // `clock.bpm` is not modified. - guard _isRunning else { return } - _tickHistory.append(now) - if _tickHistory.count > smoothingWindowTicks + 1 { - _tickHistory.removeFirst() + guard s.isRunning else { return } + s.tickHistory.append(now) + if s.tickHistory.count > smoothingWindowTicks + 1 { + s.tickHistory.removeFirst() } - guard _tickHistory.count >= 2 else { return } - let windowSize: Int = _tickHistory.count - 1 - let totalDelta: Double = Double(_tickHistory[_tickHistory.count - 1] - _tickHistory[0]) + guard s.tickHistory.count >= 2 else { return } + let windowSize: Int = s.tickHistory.count - 1 + let totalDelta: Double = Double(s.tickHistory[s.tickHistory.count - 1] - s.tickHistory[0]) let avgDeltaSamples: Double = totalDelta / Double(windowSize) guard avgDeltaSamples > 0 else { return } let secondsPerTick: Double = avgDeltaSamples / sampleRate let rawBPM: Double = secondsPerMinute / (secondsPerTick * ticksPerQuarterNote) guard rawBPM.isFinite else { return } let clamped: Double = rawBPM.clamped(to: minBPM...maxBPM) - _estimatedBPM = clamped - if abs(clamped - _lastPushedBPM) > bpmUpdateEpsilon { - _lastPushedBPM = clamped + s.estimatedBPM = clamped + if abs(clamped - s.lastPushedBPM) > bpmUpdateEpsilon { + s.lastPushedBPM = clamped newBPM = clamped } } @@ -225,11 +234,11 @@ public final class MIDIClockFollower: @unchecked Sendable { } } - /// Clear tick history and reset the estimate. Must be called with `_lock` held. - private func _clearHistory() { - _tickHistory.removeAll(keepingCapacity: true) - _estimatedBPM = 0.0 - _lastPushedBPM = 0.0 + /// Clear tick history and reset the estimate. Mutates the caller's locked `State`. + private func _clearHistory(_ s: inout State) { + s.tickHistory.removeAll(keepingCapacity: true) + s.estimatedBPM = 0.0 + s.lastPushedBPM = 0.0 } } diff --git a/Sources/Lyrebird/OSC/OSCCodec.swift b/Sources/Lyrebird/OSC/OSCCodec.swift index 31511ad..d7d4a10 100644 --- a/Sources/Lyrebird/OSC/OSCCodec.swift +++ b/Sources/Lyrebird/OSC/OSCCodec.swift @@ -24,11 +24,11 @@ enum OSCCodec { /// Decode a UDP datagram. Returns zero or more messages; handles both single /// messages and OSC bundles (including nested bundles). - static func decode(_ data: Data) throws -> [OSCMessage] { + static func decode(_ data: Data) throws(OSCDecodeError) -> [OSCMessage] { try _decode(data, depth: 0) } - private static func _decode(_ data: Data, depth: Int) throws -> [OSCMessage] { + private static func _decode(_ data: Data, depth: Int) throws(OSCDecodeError) -> [OSCMessage] { if data.starts(with: bundlePrefix) { return try decodeBundle(data, depth: depth) } @@ -37,7 +37,7 @@ enum OSCCodec { // MARK: - Message decode - static func decodeMessage(_ data: Data) throws -> OSCMessage { + static func decodeMessage(_ data: Data) throws(OSCDecodeError) -> OSCMessage { var offset: Int = 0 let address: String = try readString(data, offset: &offset) guard address.hasPrefix("/") else { throw OSCDecodeError.invalidString } @@ -86,7 +86,7 @@ enum OSCCodec { // "#bundle\0" = 8 bytes private static let bundlePrefix: Data = Data([0x23, 0x62, 0x75, 0x6E, 0x64, 0x6C, 0x65, 0x00]) - static func decodeBundle(_ data: Data, depth: Int = 0) throws -> [OSCMessage] { + static func decodeBundle(_ data: Data, depth: Int = 0) throws(OSCDecodeError) -> [OSCMessage] { guard depth < maxBundleDepth else { throw OSCDecodeError.invalidBundle } guard data.count >= 16 else { throw OSCDecodeError.invalidBundle } // Skip 8-byte "#bundle\0" header + 8-byte timetag = 16 bytes @@ -136,7 +136,7 @@ enum OSCCodec { // MARK: - Primitive read helpers - static func readString(_ data: Data, offset: inout Int) throws -> String { + static func readString(_ data: Data, offset: inout Int) throws(OSCDecodeError) -> String { guard offset < data.count else { throw OSCDecodeError.insufficientData } var end: Int = offset while end < data.count, data[data.startIndex.advanced(by: end)] != 0 { end += 1 } @@ -149,7 +149,7 @@ enum OSCCodec { return s } - static func readInt32(_ data: Data, offset: inout Int) throws -> Int32 { + static func readInt32(_ data: Data, offset: inout Int) throws(OSCDecodeError) -> Int32 { guard offset + 4 <= data.count else { throw OSCDecodeError.insufficientData } let v: Int32 = data.withUnsafeBytes { ptr -> Int32 in var raw: Int32 = 0 @@ -162,17 +162,17 @@ enum OSCCodec { return Int32(bigEndian: v) } - static func readUInt32(_ data: Data, offset: inout Int) throws -> UInt32 { + static func readUInt32(_ data: Data, offset: inout Int) throws(OSCDecodeError) -> UInt32 { let signed: Int32 = try readInt32(data, offset: &offset) return UInt32(bitPattern: signed) } - static func readFloat32(_ data: Data, offset: inout Int) throws -> Float { + static func readFloat32(_ data: Data, offset: inout Int) throws(OSCDecodeError) -> Float { let bits: UInt32 = try readUInt32(data, offset: &offset) return Float(bitPattern: bits) } - static func readBlob(_ data: Data, offset: inout Int) throws -> Data { + static func readBlob(_ data: Data, offset: inout Int) throws(OSCDecodeError) -> Data { let size: Int = Int(try readInt32(data, offset: &offset)) guard size >= 0, offset + size <= data.count else { throw OSCDecodeError.insufficientData } let blob: Data = Data(data[data.startIndex.advanced(by: offset).. public init( engine: SynthesisEngine, @@ -45,60 +55,57 @@ public final class LyrebirdClock: @unchecked Sendable { ) { precondition(bpm > 0, "bpm must be positive") _engine = engine - _bpm = bpm - epoch = engine.currentTime - _tempoChangeSample = engine.currentTime + let now: SampleTime = engine.currentTime + epoch = now + _state = Mutex(State(bpm: bpm, tempoChangeSample: now)) } /// Tempo in beats per minute. Setting this mid-performance correctly accumulates /// the beat count — the same accumulation pattern as `LyrebirdRoutineContext.tempo`. public var bpm: Double { - get { - _lock.lock(); defer { _lock.unlock() } - return _bpm - } + get { _state.withLock { $0.bpm } } set { precondition(newValue > 0, "bpm must be positive") - _lock.lock(); defer { _lock.unlock() } - let now: SampleTime = _engine.currentTime - _beatOffset += Double(now - _tempoChangeSample) / _engine.sampleRate * _bpm / LyrebirdClock.secondsPerMinute - _tempoChangeSample = now - _bpm = newValue + _state.withLock { s in + let now: SampleTime = _engine.currentTime + s.beatOffset += Double(now - s.tempoChangeSample) / _engine.sampleRate * s.bpm / LyrebirdClock.secondsPerMinute + s.tempoChangeSample = now + s.bpm = newValue + } } } /// Beats elapsed since this clock was created, correctly accumulated across tempo changes. public var currentBeat: Double { - _lock.lock(); defer { _lock.unlock() } - return _currentBeat() + _state.withLock { _currentBeat($0) } } /// Sample time corresponding to beat `beat`. /// May return a sample time in the past if `beat` has already elapsed. /// Only accurate for beats within the current tempo segment (since the last `bpm` change). public func sampleTime(beat: Double) -> SampleTime { - _lock.lock(); defer { _lock.unlock() } - return _sampleTime(beat: beat) + _state.withLock { _sampleTime(beat: beat, $0) } } /// Sample time of the next whole beat boundary after `beat`. /// If `beat` is nil, uses `currentBeat`. /// When `beat` is exactly a whole number N, returns the sample time of beat N+1. public func nextBeat(after beat: Double? = nil) -> SampleTime { - _lock.lock(); defer { _lock.unlock() } - let from: Double = beat ?? _currentBeat() - return _sampleTime(beat: floor(from) + 1.0) + _state.withLock { s in + let from: Double = beat ?? _currentBeat(s) + return _sampleTime(beat: floor(from) + 1.0, s) + } } - // MARK: - Private (must be called with _lock held) + // MARK: - Private (pure given a State snapshot; callers hold the Mutex) - private func _currentBeat() -> Double { + private func _currentBeat(_ s: State) -> Double { let now: SampleTime = _engine.currentTime - return _beatOffset + Double(now - _tempoChangeSample) / _engine.sampleRate * _bpm / LyrebirdClock.secondsPerMinute + return s.beatOffset + Double(now - s.tempoChangeSample) / _engine.sampleRate * s.bpm / LyrebirdClock.secondsPerMinute } - private func _sampleTime(beat: Double) -> SampleTime { - let samplesFromTempo: Double = (beat - _beatOffset) * LyrebirdClock.secondsPerMinute / _bpm * _engine.sampleRate - return _tempoChangeSample + SampleTime(samplesFromTempo.rounded()) + private func _sampleTime(beat: Double, _ s: State) -> SampleTime { + let samplesFromTempo: Double = (beat - s.beatOffset) * LyrebirdClock.secondsPerMinute / s.bpm * _engine.sampleRate + return s.tempoChangeSample + SampleTime(samplesFromTempo.rounded()) } } diff --git a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift index eb1f7e4..7d63541 100644 --- a/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift +++ b/Sources/Lyrebird/Spectral/CepstralEnvelopeEstimator.swift @@ -43,16 +43,16 @@ internal final class CepstralEnvelopeEstimator { private let fftSetup: FFTSetup /// log(magnitudes) — length `halfSize + 1`. - private let _logMag: UnsafeMutablePointer + private let _logMag: RTScratchBuffer /// Split-complex scratch (DC at `_realp[0]`, Nyquist at `_imagp[0]`, /// complex bins `1 ..< halfSize` in `_realp[k]` / `_imagp[k]`). /// Length `halfSize` each. - private let _realp: UnsafeMutablePointer - private let _imagp: UnsafeMutablePointer + private let _realp: RTScratchBuffer + private let _imagp: RTScratchBuffer /// Real cepstrum scratch — length `fftSize`. - private let _cepstrum: UnsafeMutablePointer + private let _cepstrum: RTScratchBuffer /// Smallest magnitude allowed before taking the log. Picked an order of /// magnitude below typical float underflow so `log(ε)` stays finite but @@ -85,26 +85,14 @@ internal final class CepstralEnvelopeEstimator { } self.fftSetup = setup - _logMag = UnsafeMutablePointer.allocate(capacity: halfSize + 1) - _realp = UnsafeMutablePointer.allocate(capacity: halfSize) - _imagp = UnsafeMutablePointer.allocate(capacity: halfSize) - _cepstrum = UnsafeMutablePointer.allocate(capacity: fftSize) - - _logMag.initialize(repeating: 0, count: halfSize + 1) - _realp.initialize(repeating: 0, count: halfSize) - _imagp.initialize(repeating: 0, count: halfSize) - _cepstrum.initialize(repeating: 0, count: fftSize) + _logMag = RTScratchBuffer(count: halfSize + 1) + _realp = RTScratchBuffer(count: halfSize) + _imagp = RTScratchBuffer(count: halfSize) + _cepstrum = RTScratchBuffer(count: fftSize) } deinit { - _logMag.deinitialize(count: halfSize + 1) - _logMag.deallocate() - _realp.deinitialize(count: halfSize) - _realp.deallocate() - _imagp.deinitialize(count: halfSize) - _imagp.deallocate() - _cepstrum.deinitialize(count: fftSize) - _cepstrum.deallocate() + // RTScratchBuffers free themselves; only the FFT setup needs manual teardown. vDSP_destroy_fftsetup(fftSetup) } @@ -121,9 +109,9 @@ internal final class CepstralEnvelopeEstimator { var floor: Float = CepstralEnvelopeEstimator.magnitudeFloor // _logMag = log(max(magnitudes, floor)) - vDSP_vthr(magnitudes, 1, &floor, _logMag, 1, vDSP_Length(n)) + vDSP_vthr(magnitudes, 1, &floor, _logMag.baseAddress, 1, vDSP_Length(n)) var nLog: Int32 = Int32(n) - vvlogf(_logMag, _logMag, &nLog) + vvlogf(_logMag.baseAddress, _logMag.baseAddress, &nLog) // Pack log-magnitudes into half-complex form for inverse real FFT. // realp[0] = log|X[0]| (DC) @@ -137,13 +125,13 @@ internal final class CepstralEnvelopeEstimator { _imagp[k] = 0 } - var split: DSPSplitComplex = DSPSplitComplex(realp: _realp, imagp: _imagp) + var split: DSPSplitComplex = DSPSplitComplex(realp: _realp.baseAddress, imagp: _imagp.baseAddress) // Inverse real FFT → split-complex packed time-domain of length fftSize. vDSP_fft_zrip(fftSetup, &split, 1, log2n, FFTDirection(kFFTDirection_Inverse)) // Unpack to contiguous real cepstrum. - _cepstrum.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in + _cepstrum.baseAddress.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in vDSP_ztoc(&split, 1, complexPtr, 2, vDSP_Length(halfSize)) } @@ -157,7 +145,7 @@ internal final class CepstralEnvelopeEstimator { } // Repack liftered cepstrum into split-complex for forward FFT. - _cepstrum.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in + _cepstrum.baseAddress.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in vDSP_ctoz(complexPtr, 2, &split, 1, vDSP_Length(halfSize)) } diff --git a/Sources/Lyrebird/Spectral/SpectralBuffer.swift b/Sources/Lyrebird/Spectral/SpectralBuffer.swift index 0953e07..3899a7b 100644 --- a/Sources/Lyrebird/Spectral/SpectralBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralBuffer.swift @@ -68,10 +68,10 @@ public final class SpectralBuffer: @unchecked Sendable { private var _nyquistValue: Float = 0 /// Magnitudes for complex bins 1..halfSize-1. Allocated at halfSize; index 0 unused. - private let _mag: UnsafeMutablePointer + private let _mag: RTScratchBuffer /// Phases (radians) for complex bins 1..halfSize-1. Allocated at halfSize; index 0 unused. - private let _phase: UnsafeMutablePointer + private let _phase: RTScratchBuffer private let _halfSize: Int private let _binCount: Int // halfSize - 1 (complex bins 1..halfSize-1) @@ -98,20 +98,13 @@ public final class SpectralBuffer: @unchecked Sendable { _halfSize = halfSize _binCount = halfSize - 1 // complex bins 1...allocate(capacity: halfSize) - _phase = UnsafeMutablePointer.allocate(capacity: halfSize) - _mag.initialize(repeating: 0, count: halfSize) - _phase.initialize(repeating: 0, count: halfSize) + _mag = RTScratchBuffer(count: halfSize) + _phase = RTScratchBuffer(count: halfSize) _isValid = Atomic(true) } - deinit { - _mag.deinitialize(count: _halfSize) - _mag.deallocate() - _phase.deinitialize(count: _halfSize) - _phase.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - Lifecycle @@ -241,28 +234,28 @@ public final class SpectralBuffer: @unchecked Sendable { /// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1). @discardableResult func withUnsafeMagnitudePointer(_ body: (UnsafePointer) -> R) -> R { - body(UnsafePointer(_mag.advanced(by: 1))) + body(UnsafePointer(_mag.baseAddress.advanced(by: 1))) } /// Call `body` with a mutable pointer to the magnitude array at index 1. /// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1). @discardableResult func withUnsafeMutableMagnitudePointer(_ body: (UnsafeMutablePointer) -> R) -> R { - body(_mag.advanced(by: 1)) + body(_mag.baseAddress.advanced(by: 1)) } /// Call `body` with a read-only pointer to the phase array at index 1. /// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1). @discardableResult func withUnsafePhasePointer(_ body: (UnsafePointer) -> R) -> R { - body(UnsafePointer(_phase.advanced(by: 1))) + body(UnsafePointer(_phase.baseAddress.advanced(by: 1))) } /// Call `body` with a mutable pointer to the phase array at index 1. /// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1). @discardableResult func withUnsafeMutablePhasePointer(_ body: (UnsafeMutablePointer) -> R) -> R { - body(_phase.advanced(by: 1)) + body(_phase.baseAddress.advanced(by: 1)) } // MARK: - Internal rectangular conversion (package-internal) @@ -287,8 +280,8 @@ public final class SpectralBuffer: @unchecked Sendable { let rp: UnsafePointer = realp.advanced(by: 1) let ip: UnsafePointer = imagp.advanced(by: 1) - let mp: UnsafeMutablePointer = _mag.advanced(by: 1) - let pp: UnsafeMutablePointer = _phase.advanced(by: 1) + let mp: UnsafeMutablePointer = _mag.baseAddress.advanced(by: 1) + let pp: UnsafeMutablePointer = _phase.baseAddress.advanced(by: 1) let n: vDSP_Length = vDSP_Length(_binCount) // Magnitudes: squared magnitude via vDSP, then vectorized sqrt. @@ -323,8 +316,8 @@ public final class SpectralBuffer: @unchecked Sendable { let rp: UnsafeMutablePointer = realp.advanced(by: 1) let ip: UnsafeMutablePointer = imagp.advanced(by: 1) - let mp: UnsafeMutablePointer = _mag.advanced(by: 1) - let pp: UnsafeMutablePointer = _phase.advanced(by: 1) + let mp: UnsafeMutablePointer = _mag.baseAddress.advanced(by: 1) + let pp: UnsafeMutablePointer = _phase.baseAddress.advanced(by: 1) let n: vDSP_Length = vDSP_Length(_binCount) var count: Int32 = Int32(_binCount) diff --git a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift index 57de1e7..1790192 100644 --- a/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift +++ b/Sources/Lyrebird/Spectral/SpectralFrameBuffer.swift @@ -45,10 +45,10 @@ public final class SpectralFrameBuffer: @unchecked Sendable { // MARK: - Internal storage (module-internal for FileIO and SpectralPlayBuffer access) - let _dc: UnsafeMutablePointer // [frameCount] - let _nyquist: UnsafeMutablePointer // [frameCount] - let _mag: UnsafeMutablePointer // [frameCount × halfSize]; index 0 per frame unused - let _phase: UnsafeMutablePointer // [frameCount × halfSize]; same layout + let _dc: RTScratchBuffer // [frameCount] + let _nyquist: RTScratchBuffer // [frameCount] + let _mag: RTScratchBuffer // [frameCount × halfSize]; index 0 per frame unused + let _phase: RTScratchBuffer // [frameCount × halfSize]; same layout let _binCount: Int // halfSize - 1 (complex bins 1...allocate(capacity: frameCount) - _nyquist = UnsafeMutablePointer.allocate(capacity: frameCount) - _mag = UnsafeMutablePointer.allocate(capacity: magPhaseCount) - _phase = UnsafeMutablePointer.allocate(capacity: magPhaseCount) - - _dc.initialize(repeating: 0, count: frameCount) - _nyquist.initialize(repeating: 0, count: frameCount) - _mag.initialize(repeating: 0, count: magPhaseCount) - _phase.initialize(repeating: 0, count: magPhaseCount) + _dc = RTScratchBuffer(count: frameCount) + _nyquist = RTScratchBuffer(count: frameCount) + _mag = RTScratchBuffer(count: magPhaseCount) + _phase = RTScratchBuffer(count: magPhaseCount) _isValid = Atomic(true) _framesWritten = Atomic(frameCount) } - deinit { - let magPhaseCount: Int = frameCount * halfSize - _dc.deinitialize(count: frameCount) - _dc.deallocate() - _nyquist.deinitialize(count: frameCount) - _nyquist.deallocate() - _mag.deinitialize(count: magPhaseCount) - _mag.deallocate() - _phase.deinitialize(count: magPhaseCount) - _phase.deallocate() - } + // No deinit: each RTScratchBuffer frees its own allocation exactly once. // MARK: - Phase interpolation (RT-safe) @@ -201,8 +186,8 @@ public final class SpectralFrameBuffer: @unchecked Sendable { newBuf._dc[f] = _dc[f] newBuf._nyquist[f] = _nyquist[f] let base: Int = f * halfSize - _ = memcpy(newBuf._mag + base + 1, _mag + base + 1, byteCount) - _ = memcpy(newBuf._phase + base + 1, _phase + base + 1, byteCount) + _ = memcpy(newBuf._mag.baseAddress + base + 1, _mag.baseAddress + base + 1, byteCount) + _ = memcpy(newBuf._phase.baseAddress + base + 1, _phase.baseAddress + base + 1, byteCount) } return newBuf } @@ -229,10 +214,10 @@ public final class SpectralFrameBuffer: @unchecked Sendable { let base: Int = frame * halfSize let byteCount: Int = _binCount * MemoryLayout.stride spectral.withUnsafeMagnitudePointer { src in - _ = memcpy(_mag + base + 1, src, byteCount) + _ = memcpy(_mag.baseAddress + base + 1, src, byteCount) } spectral.withUnsafePhasePointer { src in - _ = memcpy(_phase + base + 1, src, byteCount) + _ = memcpy(_phase.baseAddress + base + 1, src, byteCount) } } @@ -248,10 +233,10 @@ public final class SpectralFrameBuffer: @unchecked Sendable { let base: Int = frame * halfSize let byteCount: Int = _binCount * MemoryLayout.stride spectral.withUnsafeMutableMagnitudePointer { dst in - _ = memcpy(dst, _mag + base + 1, byteCount) + _ = memcpy(dst, _mag.baseAddress + base + 1, byteCount) } spectral.withUnsafeMutablePhasePointer { dst in - _ = memcpy(dst, _phase + base + 1, byteCount) + _ = memcpy(dst, _phase.baseAddress + base + 1, byteCount) } } @@ -274,8 +259,8 @@ public final class SpectralFrameBuffer: @unchecked Sendable { ) { var beta: Float = frac vDSP_vintb( - _mag + frameA * halfSize + 1, 1, - _mag + frameB * halfSize + 1, 1, + _mag.baseAddress + frameA * halfSize + 1, 1, + _mag.baseAddress + frameB * halfSize + 1, 1, &beta, dst + 1, 1, vDSP_Length(_binCount) diff --git a/Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift b/Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift index cfa45aa..c311d15 100644 --- a/Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift +++ b/Sources/Lyrebird/Spectral/SpectralFrameBufferFileIO.swift @@ -15,6 +15,9 @@ public enum SpectralFileError: Error, Equatable { case invalidMagic case invalidHeader case unsupportedVersion(UInt32) + /// An underlying `FileHandle` write / close failed. Associated value is the + /// system error's description. + case ioFailure(String) } // MARK: - .lbsf format constants @@ -73,7 +76,7 @@ extension SpectralFrameBuffer { /// `framesWritten` (not `frameCount`), and the body contains exactly that many frames. /// This ensures that a partially-filled buffer (e.g. a large pre-allocation used with /// `SpectralRecordBuffer`) produces a compact file without trailing garbage frames. - public func write(to url: URL) throws { + public func write(to url: URL) throws(SpectralFileError) { let path: String = url.path guard FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) else { throw SpectralFileError.cannotCreateFile @@ -87,7 +90,8 @@ extension SpectralFrameBuffer { defer { if !didClose { try? fh.close() } } let writtenCount: Int = min(framesWritten, frameCount) - try fh.write(contentsOf: _makeHeader(frameCount: writtenCount)) + do { try fh.write(contentsOf: _makeHeader(frameCount: writtenCount)) } + catch { throw SpectralFileError.ioFailure(String(describing: error)) } // Write body: one frame at a time to bound peak memory usage. let frameFloats: Int = fftSize // 1 + 1 + (halfSize-1) + (halfSize-1) = fftSize @@ -98,14 +102,16 @@ extension SpectralFrameBuffer { frameBuf[1] = _nyquist[f] frameBuf.withUnsafeMutableBufferPointer { ptr in guard let bptr: UnsafeMutablePointer = ptr.baseAddress else { return } - memcpy(bptr + 2, _mag + base + 1, _binCount * MemoryLayout.stride) - memcpy(bptr + 2 + _binCount, _phase + base + 1, _binCount * MemoryLayout.stride) + memcpy(bptr + 2, _mag.baseAddress + base + 1, _binCount * MemoryLayout.stride) + memcpy(bptr + 2 + _binCount, _phase.baseAddress + base + 1, _binCount * MemoryLayout.stride) } let frameData: Data = frameBuf.withUnsafeBufferPointer { Data(buffer: $0) } - try fh.write(contentsOf: frameData) + do { try fh.write(contentsOf: frameData) } + catch { throw SpectralFileError.ioFailure(String(describing: error)) } } - try fh.close() + do { try fh.close() } + catch { throw SpectralFileError.ioFailure(String(describing: error)) } didClose = true } @@ -114,7 +120,7 @@ extension SpectralFrameBuffer { /// Load a `.lbsf` file from `url` and return a new `SpectralFrameBuffer`. /// /// - Throws: `SpectralFileError` on invalid magic, unsupported version, or I/O failure. - public static func load(url: URL) throws -> SpectralFrameBuffer { + public static func load(url: URL) throws(SpectralFileError) -> SpectralFrameBuffer { guard let fh: FileHandle = try? FileHandle(forReadingFrom: url) else { throw SpectralFileError.cannotOpenFile } @@ -174,8 +180,8 @@ extension SpectralFrameBuffer { let frameBase: Int = f * buf.halfSize frameBuf.withUnsafeBufferPointer { ptr in guard let bptr: UnsafePointer = ptr.baseAddress else { return } - _ = memcpy(buf._mag + frameBase + 1, bptr + 2, binCount * MemoryLayout.stride) - _ = memcpy(buf._phase + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout.stride) + _ = memcpy(buf._mag.baseAddress + frameBase + 1, bptr + 2, binCount * MemoryLayout.stride) + _ = memcpy(buf._phase.baseAddress + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout.stride) } framesRead += 1 } diff --git a/Sources/Lyrebird/Synthesizer/SynthesizerBase.swift b/Sources/Lyrebird/Synthesizer/SynthesizerBase.swift index 09e0965..f1b194f 100644 --- a/Sources/Lyrebird/Synthesizer/SynthesizerBase.swift +++ b/Sources/Lyrebird/Synthesizer/SynthesizerBase.swift @@ -163,7 +163,7 @@ open class SynthesizerBase: Synthesizer { /// more useful than spinning. nonisolated private static let bindMaxPasses: Int = 2 - nonisolated internal func _bind(to engine: SynthesisEngine) throws { + nonisolated internal func _bind(to engine: SynthesisEngine) throws(EngineAddError) { let rawPointer: UnsafeMutableRawPointer = Unmanaged.passUnretained(engine).toOpaque() let target: UInt = UInt(bitPattern: rawPointer) @@ -403,7 +403,7 @@ open class SynthesizerBase: Synthesizer { /// - key: The property name of the `@LiveParam` / `@UIParam`. /// - value: New parameter value. /// - Throws: `ParameterUpdateError.keyNotFound` if no live parameter exists for `key`. - public final func updateParameter(_ key: String, value: Double) throws { + public final func updateParameter(_ key: String, value: Double) throws(ParameterUpdateError) { guard let entry: any LiveParameterValue = parameterTable.inputs[key] as? LiveParameterValue else { throw ParameterUpdateError.keyNotFound(key) } diff --git a/Sources/Lyrebird/Trigger/TriggerListener.swift b/Sources/Lyrebird/Trigger/TriggerListener.swift index 5153d01..062d209 100644 --- a/Sources/Lyrebird/Trigger/TriggerListener.swift +++ b/Sources/Lyrebird/Trigger/TriggerListener.swift @@ -40,21 +40,30 @@ import Synchronization /// during `NRTDriver.start()` in NRT mode. The `LyrebirdMessageContext` passed to handlers /// dispatches engine mutations to the main thread (RT) or inline (NRT). public final class TriggerListener: @unchecked Sendable { - // Sendable invariant: `handlers` is serialised by `lock` for all reads and writes; - // `nextTokenID` is `Atomic`. All other stored state is immutable `let` references. + // @unchecked Sendable invariant: + // - `_handlers` (Sendable) is a `Mutex`, so its access is compiler-serialised. + // - `source` is a `DispatchSourceUserDataAdd`, touched only on the main thread + // (the start / stop / detach lifecycle). It is a plain var, NOT in the Mutex, + // because it is non-Sendable on Linux and must be handed back out (to cancel, + // and to build the RT signal closure) — `Mutex.withLock`'s `sending` inout + // cannot extract a non-Sendable value from the guarded region. + // - `engine` is a non-Sendable class shared across the engine graph — the sole + // reason this stays `@unchecked` rather than a checked `Sendable`. + // - `handlerQueue` is immutable; `nextTokenID` is `Atomic`. private let engine: SynthesisEngine - - private let lock: NSLock = NSLock() - private var handlers: [(token: TriggerHandlerToken, id: Int32?, - onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void)] = [] private let nextTokenID: Atomic = Atomic(0) - private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.trigger", qos: .userInteractive) - /// Dispatch source that wakes `handlerQueue` when `engine._postTrigger` is called. - /// Created and activated in `start()`; cancelled in `stop()`. - private var source: DispatchSourceUserDataAdd? + private typealias Handler = (token: TriggerHandlerToken, id: Int32?, + onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void) + + /// Registered handler list — Sendable, so compiler-guarded by a `Mutex`. + private let _handlers: Mutex<[Handler]> = Mutex([]) + + /// Dispatch source that wakes `handlerQueue` when the RT thread posts a trigger. + /// Created in `start()`, cancelled in `stop()`; main-thread-confined by contract. + private var source: (any DispatchSourceUserDataAdd)? /// Creates a listener and immediately attaches it to `engine`. /// No separate `engine.attachTriggerListener` call is needed. @@ -120,13 +129,13 @@ public final class TriggerListener: @unchecked Sendable { ) -> TriggerHandlerToken { let rawID: UInt64 = nextTokenID.add(1, ordering: .acquiringAndReleasing).newValue let token: TriggerHandlerToken = TriggerHandlerToken(id: rawID) - lock.withLock { handlers.append((token, id, onEvent)) } + _handlers.withLock { $0.append((token, id, onEvent)) } return token } /// Remove the handler identified by `token`. Thread-safe; safe to call from any queue. public func removeHandler(_ token: TriggerHandlerToken) { - lock.withLock { handlers.removeAll { $0.token == token } } + _handlers.withLock { s in s.removeAll { $0.token == token } } } // MARK: - Internal: RT signal closure preparation @@ -169,9 +178,9 @@ public final class TriggerListener: @unchecked Sendable { } private func _dispatchEvents(ctx: LyrebirdMessageContext) { - let snapshot: [(token: TriggerHandlerToken, id: Int32?, onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void)] = lock.withLock { handlers } + let snapshot: [Handler] = _handlers.withLock { $0 } while let event: TriggerEvent = engine.triggerQueue.dequeue() { - for entry: (token: TriggerHandlerToken, id: Int32?, onEvent: @Sendable (TriggerEvent, LyrebirdMessageContext) -> Void) in snapshot where entry.id == nil || entry.id == event.id { + for entry: Handler in snapshot where entry.id == nil || entry.id == event.id { entry.onEvent(event, ctx) } } diff --git a/Sources/LyrebirdCLI/Version.swift b/Sources/LyrebirdCLI/Version.swift index 2daa155..572ff70 100644 --- a/Sources/LyrebirdCLI/Version.swift +++ b/Sources/LyrebirdCLI/Version.swift @@ -5,7 +5,7 @@ // SPDX-License-Identifier: MIT /// The current Lyrebird framework and CLI version. -public let lyrebirdVersion: String = "2.0.0" +public let lyrebirdVersion: String = "2.1.0" /// The banner printed when the interactive shell or REPL session starts. public let welcomeBanner: String = """ diff --git a/Tests/LyrebirdTests/Buffers/RTScratchBufferTests.swift b/Tests/LyrebirdTests/Buffers/RTScratchBufferTests.swift new file mode 100644 index 0000000..91def28 --- /dev/null +++ b/Tests/LyrebirdTests/Buffers/RTScratchBufferTests.swift @@ -0,0 +1,60 @@ +// RTScratchBufferTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@Suite("RTScratchBuffer") +struct RTScratchBufferTests { + + @Test("init allocates the requested count, zero-filled") + func initZeroFills() { + let buf: RTScratchBuffer = RTScratchBuffer(count: 8) + #expect(buf.count == 8) + for i: Int in 0..<8 { + #expect(buf[i] == 0) + } + } + + @Test("init(count:repeating:) fills with the given value") + func initRepeatingFills() { + let buf: RTScratchBuffer = RTScratchBuffer(count: 5, repeating: 1) + #expect(buf.count == 5) + for i: Int in 0..<5 { + #expect(buf[i] == 1) + } + } + + @Test("subscript round-trips writes") + func subscriptRoundTrip() { + let buf: RTScratchBuffer = RTScratchBuffer(count: 4) + buf[0] = 1.5 + buf[3] = -2.25 + #expect(buf[0] == 1.5) + #expect(buf[1] == 0) + #expect(buf[3] == -2.25) + } + + @Test("baseAddress aliases the same storage as subscript") + func baseAddressAliasesStorage() { + let buf: RTScratchBuffer = RTScratchBuffer(count: 3) + buf[1] = 42 + #expect(buf.baseAddress[1] == 42) + buf.baseAddress[2] = 7 + #expect(buf[2] == 7) + } + + @Test("buffers of the same element type own distinct allocations") + func distinctAllocations() { + let a: RTScratchBuffer = RTScratchBuffer(count: 2) + let b: RTScratchBuffer = RTScratchBuffer(count: 2) + a[0] = 100 + b[0] = 200 + #expect(a[0] == 100) + #expect(b[0] == 200) + #expect(a.baseAddress != b.baseAddress) + } +} diff --git a/docs/engine/portable-wav-codec.md b/docs/engine/portable-wav-codec.md index 29d2542..b505186 100644 --- a/docs/engine/portable-wav-codec.md +++ b/docs/engine/portable-wav-codec.md @@ -72,7 +72,12 @@ reader.close() `WavFileError` — `.cannotCreate`, `.cannotOpen`, `.notWave`, `.unsupportedFormat(formatTag:bitsPerSample:)`, `.truncated`, -`.fileTooLarge(bytes:)`. +`.fileTooLarge(bytes:)`, `.ioFailure(String)`. + +`.ioFailure` carries the description of an underlying `FileHandle` +read / seek / write / close failure, funneled from the platform I/O layer so +the reader and writer surface a single typed error rather than a raw +`NSError`. These escape `NRTDriver` and `LyrebirdBuffer` file I/O **on non-Apple platforms**, where this codec is the backend. Error handling written against diff --git a/docs/protocols/extension-sdk.md b/docs/protocols/extension-sdk.md index 9e80e8b..711ec12 100644 --- a/docs/protocols/extension-sdk.md +++ b/docs/protocols/extension-sdk.md @@ -93,6 +93,21 @@ when Lyrebird's MINOR rolls over. | `func fillRampedResult(into:from:to:mulAdd:graph:count:)` | ControlGenerator ramp helper | | `func lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` | block-constant capture from a generator input | +### Scratch buffers (`Buffers/RTScratchBuffer.swift`) + +| Symbol | Signature | +|---|---| +| `struct RTScratchBuffer: ~Copyable` | single-owner heap scratch buffer; compiler-enforced single free at `deinit`, no ARC | +| `RTScratchBuffer.init(count:)` | allocate + zero-fill (`Element: Numeric`) | +| `RTScratchBuffer.init(count:repeating:)` | allocate + fill with a value | +| `RTScratchBuffer.baseAddress` / `.count` / `subscript` | `@inline(__always)`; `baseAddress` for vDSP / Accelerate / `memcpy` interop | + +Replaces the hand-paired `UnsafeMutablePointer.allocate` / `deinitialize` / +`deallocate` in a scratch-owning generator. Store as a `let` assigned in `init` +(never a per-call local) so `deinit` frees off the RT thread. Not for +`[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` type cannot be +`Array`-stored) or capacity-1 scalar boxes used via `.pointee` — leave those raw. + ### PRNG (`Generators/Noise/WhiteNoise.swift`) | Symbol | Signature | diff --git a/docs/protocols/writing-generators.md b/docs/protocols/writing-generators.md index be8da2a..083b2cb 100644 --- a/docs/protocols/writing-generators.md +++ b/docs/protocols/writing-generators.md @@ -1014,6 +1014,28 @@ A family of module-level free functions, base classes, and methods exist to elim > **Out-of-tree extension packages:** these helpers are exposed as `@_spi(LyrebirdExtensions) public`. Add `@_spi(LyrebirdExtensions) import LyrebirdSynth` to any generator implementation file outside the core module. Full surface and stability policy: [extension-sdk.md](extension-sdk.md). +### `RTScratchBuffer` — single-owner RAII scratch buffer + +`Buffers/RTScratchBuffer.swift`. A `~Copyable` heap buffer that replaces the +hand-paired `UnsafeMutablePointer.allocate` / `deinitialize` / `deallocate` a +scratch-owning generator otherwise repeats per buffer. The compiler guarantees it +is freed exactly once at `deinit` (with the right count) and can never be +copy-aliased; it carries no ARC and every accessor is `@inline(__always)`, so a +hot loop compiles to the same code as the raw pointer it replaces. + +- `init(count:)` allocates + zero-fills (`Element: Numeric`); `init(count:repeating:)` + fills with any value (e.g. a unity gain table: `RTScratchBuffer(count: n, repeating: 1)`). +- Element access is `buffer[i]` (subscript; the setter is `nonmutating`, so a + `let`-held buffer is still writable — matching the raw pointer). Pass + `buffer.baseAddress` to vDSP / Accelerate / `memcpy`; for an offset use + `buffer.baseAddress + k` / `.baseAddress.advanced(by: k)`. +- **Must be a stored property assigned in `init`** — never a local inside + `process` / `_computeSamples`, which would allocate + free every render call. +- Not for `[UnsafeMutablePointer]`-style per-channel arrays (a `~Copyable` type + cannot be stored in an `Array`) nor for capacity-1 scalar boxes used via + `.pointee`; leave those on raw pointers. +- `@_spi(LyrebirdExtensions) public` — add the SPI import in out-of-tree files. + ### `_resolvedInput()` — init-time resolution of `any ValidGeneratorInput` Protocol requirement on `ValidGeneratorInput`. Default impl returns `self`; `GeneratorInputProvider` overrides to call its `make` closure and return a fresh `any ValidGeneratorInput`. Every Generator `init` that takes `any ValidGeneratorInput` parameters MUST call `_resolvedInput()` on each slot before storing or running `is any Generator` classification. diff --git a/docs/tooling/nrt-guide.md b/docs/tooling/nrt-guide.md index fe741f1..fcdaaf8 100644 --- a/docs/tooling/nrt-guide.md +++ b/docs/tooling/nrt-guide.md @@ -449,7 +449,8 @@ if task.terminationStatus == 0 { > **Off Apple (Linux/Windows):** the portable WAV codec backs these renders, so > a `WavFileError` — `.cannotCreate`, `.cannotOpen`, `.notWave`, -> `.unsupportedFormat`, `.truncated`, `.fileTooLarge` — can also escape +> `.unsupportedFormat`, `.truncated`, `.fileTooLarge`, `.ioFailure` (an +> underlying `FileHandle` failure) — can also escape > `NRTDriver.setup`/`start`. A handler written against `NRTDriverError` alone > will miss those. The Apple-only containers (CAF, AIFF-C, AAC, ALAC) throw > `NRTDriverError.unsupportedFormatOnPlatform` there; render to