Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 844dc4d9cd | |||
| 2c20b02e59 |
@@ -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<Element>` — `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
|
||||
|
||||
+24
@@ -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<State>` 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.
|
||||
|
||||
@@ -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<Float>, frames: Int) throws {
|
||||
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, 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() }
|
||||
|
||||
@@ -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<Float>
|
||||
/// 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<Element>: ~Copyable {
|
||||
|
||||
@usableFromInline let _base: UnsafeMutablePointer<Element>
|
||||
@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<Element>.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<Element> { _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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -61,10 +61,10 @@ public final class Audio: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - RT-only working storage (UnsafeMutablePointer — no CoW, no ARC)
|
||||
|
||||
private let _interpMag: UnsafeMutablePointer<Float> // [halfSize]; index 0 unused
|
||||
private let _phases: UnsafeMutablePointer<Float> // [halfSize]; index 0 unused
|
||||
private let _phaseIncrements: UnsafeMutablePointer<Float> // [halfSize]; index 0 unused
|
||||
private let _sinBuf: UnsafeMutablePointer<Float> // [halfSize]; scratch for vvsinf
|
||||
private let _interpMag: RTScratchBuffer<Float> // [halfSize]; index 0 unused
|
||||
private let _phases: RTScratchBuffer<Float> // [halfSize]; index 0 unused
|
||||
private let _phaseIncrements: RTScratchBuffer<Float> // [halfSize]; index 0 unused
|
||||
private let _sinBuf: RTScratchBuffer<Float> // [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<Float>.allocate(capacity: hs)
|
||||
_phases = UnsafeMutablePointer<Float>.allocate(capacity: hs)
|
||||
_phaseIncrements = UnsafeMutablePointer<Float>.allocate(capacity: hs)
|
||||
_sinBuf = UnsafeMutablePointer<Float>.allocate(capacity: hs)
|
||||
_interpMag = RTScratchBuffer<Float>(count: hs)
|
||||
_phases = RTScratchBuffer<Float>(count: hs)
|
||||
_phaseIncrements = RTScratchBuffer<Float>(count: hs)
|
||||
_sinBuf = RTScratchBuffer<Float>(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..<count {
|
||||
// Advance phases for all active partials.
|
||||
vDSP_vadd(
|
||||
_phases + 1, 1,
|
||||
_phaseIncrements + 1, 1,
|
||||
_phases + 1, 1,
|
||||
_phases.baseAddress + 1, 1,
|
||||
_phaseIncrements.baseAddress + 1, 1,
|
||||
_phases.baseAddress + 1, 1,
|
||||
activePartialCount
|
||||
)
|
||||
// Compute sines of current phases.
|
||||
var n: Int32 = Int32(_activePartials)
|
||||
vvsinf(_sinBuf + 1, _phases + 1, &n)
|
||||
vvsinf(_sinBuf.baseAddress + 1, _phases.baseAddress + 1, &n)
|
||||
// Dot product of sines with interpolated magnitudes → one output sample.
|
||||
var dot: Float = 0
|
||||
vDSP_dotpr(
|
||||
_sinBuf + 1, 1,
|
||||
_interpMag + 1, 1,
|
||||
_sinBuf.baseAddress + 1, 1,
|
||||
_interpMag.baseAddress + 1, 1,
|
||||
&dot,
|
||||
activePartialCount
|
||||
)
|
||||
|
||||
@@ -69,7 +69,6 @@ public final class OnsetDetector: SpectralProcessor {
|
||||
|
||||
// MARK: - Geometry (immutable)
|
||||
|
||||
private let _halfSize: Int
|
||||
private let _binCount: Int // complex bins 1 ..< halfSize
|
||||
private let _method: OnsetDetectionMethod
|
||||
private let _medianWindowFrames: Int
|
||||
@@ -129,25 +128,24 @@ public final class OnsetDetector: SpectralProcessor {
|
||||
|
||||
// MARK: - Per-bin state (RT thread only)
|
||||
|
||||
private let _prevMag: UnsafeMutablePointer<Float>
|
||||
private let _prevPhase: UnsafeMutablePointer<Float>
|
||||
private let _prevPrevPhase: UnsafeMutablePointer<Float>
|
||||
private let _prevMag: RTScratchBuffer<Float>
|
||||
private let _prevPhase: RTScratchBuffer<Float>
|
||||
private let _prevPrevPhase: RTScratchBuffer<Float>
|
||||
|
||||
/// 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..<halfSize`.
|
||||
private let _curPhaseScratch: UnsafeMutablePointer<Float>
|
||||
private let _predPhaseScratch: UnsafeMutablePointer<Float>
|
||||
private let _curCosBuf: UnsafeMutablePointer<Float>
|
||||
private let _curSinBuf: UnsafeMutablePointer<Float>
|
||||
private let _predCosBuf: UnsafeMutablePointer<Float>
|
||||
private let _predSinBuf: UnsafeMutablePointer<Float>
|
||||
private let _trigScratchCount: Int // 0 when unused, halfSize when method == .complexDomain
|
||||
private let _curPhaseScratch: RTScratchBuffer<Float>
|
||||
private let _predPhaseScratch: RTScratchBuffer<Float>
|
||||
private let _curCosBuf: RTScratchBuffer<Float>
|
||||
private let _curSinBuf: RTScratchBuffer<Float>
|
||||
private let _predCosBuf: RTScratchBuffer<Float>
|
||||
private let _predSinBuf: RTScratchBuffer<Float>
|
||||
|
||||
// MARK: - Median ring (RT thread only)
|
||||
|
||||
private let _odfRing: UnsafeMutablePointer<Float>
|
||||
private let _medianScratch: UnsafeMutablePointer<Float>
|
||||
private let _odfRing: RTScratchBuffer<Float>
|
||||
private let _medianScratch: RTScratchBuffer<Float>
|
||||
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<Float>.allocate(capacity: halfSize)
|
||||
_prevMag.initialize(repeating: 0, count: halfSize)
|
||||
_prevPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_prevPhase.initialize(repeating: 0, count: halfSize)
|
||||
_prevPrevPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_prevPrevPhase.initialize(repeating: 0, count: halfSize)
|
||||
_prevMag = RTScratchBuffer<Float>(count: halfSize)
|
||||
_prevPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
_prevPrevPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
|
||||
_odfRing = UnsafeMutablePointer<Float>.allocate(capacity: medianWindowFrames)
|
||||
_odfRing.initialize(repeating: 0, count: medianWindowFrames)
|
||||
_medianScratch = UnsafeMutablePointer<Float>.allocate(capacity: medianWindowFrames)
|
||||
_medianScratch.initialize(repeating: 0, count: medianWindowFrames)
|
||||
_odfRing = RTScratchBuffer<Float>(count: medianWindowFrames)
|
||||
_medianScratch = RTScratchBuffer<Float>(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<Float>.allocate(capacity: trigCount)
|
||||
_curPhaseScratch.initialize(repeating: 0, count: trigCount)
|
||||
_predPhaseScratch = UnsafeMutablePointer<Float>.allocate(capacity: trigCount)
|
||||
_predPhaseScratch.initialize(repeating: 0, count: trigCount)
|
||||
_curCosBuf = UnsafeMutablePointer<Float>.allocate(capacity: trigCount)
|
||||
_curCosBuf.initialize(repeating: 0, count: trigCount)
|
||||
_curSinBuf = UnsafeMutablePointer<Float>.allocate(capacity: trigCount)
|
||||
_curSinBuf.initialize(repeating: 0, count: trigCount)
|
||||
_predCosBuf = UnsafeMutablePointer<Float>.allocate(capacity: trigCount)
|
||||
_predCosBuf.initialize(repeating: 0, count: trigCount)
|
||||
_predSinBuf = UnsafeMutablePointer<Float>.allocate(capacity: trigCount)
|
||||
_predSinBuf.initialize(repeating: 0, count: trigCount)
|
||||
_curPhaseScratch = RTScratchBuffer<Float>(count: trigCount)
|
||||
_predPhaseScratch = RTScratchBuffer<Float>(count: trigCount)
|
||||
_curCosBuf = RTScratchBuffer<Float>(count: trigCount)
|
||||
_curSinBuf = RTScratchBuffer<Float>(count: trigCount)
|
||||
_predCosBuf = RTScratchBuffer<Float>(count: trigCount)
|
||||
_predSinBuf = RTScratchBuffer<Float>(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..<binCount {
|
||||
let k: Int = i + 1
|
||||
|
||||
@@ -77,17 +77,17 @@ public final class SpectralBinDelay: SpectralProcessor {
|
||||
private let _feedbacksSlot: RTBufferSlot
|
||||
|
||||
/// Pre-allocated scratch for the per-hop snapshot of delayTimes.
|
||||
private let _delayFramesScratch: UnsafeMutablePointer<Int>
|
||||
private let _delayFramesScratch: RTScratchBuffer<Int>
|
||||
/// Pre-allocated scratch for the per-hop snapshot of feedbacks.
|
||||
private let _feedbackScratch: UnsafeMutablePointer<Float>
|
||||
private let _feedbackScratch: RTScratchBuffer<Float>
|
||||
|
||||
/// Conversion factor: hop-frames per second of delay time. `sampleRate / hopSize`.
|
||||
private let _framesPerSecond: Double
|
||||
|
||||
// MARK: - Ring storage (rectangular)
|
||||
|
||||
private let _ringReal: UnsafeMutablePointer<Float>
|
||||
private let _ringImag: UnsafeMutablePointer<Float>
|
||||
private let _ringReal: RTScratchBuffer<Float>
|
||||
private let _ringImag: RTScratchBuffer<Float>
|
||||
|
||||
/// 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<Int>.allocate(capacity: halfSize)
|
||||
_delayFramesScratch.initialize(repeating: 0, count: halfSize)
|
||||
_feedbackScratch = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_feedbackScratch.initialize(repeating: 0, count: halfSize)
|
||||
_delayFramesScratch = RTScratchBuffer<Int>(count: halfSize)
|
||||
_feedbackScratch = RTScratchBuffer<Float>(count: halfSize)
|
||||
|
||||
let ringCells: Int = halfSize * numFrames
|
||||
_ringReal = UnsafeMutablePointer<Float>.allocate(capacity: ringCells)
|
||||
_ringReal.initialize(repeating: 0, count: ringCells)
|
||||
_ringImag = UnsafeMutablePointer<Float>.allocate(capacity: ringCells)
|
||||
_ringImag.initialize(repeating: 0, count: ringCells)
|
||||
_ringReal = RTScratchBuffer<Float>(count: ringCells)
|
||||
_ringImag = RTScratchBuffer<Float>(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
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ public final class SpectralBlur: SpectralProcessor {
|
||||
private let _binCount: Int
|
||||
|
||||
private let _radius: Atomic<Int>
|
||||
private let _blurOut: UnsafeMutablePointer<Float> // [_binCount]
|
||||
private let _blurOut: RTScratchBuffer<Float> // [_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<Float>.allocate(capacity: allocCount)
|
||||
_blurOut.initialize(repeating: 0, count: allocCount)
|
||||
_blurOut = RTScratchBuffer<Float>(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.
|
||||
|
||||
@@ -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<Float> // interpolated magnitude scratch
|
||||
private let _interpPhase: UnsafeMutablePointer<Float> // interpolated phase scratch
|
||||
private let _interpMag: RTScratchBuffer<Float> // interpolated magnitude scratch
|
||||
private let _interpPhase: RTScratchBuffer<Float> // 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<Float>.allocate(capacity: ptrSize)
|
||||
_interpPhase = UnsafeMutablePointer<Float>.allocate(capacity: ptrSize)
|
||||
_interpMag.initialize(repeating: 0, count: ptrSize)
|
||||
_interpPhase.initialize(repeating: 0, count: ptrSize)
|
||||
_interpMag = RTScratchBuffer<Float>(count: ptrSize)
|
||||
_interpPhase = RTScratchBuffer<Float>(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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Float>
|
||||
private let _imag: UnsafeMutablePointer<Float>
|
||||
private let _real: RTScratchBuffer<Float>
|
||||
private let _imag: RTScratchBuffer<Float>
|
||||
|
||||
/// - 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<Float>.allocate(capacity: _halfSize)
|
||||
_imag = UnsafeMutablePointer<Float>.allocate(capacity: _halfSize)
|
||||
_real.initialize(repeating: 0, count: _halfSize)
|
||||
_imag.initialize(repeating: 0, count: _halfSize)
|
||||
_real = RTScratchBuffer<Float>(count: _halfSize)
|
||||
_imag = RTScratchBuffer<Float>(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..<halfSize] + _imag[1..<halfSize].
|
||||
spectral._readToRectangular(realp: _real, imagp: _imag)
|
||||
spectral._readToRectangular(realp: _real.baseAddress, imagp: _imag.baseAddress)
|
||||
|
||||
// Step 2: invoke the closure with Cartesian access.
|
||||
let realBuf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(start: _real, count: _halfSize)
|
||||
let imagBuf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(start: _imag, count: _halfSize)
|
||||
let realBuf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(start: _real.baseAddress, count: _halfSize)
|
||||
let imagBuf: UnsafeMutableBufferPointer<Float> = 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
|
||||
}
|
||||
|
||||
@@ -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<Float>
|
||||
private let _templateMag: RTScratchBuffer<Float>
|
||||
|
||||
// MARK: - Initialisation
|
||||
|
||||
@@ -140,14 +140,10 @@ public final class SpectralCrossMap: SpectralProcessor2 {
|
||||
_floor = Atomic(Float(floor))
|
||||
_mode = Atomic(Float(mode))
|
||||
|
||||
_templateMag = UnsafeMutablePointer<Float>.allocate(capacity: _halfSize)
|
||||
_templateMag.initialize(repeating: 0, count: _halfSize)
|
||||
_templateMag = RTScratchBuffer<Float>(count: _halfSize)
|
||||
}
|
||||
|
||||
deinit {
|
||||
_templateMag.deinitialize(count: _halfSize)
|
||||
_templateMag.deallocate()
|
||||
}
|
||||
// No deinit: each RTScratchBuffer frees its own allocation exactly once.
|
||||
|
||||
// MARK: - SpectralProcessor2
|
||||
|
||||
|
||||
@@ -96,17 +96,17 @@ public final class SpectralFormantShift: SpectralProcessor {
|
||||
|
||||
/// Working magnitude buffer (`|DC|`, complex-bin mags, `|Nyquist|`).
|
||||
/// Length `halfSize + 1`.
|
||||
private let _magSource: UnsafeMutablePointer<Float>
|
||||
private let _magSource: RTScratchBuffer<Float>
|
||||
|
||||
/// Smooth envelope produced by the estimator. Length `halfSize + 1`.
|
||||
private let _envelope: UnsafeMutablePointer<Float>
|
||||
private let _envelope: RTScratchBuffer<Float>
|
||||
|
||||
/// Whitened residual `magSource / (envelope + ε)`. Length `halfSize + 1`.
|
||||
private let _residual: UnsafeMutablePointer<Float>
|
||||
private let _residual: RTScratchBuffer<Float>
|
||||
|
||||
/// Envelope resampled along the bin axis by `shiftRatio`. Length
|
||||
/// `halfSize + 1`.
|
||||
private let _newEnvelope: UnsafeMutablePointer<Float>
|
||||
private let _newEnvelope: RTScratchBuffer<Float>
|
||||
|
||||
/// - 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<Float>.allocate(capacity: n)
|
||||
_envelope = UnsafeMutablePointer<Float>.allocate(capacity: n)
|
||||
_residual = UnsafeMutablePointer<Float>.allocate(capacity: n)
|
||||
_newEnvelope = UnsafeMutablePointer<Float>.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<Float>(count: n)
|
||||
_envelope = RTScratchBuffer<Float>(count: n)
|
||||
_residual = RTScratchBuffer<Float>(count: n)
|
||||
_newEnvelope = RTScratchBuffer<Float>(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 + ε).
|
||||
|
||||
@@ -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<Float> // [halfSize] — phase at previous hop
|
||||
private let _phaseDelta: UnsafeMutablePointer<Float>// [halfSize] — principal phase increment per hop
|
||||
private let _frozenMag: UnsafeMutablePointer<Float> // [halfSize] — frozen magnitudes (index 1+)
|
||||
private let _frozenPhase: UnsafeMutablePointer<Float>// [halfSize] — running phase accumulator
|
||||
private let _prevPhase: RTScratchBuffer<Float> // [halfSize] — phase at previous hop
|
||||
private let _phaseDelta: RTScratchBuffer<Float>// [halfSize] — principal phase increment per hop
|
||||
private let _frozenMag: RTScratchBuffer<Float> // [halfSize] — frozen magnitudes (index 1+)
|
||||
private let _frozenPhase: RTScratchBuffer<Float>// [halfSize] — running phase accumulator
|
||||
|
||||
// MARK: - Public state
|
||||
|
||||
@@ -71,27 +71,14 @@ public final class SpectralFreeze: SpectralProcessor {
|
||||
_isFrozen = Atomic(false)
|
||||
_freezeRequested = Atomic(false)
|
||||
|
||||
_prevPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_phaseDelta = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_frozenMag = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_frozenPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_prevPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
_phaseDelta = RTScratchBuffer<Float>(count: halfSize)
|
||||
_frozenMag = RTScratchBuffer<Float>(count: halfSize)
|
||||
_frozenPhase = RTScratchBuffer<Float>(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<Float> = _frozenPhase.advanced(by: 1)
|
||||
let pd: UnsafeMutablePointer<Float> = _phaseDelta.advanced(by: 1)
|
||||
let fm: UnsafeMutablePointer<Float> = _frozenMag.advanced(by: 1)
|
||||
let fp: UnsafeMutablePointer<Float> = _frozenPhase.baseAddress.advanced(by: 1)
|
||||
let pd: UnsafeMutablePointer<Float> = _phaseDelta.baseAddress.advanced(by: 1)
|
||||
let fm: UnsafeMutablePointer<Float> = _frozenMag.baseAddress.advanced(by: 1)
|
||||
|
||||
// Advance phase: frozenPhase[k] += phaseDelta[k]
|
||||
vDSP_vadd(fp, 1, pd, 1, fp, 1, n)
|
||||
|
||||
@@ -65,8 +65,8 @@ public final class SpectralNoiseFilter: SpectralProcessor {
|
||||
|
||||
// MARK: - Per-bin state
|
||||
|
||||
private let _prevPhase: UnsafeMutablePointer<Float>
|
||||
private let _history: UnsafeMutablePointer<Float>
|
||||
private let _prevPhase: RTScratchBuffer<Float>
|
||||
private let _history: RTScratchBuffer<Float>
|
||||
private var _curFrame: Int = 0
|
||||
private var _warmupRemaining: Int
|
||||
|
||||
@@ -107,22 +107,15 @@ public final class SpectralNoiseFilter: SpectralProcessor {
|
||||
|
||||
_threshold = Atomic(Float(threshold))
|
||||
|
||||
_prevPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_prevPhase.initialize(repeating: 0, count: halfSize)
|
||||
_prevPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
|
||||
let historyCount: Int = halfSize * numFrames
|
||||
_history = UnsafeMutablePointer<Float>.allocate(capacity: historyCount)
|
||||
_history.initialize(repeating: 0, count: historyCount)
|
||||
_history = RTScratchBuffer<Float>(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
|
||||
|
||||
|
||||
@@ -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<Float>
|
||||
private let _prevPhase: RTScratchBuffer<Float>
|
||||
|
||||
/// Ring of per-bin metric history. Layout: `_history[bin * numFrames + frame]`
|
||||
/// where `bin ∈ 1..<halfSize` and `frame ∈ 0..<numFrames`.
|
||||
/// Total length: `halfSize * numFrames`.
|
||||
private let _history: UnsafeMutablePointer<Float>
|
||||
private let _history: RTScratchBuffer<Float>
|
||||
|
||||
/// 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<Float>.allocate(capacity: halfSize)
|
||||
_prevPhase.initialize(repeating: 0, count: halfSize)
|
||||
_prevPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
|
||||
let historyCount: Int = halfSize * numFrames
|
||||
_history = UnsafeMutablePointer<Float>.allocate(capacity: historyCount)
|
||||
_history.initialize(repeating: 0, count: historyCount)
|
||||
_history = RTScratchBuffer<Float>(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
|
||||
|
||||
|
||||
@@ -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<Float>
|
||||
private let _prevPhase: RTScratchBuffer<Float>
|
||||
|
||||
/// Synthesis phase accumulator — advanced by the true-frequency-scaled step each hop.
|
||||
private let _synthPhase: UnsafeMutablePointer<Float>
|
||||
private let _synthPhase: RTScratchBuffer<Float>
|
||||
|
||||
/// Scratch buffer for remapped magnitudes. Zeroed before each hop's accumulation pass.
|
||||
private let _shiftedMag: UnsafeMutablePointer<Float>
|
||||
private let _shiftedMag: RTScratchBuffer<Float>
|
||||
|
||||
/// True-frequency bin `k + deviation / (2π/hop)` computed in Pass 1 and read in Pass 2.
|
||||
private let _trueFreqBin: UnsafeMutablePointer<Float>
|
||||
private let _trueFreqBin: RTScratchBuffer<Float>
|
||||
|
||||
// MARK: - Initialisation
|
||||
|
||||
@@ -96,27 +96,13 @@ public final class SpectralPitchShift: SpectralProcessor {
|
||||
|
||||
_pitchRatio = Atomic(Float(pitchRatio))
|
||||
|
||||
_prevPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_synthPhase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_shiftedMag = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_trueFreqBin = UnsafeMutablePointer<Float>.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<Float>(count: halfSize)
|
||||
_synthPhase = RTScratchBuffer<Float>(count: halfSize)
|
||||
_shiftedMag = RTScratchBuffer<Float>(count: halfSize)
|
||||
_trueFreqBin = RTScratchBuffer<Float>(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).
|
||||
|
||||
@@ -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<Float> // synthesis phase accumulator
|
||||
private let _interpMag: UnsafeMutablePointer<Float> // interpolated magnitudes scratch
|
||||
private let _phaseDelta: UnsafeMutablePointer<Float> // inter-frame phase delta scratch
|
||||
private let _synthPhase: RTScratchBuffer<Float> // synthesis phase accumulator
|
||||
private let _interpMag: RTScratchBuffer<Float> // interpolated magnitudes scratch
|
||||
private let _phaseDelta: RTScratchBuffer<Float> // 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<Float>.allocate(capacity: ptrSize)
|
||||
_interpMag = UnsafeMutablePointer<Float>.allocate(capacity: ptrSize)
|
||||
_phaseDelta = UnsafeMutablePointer<Float>.allocate(capacity: ptrSize)
|
||||
_synthPhase.initialize(repeating: 0, count: ptrSize)
|
||||
_interpMag.initialize(repeating: 0, count: ptrSize)
|
||||
_phaseDelta.initialize(repeating: 0, count: ptrSize)
|
||||
_synthPhase = RTScratchBuffer<Float>(count: ptrSize)
|
||||
_interpMag = RTScratchBuffer<Float>(count: ptrSize)
|
||||
_phaseDelta = RTScratchBuffer<Float>(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.
|
||||
|
||||
@@ -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<Float>
|
||||
private let _gainTable: RTScratchBuffer<Float>
|
||||
|
||||
/// - 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<Float>.allocate(capacity: tableCount)
|
||||
_gainTable.initialize(repeating: 1, count: tableCount)
|
||||
_gainTable = RTScratchBuffer<Float>(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<Float> = _gainTable.advanced(by: 1)
|
||||
let gainComplex: UnsafeMutablePointer<Float> = _gainTable.baseAddress.advanced(by: 1)
|
||||
spectral.withUnsafeMutableMagnitudePointer { mp in
|
||||
vDSP_vmul(mp, 1, gainComplex, 1, mp, 1, vDSP_Length(_binCount))
|
||||
}
|
||||
|
||||
@@ -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<Messaging> = Mutex(Messaging())
|
||||
private let nextTokenID: Atomic<UInt64> = Atomic<UInt64>(0)
|
||||
private var _sources: [MIDISource] = []
|
||||
private var _destinations: [MIDIDestination] = []
|
||||
|
||||
private let handlerQueue: DispatchQueue = DispatchQueue(label: "lyrebird.midi", qos: .userInteractive)
|
||||
private let _running: Atomic<Bool> = Atomic<Bool>(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)
|
||||
}
|
||||
|
||||
@@ -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<Transport> = 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<Messaging> = 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<UInt64> = Atomic<UInt64>(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<MIDIEventList>, Int, UnsafeMutablePointer<MIDIEventPacket>, inout [UInt32]) throws -> OSStatus
|
||||
) throws {
|
||||
via sendFn: (UnsafeMutablePointer<MIDIEventList>, Int, UnsafeMutablePointer<MIDIEventPacket>, 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<MIDIEventList> = base.assumingMemoryBound(to: MIDIEventList.self)
|
||||
let pktPtr: UnsafeMutablePointer<MIDIEventPacket> = 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..<MIDIGetNumberOfSources() {
|
||||
MIDIPortConnectSource(port, MIDIGetSource(i), nil)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// Plays back a parsed ``MIDIFile`` against a ``LyrebirdClock`` on a
|
||||
/// dedicated routine thread.
|
||||
@@ -62,8 +63,11 @@ public final class MIDIFilePlayer: @unchecked Sendable {
|
||||
public let applyTempoMap: Bool
|
||||
|
||||
private let _engine: SynthesisEngine
|
||||
private var _routine: LyrebirdRoutine?
|
||||
private let _routineLock: NSLock = NSLock()
|
||||
// @unchecked Sendable invariant: the one mutable field, `_routine`, is a
|
||||
// `Mutex` so its access is compiler-serialised; the remaining stored state is
|
||||
// immutable `let` (including `_engine`, a non-Sendable shared reference — the
|
||||
// reason this stays `@unchecked` — see SynthesisEngine's non-Sendable note).
|
||||
private let _routine: Mutex<LyrebirdRoutine?> = 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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<State> = 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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)..<data.startIndex.advanced(by: offset + size)])
|
||||
|
||||
@@ -192,7 +192,7 @@ public final class OSCServer: @unchecked Sendable {
|
||||
/// Bind a UDP socket to the port and start the receive thread.
|
||||
///
|
||||
/// - Throws: ``OSCServerError`` on socket / bind failure (carrying `errno`).
|
||||
public func start() throws {
|
||||
public func start() throws(OSCServerError) {
|
||||
guard !_abandonedThread.load(ordering: .acquiring) else {
|
||||
// A previous receive thread never returned; its (leaked) socket is
|
||||
// still being read. Binding a second one would leave two live.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Synchronization
|
||||
|
||||
/// Named shared clock that multiple routines
|
||||
/// and tasks can align to without per-routine drift.
|
||||
@@ -22,22 +23,31 @@ import Foundation
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// @unchecked Sendable invariant: all mutable tempo / epoch state is read and
|
||||
// written under `_lock`; immutable references (`_engine`, `epoch`) are set at
|
||||
// init and never mutated. Capture across actor boundaries is therefore safe.
|
||||
// @unchecked Sendable invariant: all mutable tempo state lives in `_state`, a
|
||||
// `Mutex` that serialises every read and write, so the lock discipline is
|
||||
// compiler-enforced rather than hand-audited. The only hand-verified item is the
|
||||
// immutable `_engine` reference — a non-Sendable class shared across the engine
|
||||
// graph (see SynthesisEngine's "Deliberately NOT Sendable" note), which is why
|
||||
// this stays `@unchecked` rather than a checked `Sendable`. `epoch` is an
|
||||
// immutable `let`.
|
||||
public final class LyrebirdClock: @unchecked Sendable {
|
||||
|
||||
private let _engine: SynthesisEngine
|
||||
private let _lock: NSLock = NSLock()
|
||||
|
||||
private static let secondsPerMinute: Double = 60.0
|
||||
|
||||
/// Sample time at which this clock was created. Useful as a shared epoch.
|
||||
public let epoch: SampleTime
|
||||
|
||||
private var _bpm: Double
|
||||
private var _beatOffset: Double = 0.0
|
||||
private var _tempoChangeSample: SampleTime
|
||||
/// Mutable tempo state, guarded as a unit. `beatOffset` accumulates the beats
|
||||
/// elapsed under prior tempi; `tempoChangeSample` is the sample time of the
|
||||
/// last `bpm` change, the anchor the current segment is measured from.
|
||||
private struct State {
|
||||
var bpm: Double
|
||||
var beatOffset: Double = 0.0
|
||||
var tempoChangeSample: SampleTime
|
||||
}
|
||||
private let _state: Mutex<State>
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,16 +43,16 @@ internal final class CepstralEnvelopeEstimator {
|
||||
private let fftSetup: FFTSetup
|
||||
|
||||
/// log(magnitudes) — length `halfSize + 1`.
|
||||
private let _logMag: UnsafeMutablePointer<Float>
|
||||
private let _logMag: RTScratchBuffer<Float>
|
||||
|
||||
/// 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<Float>
|
||||
private let _imagp: UnsafeMutablePointer<Float>
|
||||
private let _realp: RTScratchBuffer<Float>
|
||||
private let _imagp: RTScratchBuffer<Float>
|
||||
|
||||
/// Real cepstrum scratch — length `fftSize`.
|
||||
private let _cepstrum: UnsafeMutablePointer<Float>
|
||||
private let _cepstrum: RTScratchBuffer<Float>
|
||||
|
||||
/// 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<Float>.allocate(capacity: halfSize + 1)
|
||||
_realp = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_imagp = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_cepstrum = UnsafeMutablePointer<Float>.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<Float>(count: halfSize + 1)
|
||||
_realp = RTScratchBuffer<Float>(count: halfSize)
|
||||
_imagp = RTScratchBuffer<Float>(count: halfSize)
|
||||
_cepstrum = RTScratchBuffer<Float>(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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Float>
|
||||
private let _mag: RTScratchBuffer<Float>
|
||||
|
||||
/// Phases (radians) for complex bins 1..halfSize-1. Allocated at halfSize; index 0 unused.
|
||||
private let _phase: UnsafeMutablePointer<Float>
|
||||
private let _phase: RTScratchBuffer<Float>
|
||||
|
||||
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..<halfSize
|
||||
|
||||
_mag = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_phase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_mag.initialize(repeating: 0, count: halfSize)
|
||||
_phase.initialize(repeating: 0, count: halfSize)
|
||||
_mag = RTScratchBuffer<Float>(count: halfSize)
|
||||
_phase = RTScratchBuffer<Float>(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<R>(_ body: (UnsafePointer<Float>) -> 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<R>(_ body: (UnsafeMutablePointer<Float>) -> 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<R>(_ body: (UnsafePointer<Float>) -> 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<R>(_ body: (UnsafeMutablePointer<Float>) -> 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<Float> = realp.advanced(by: 1)
|
||||
let ip: UnsafePointer<Float> = imagp.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _phase.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.baseAddress.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _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<Float> = realp.advanced(by: 1)
|
||||
let ip: UnsafeMutablePointer<Float> = imagp.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _phase.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.baseAddress.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _phase.baseAddress.advanced(by: 1)
|
||||
let n: vDSP_Length = vDSP_Length(_binCount)
|
||||
var count: Int32 = Int32(_binCount)
|
||||
|
||||
|
||||
@@ -45,10 +45,10 @@ public final class SpectralFrameBuffer: @unchecked Sendable {
|
||||
|
||||
// MARK: - Internal storage (module-internal for FileIO and SpectralPlayBuffer access)
|
||||
|
||||
let _dc: UnsafeMutablePointer<Float> // [frameCount]
|
||||
let _nyquist: UnsafeMutablePointer<Float> // [frameCount]
|
||||
let _mag: UnsafeMutablePointer<Float> // [frameCount × halfSize]; index 0 per frame unused
|
||||
let _phase: UnsafeMutablePointer<Float> // [frameCount × halfSize]; same layout
|
||||
let _dc: RTScratchBuffer<Float> // [frameCount]
|
||||
let _nyquist: RTScratchBuffer<Float> // [frameCount]
|
||||
let _mag: RTScratchBuffer<Float> // [frameCount × halfSize]; index 0 per frame unused
|
||||
let _phase: RTScratchBuffer<Float> // [frameCount × halfSize]; same layout
|
||||
let _binCount: Int // halfSize - 1 (complex bins 1..<halfSize)
|
||||
|
||||
// MARK: - Validity
|
||||
@@ -118,31 +118,16 @@ public final class SpectralFrameBuffer: @unchecked Sendable {
|
||||
_binCount = hs - 1
|
||||
|
||||
let magPhaseCount: Int = frameCount * hs
|
||||
_dc = UnsafeMutablePointer<Float>.allocate(capacity: frameCount)
|
||||
_nyquist = UnsafeMutablePointer<Float>.allocate(capacity: frameCount)
|
||||
_mag = UnsafeMutablePointer<Float>.allocate(capacity: magPhaseCount)
|
||||
_phase = UnsafeMutablePointer<Float>.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<Float>(count: frameCount)
|
||||
_nyquist = RTScratchBuffer<Float>(count: frameCount)
|
||||
_mag = RTScratchBuffer<Float>(count: magPhaseCount)
|
||||
_phase = RTScratchBuffer<Float>(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<Float>.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<Float>.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)
|
||||
|
||||
@@ -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<Float> = ptr.baseAddress else { return }
|
||||
memcpy(bptr + 2, _mag + base + 1, _binCount * MemoryLayout<Float>.stride)
|
||||
memcpy(bptr + 2 + _binCount, _phase + base + 1, _binCount * MemoryLayout<Float>.stride)
|
||||
memcpy(bptr + 2, _mag.baseAddress + base + 1, _binCount * MemoryLayout<Float>.stride)
|
||||
memcpy(bptr + 2 + _binCount, _phase.baseAddress + base + 1, _binCount * MemoryLayout<Float>.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<Float> = ptr.baseAddress else { return }
|
||||
_ = memcpy(buf._mag + frameBase + 1, bptr + 2, binCount * MemoryLayout<Float>.stride)
|
||||
_ = memcpy(buf._phase + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout<Float>.stride)
|
||||
_ = memcpy(buf._mag.baseAddress + frameBase + 1, bptr + 2, binCount * MemoryLayout<Float>.stride)
|
||||
_ = memcpy(buf._phase.baseAddress + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout<Float>.stride)
|
||||
}
|
||||
framesRead += 1
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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<UInt64> = Atomic<UInt64>(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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 = """
|
||||
|
||||
@@ -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<Float> = RTScratchBuffer<Float>(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<Float> = RTScratchBuffer<Float>(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<Double> = RTScratchBuffer<Double>(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<Float> = RTScratchBuffer<Float>(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<Float> = RTScratchBuffer<Float>(count: 2)
|
||||
let b: RTScratchBuffer<Float> = RTScratchBuffer<Float>(count: 2)
|
||||
a[0] = 100
|
||||
b[0] = 200
|
||||
#expect(a[0] == 100)
|
||||
#expect(b[0] == 200)
|
||||
#expect(a.baseAddress != b.baseAddress)
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,10 @@ Tag format: `vX.Y.Z` (the `v` is conventional; SwiftPM strips it).
|
||||
> (`import Lyrebird` → `import LyrebirdSynth`). Because 1.0.0 was never
|
||||
> distributed before the rename, it shipped *as* 1.0.0. A comparable rename
|
||||
> after a public release would be a major bump.
|
||||
>
|
||||
> The consumer-facing 1.x → 2.0 upgrade steps (the module rename plus the
|
||||
> `@UIParam` / `UIParamNode` move into the core module) are in
|
||||
> `docs/migrating-to-2.0.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
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<!--
|
||||
migrating-to-2.0.md
|
||||
Lyrebird
|
||||
Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
SPDX-License-Identifier: MIT
|
||||
-->
|
||||
|
||||
# Migrating to Lyrebird 2.0
|
||||
|
||||
Lyrebird 2.0 is a major (source-breaking) release. Two changes affect existing
|
||||
consumers. Both are quick, mechanical fixes.
|
||||
|
||||
## 1. Module rename: `Lyrebird` → `LyrebirdSynth`
|
||||
|
||||
The core module was renamed. The **product** you add in `Package.swift` is still
|
||||
`Lyrebird`, but the **module** you import is now `LyrebirdSynth`.
|
||||
|
||||
```swift
|
||||
// Before (1.x)
|
||||
import Lyrebird
|
||||
|
||||
// After (2.0)
|
||||
import LyrebirdSynth
|
||||
```
|
||||
|
||||
Your `Package.swift` dependency is unchanged:
|
||||
|
||||
```swift
|
||||
.product(name: "Lyrebird", package: "Lyrebird") // still correct
|
||||
```
|
||||
|
||||
## 2. `@UIParam` / `UIParamNode` moved to the core module
|
||||
|
||||
In 1.x, the `@UIParam` property wrapper and its projected `UIParamNode` lived in
|
||||
**`LyrebirdUI`**. In 2.0 they moved into the core **`LyrebirdSynth`** module, so
|
||||
the parameter model is independent of any UI framework (this is what lets
|
||||
`LyrebirdUI` be a single cross-platform module — real SwiftUI on Apple,
|
||||
SwiftOpenUI/GTK4 on Linux).
|
||||
|
||||
`LyrebirdUI` does **not** re-export `LyrebirdSynth`, so two things must change in
|
||||
any code that uses `@UIParam` / `UIParamNode`:
|
||||
|
||||
**a. Import `LyrebirdSynth`.** A file that previously got these types via
|
||||
`import LyrebirdUI` alone now needs:
|
||||
|
||||
```swift
|
||||
import LyrebirdSynth // @UIParam, UIParamNode
|
||||
import LyrebirdUI // ParameterKnob, ParameterSlider, … (the controls)
|
||||
```
|
||||
|
||||
**b. Depend on the `Lyrebird` product.** Any *target* that touches `@UIParam` /
|
||||
`UIParamNode` must depend on the `Lyrebird` product, not only `LyrebirdUI` —
|
||||
otherwise `import LyrebirdSynth` will not resolve its types (Swift's explicit
|
||||
module maps only expose declared dependencies):
|
||||
|
||||
```swift
|
||||
.target(
|
||||
name: "MyUI",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"), // ← add this
|
||||
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
### Symptom
|
||||
|
||||
If you miss either, you'll see:
|
||||
|
||||
```
|
||||
error: cannot find type 'UIParamNode' in scope
|
||||
```
|
||||
|
||||
— even in a file that already `import LyrebirdUI`s, and even (for the
|
||||
missing-target-dependency case) in a file that already `import LyrebirdSynth`s.
|
||||
Add the import **and** the product dependency and it resolves.
|
||||
|
||||
## Not breaking, but new
|
||||
|
||||
`LyrebirdUI` is now one cross-platform module. On Apple it compiles against real
|
||||
SwiftUI exactly as before; on Linux it renders through SwiftOpenUI/GTK4. Apple
|
||||
consumers need no change for this — the control names (`ParameterKnob`,
|
||||
`ParameterSlider`, `ParameterXY`, `ParameterButton`, `ParameterLabel`, the scope
|
||||
/ envelope / status views) and their initializers are unchanged.
|
||||
@@ -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<Element>: ~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 |
|
||||
|
||||
@@ -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<Element>` — 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user