diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..c9071d5 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,272 @@ +# Lyrebird — Architecture + +A technical tour of how Lyrebird runs audio: the thread model, how the non-real-time world talks to the real-time render callback without locks, how a block is split for sample-accurate scheduling, how bus memory is managed, and how work fans out across cores. The audience is engineers who want to answer "how does this actually work?" and "how would I do *X*?" — not a getting-started guide (see [`README.md`](README.md)) and not an API reference (see `docs/`). + +The single organizing principle: **the real-time audio thread never allocates, never locks, never blocks.** Every design decision below follows from that constraint. + +--- + +## 1. The thread model + +Lyrebird is a single-process framework. At runtime there are up to four kinds of execution context. Knowing which thread you are on tells you what you are allowed to do. + +### 1.1 The real-time (RT) audio thread + +This is the Core Audio render callback, invoked by the OS audio HAL every `blockSize` samples at real-time scheduling priority. On macOS the callback is driven by an AUHAL unit (`kAudioUnitSubType_HALOutput`, chosen over `DefaultOutput` because it supports full-duplex input + output); on iOS by RemoteIO. The callback path is: + +``` +HAL → lyrebirdRenderCallback → CoreAudioDriver.render() → SynthesisEngine.processBlock() +``` + +Everything reachable from `processBlock()` runs under the RT contract: + +- **No allocation** — no `Array`/`String`/object creation, no implicit Copy-on-Write reallocs. +- **No locks** — no `Mutex`, `NSLock`, `DispatchSemaphore`, no `os_unfair_lock`. +- **No blocking** — no file/network I/O, no `DispatchQueue.async`, no waiting on another thread. +- **No ARC churn** — no `retain`/`release` on hot paths; cached references are held via `Unmanaged`. +- **No `print` / no dynamic casts** — no Foundation logging, no `as?`/`is` runtime type checks (inputs are classified once at `init`). + +The RT thread is the **single writer** of: the engine's audio bus memory, `_currentTime`, the segment serial, and the CPU-load statistics. Everyone else reads those through atomics. + +### 1.2 The main / non-RT thread + +This is wherever you call the public API: `engine.add(_:)`, `engine.schedule(_:)`, `engine.remove(_:)`, and parameter mutations. It is allowed to do everything the RT thread cannot. Its job is to do all the expensive work — allocate synthesizers, run `build()` to construct the generator DAG, retain references — *before* handing a fully-prepared, pointer-only payload to the RT thread through a lock-free queue. SwiftUI `@Published` updates, file loading, and locks all live here. + +### 1.3 The deferred-deallocation worker + +When a synth is removed, its memory must not be freed on the RT thread (ARC dealloc can take locks and walk arbitrary deinit chains). Instead the RT thread hands the retained reference to a background queue — `DispatchQueue(label: "lyrebird.free", qos: .background)` — which drains a free-queue on a timer and calls `Unmanaged.release()` off the hot path. ARC deinit therefore always fires on a non-RT thread. + +### 1.4 ParallelGroup worker threads + +When a `ParallelGroup` evaluates more than one child, it dispatches the children across cores via `DispatchQueue.concurrentPerform`. Those worker invocations run *as part of* one `processBlock()` call — they are RT-priority work and inherit the full RT contract. They are not a long-lived pool you manage; `concurrentPerform` joins before the block returns. (See §7.) + +### 1.5 The NRT (offline) render thread + +`NRTDriver` is a passive driver: instead of an audio device callback, it runs a tight loop calling `engine.processBlock()` as fast as possible until the requested duration is filled, writing each block to a CAF file via `ExtAudioFile`. The *same* `processBlock` and the *same* scheduling stack run — there is no separate offline code path — but there is no hardware clock, so it renders faster than real time. The RT contract still holds inside `processBlock`, but the driver loop around it is ordinary code. + +--- + +## 2. Non-RT → RT communication: the lock-free handoff + +The central problem: the main thread wants to add/remove/retune voices, but cannot take a lock that the RT thread might wait on, and the RT thread cannot allocate or block. The solution is a set of **single-producer / single-consumer (SPSC) lock-free ring queues** plus a strict rule that all allocation happens on the producer side. + +### 2.1 SPSCQueue + +`SPSCQueue` (in `Sources/Lyrebird/Engine/SPSCQueue.swift`) is the shared primitive. It is a fixed-size ring buffer (`[T?]`, capacity rounded to a power of two) with two atomic, unbounded, monotonically-increasing counters from the `Synchronization` module: + +- `writeIdx: Atomic` — advanced by the producer with a **releasing** store on enqueue. +- `readIdx: Atomic` — advanced by the consumer with an **acquiring** load on dequeue. + +The real slot is `counter & mask`. Occupancy is `writeIdx - readIdx`. The release/acquire pairing establishes a happens-before edge: everything the producer wrote into the slot is visible to the consumer once it observes the new `writeIdx`. No lock is ever taken. Because the capacity is fixed and the buffer is allocated up front, enqueue/dequeue never allocate. + +`Synchronization.Atomic` is why the platform floor is **macOS 15 / iOS 18** — earlier OSes lack it. + +### 2.2 The queues + +| Queue | Direction | Carries | Notes | +|---|---|---|---| +| `pendingQueue` | main → RT | `ScheduledEvent` (add/remove/param/groupFree) | Default capacity 1024 (power-of-2). Enqueue returns `Bool`; on full, the event drops and `pendingQueueDroppedCount` increments so the caller can detect a burst overflow. | +| `freeQueue` | RT → free-worker | `Unmanaged` | Pre-retained on main thread; released on the background worker. | +| `parameterSourceKillQueue` | RT → main | pointer to a replaced parameter source | Old `@LiveParam`/`@UIParam` source freed off-RT after a swap. | +| `bufferSwapKillQueue` | RT → main | pointer to a replaced `LyrebirdBuffer` | Old buffer freed off-RT after a hot-swap. | +| `triggerQueue` | RT → listener | `TriggerEvent` | RT-side trigger notifications surfaced to non-RT listeners. | + +The design pattern is identical across all of them: **whoever can allocate does the allocation; the queue moves only pointers / pre-built values.** + +### 2.3 ScheduledEvent — a pointer-only payload + +The work the RT thread does to apply an event is deliberately trivial: re-link a node into the tree, or store a parameter value. All the heavy lifting (allocating the synth, calling `build()`, constructing the `PreparedNode`, retaining it) happens on the main thread *before* the event is enqueued. The enum captures exactly the pre-built state needed: + +- `.add(PreparedNode, at: SampleTime)` — node already built and retained. +- `.addNode(PreparedNode, NodePosition, at: SampleTime)` — same, with an explicit tree position. +- `.remove(Synthesizer, retainedRef: Unmanaged, at: SampleTime)` — the synth is retained via `Unmanaged.passRetained()` on the main thread so the RT thread can hand it to `freeQueue` without touching ARC. +- `.groupFree(Group, parentGroup: Group?, at: SampleTime)` — frees a whole subtree. + +### 2.4 Binding: single-shot atomic compare-exchange + +A synthesizer may belong to exactly one engine at a time. This is enforced not with a lock but with a single-shot CAS on `SynthesizerBase._engineBinding: Atomic`, which stores the engine pointer's bit pattern: + +``` +compareExchange(expected: 0, desired: enginePtrBits, ordering: .acquiringAndReleasing) +``` + +If the slot was already non-zero, the synth is bound elsewhere → `engine.add` throws `EngineAddError.boundToOtherEngine(current:prior:)` (or `.doubleAdd` if it is the *same* engine without an intervening `remove`). The errors map raw pointers back to human-readable `SynthesisEngine.identifier: UUID` values via a process-wide `EngineLifecycleCoordinator` registry (weakly holding every live engine). There is bounded stale-pointer recovery (max 2 passes): if the previously-bound engine has since deinit'd, the binding is cleared and the CAS retried. + +`LyrebirdBuffer` extends this to a **two-tier** model for cross-engine sharing: `bindExclusive` (CAS on `_exclusiveEngine`, one engine, fails if any read-only holder) vs. `bindReadOnly` (refcounted via `_readOnlyRefCount: Atomic`, N engines, fails if an exclusive holder exists). The two tiers are mutually exclusive at any instant. Single-engine code needs none of this — an unbound buffer just works. + +--- + +## 3. The render callback flow + +`SynthesisEngine.processBlock()` is the heart of the system. One invocation produces one hardware block. In order: + +1. **Mark RT identity** — `RTThreadIdentity.markCurrentThreadAsRT()` sets a thread-local flag so `DEBUG` assertions elsewhere can trap RT-illegal calls. +2. **Flush denormals** — `fesetenv()` enables flush-to-zero so denormal floats don't tank CPU. +3. **Zero the audio buses** — `vDSP_vclr()` clears audio bus memory for the block. (Control buses are *not* zeroed — they persist.) +4. **Copy hardware input** — incoming mic/line samples are `memcpy`'d into the reserved input buses. Never via Swift array assignment (which could trigger a CoW dealloc on the RT thread). +5. **Drain `pendingQueue`** and split the block at event boundaries (§4). +6. **Evaluate each segment** in order via `evaluateSegment(count:busOffset:)`. +7. **Advance `_currentTime`** by `blockSize` with a releasing atomic store. +8. **Update CPU stats** (EMA, relaxed atomics — best-effort). +9. **Write the scope tap** if an oscilloscope capture is attached. +10. **Apply the master gain ramp** — interpolated from the previous block's gain to the current target so volume/mute changes never click. + +`blockSize` is capped at **512** (`lyrebirdDefaultResultBufferSize`) because every generator's output buffer is pre-allocated to exactly that size — there is no grow path on the RT thread. + +--- + +## 4. Sample-accurate scheduling: block splitting + +Audio is processed in blocks, but musical events must land on exact samples. Lyrebird reconciles the two by **splitting a block into segments at event boundaries** and evaluating each segment independently. + +Time is `SampleTime` (`Int64`), a monotonic sample counter incremented by `blockSize` each block, written only by the RT thread and read elsewhere via atomic load. A `ScheduledEvent` carries an absolute `targetTime`. + +Within one `processBlock`, with `blockStart = currentTime` and `blockEnd = blockStart + blockSize`: + +``` +1. Collect events whose targetTime ∈ [blockStart, blockEnd) from pendingQueue + (plus any carried over from a previous block). +2. Sort by targetTime — allocation-free insertion sort. +3. cursor = 0 + for each event E, at offset = E.targetTime - blockStart: + if offset > cursor: + evaluateSegment(count: offset - cursor, busOffset: cursor) // render up to the event + applyEvent(E) // pointer-only: link/unlink node, or store a parameter + cursor = offset + evaluateSegment(count: blockSize - cursor, busOffset: cursor) // render the tail +4. currentTime += blockSize +``` + +So a synth scheduled at sample offset 137 of a 512-sample block causes the block to render as `[0..137)`, then the synth links in, then `[137..512)` renders with it active — and its `Out` generator begins writing at exactly `busOffset = 137`. Events in the past clamp to the block start; a hard cap of **256 events per block** bounds worst-case work (excess defers/drops). + +`evaluateSegment` bumps `_atomicSegmentSerial` (releasing store), builds a `SynthGraph` around a pre-allocated empty parameter table (no per-segment alloc), and calls `rootGroup.evaluate(graph:count:)`. Crucially, generators render `count` samples — *not* always `blockSize` — and advance their internal state (oscillator phase, filter history, delay write heads) by exactly `count`. This is why a generator's `_computeSamples` must use `count`, never `engine.blockSize`: it may be called several times within a single block. + +--- + +## 5. Bus memory + +Buses are the only shared signal medium between nodes, and all of their memory is pre-allocated at `start()` and never resized. + +- `audioBuses: [[Float]]` — shape `[numAudioBuses][blockSize]`. +- `controlBuses: [Float]` — shape `[numControlBuses]` (one ramp-target value per control bus). + +Layout reserves the low audio buses for hardware: + +``` +[0 .. numOutputChannels) → hardware output (memcpy'd to the device) +[numOutputChannels .. +numInputChannels) → hardware input (filled from the device) +[numOutputChannels+numInputChannels .. numAudioBuses) → user buses +``` + +Per-block semantics differ by type: + +- **Audio buses** are zeroed each block, written by `Out.Audio` with `+=` (so multiple voices on one bus mix naturally), and read by `In.Audio`. +- **Control buses** are *not* zeroed; a value persists until overwritten, carrying a single per-block ramp target. + +"How would I route one synth into another?" → write to a user audio bus with `Out.Audio(bus: N, ...)` and read it with `In.Audio(bus: N)` in a downstream synth placed later in the node tree. Evaluation order (the node tree, head-to-tail) determines who sees whose output within a block. + +### 5.1 ScratchBuses (parallel isolation) + +When work is parallelized, concurrent children cannot all `+=` into the same shared engine bus without racing. Each `ParallelGroup` child therefore renders into its own pre-allocated `ScratchBuses` (same shape as the engine buses, plus a per-bus **dirty mask**). After the parallel barrier, a sequential merge pass sums each *dirty* scratch bus into the engine buses with `vDSP_vadd`. The dirty mask is the key optimization: a typical stereo voice touches 2 buses, so the merge does ~2 vector-adds instead of scanning all `numAudioBuses`. + +--- + +## 6. How RT-safety is actually enforced + +The contract in §1.1 is upheld by four mechanisms, not by hope: + +1. **Pre-allocation everywhere.** Engine buses and parameter tables in `start()`; per-child `ScratchBuses` in `ParallelGroup.build()`; every generator's `_result` buffer (512 doubles) in `GeneratorBase.init()`. The RT thread only ever reads/writes into storage that already exists. `SynthesisEngine.init` rejects `blockSize > 512`. +2. **Atomics-only synchronization.** All cross-thread state is a `Synchronization.Atomic`. Memory ordering is deliberate: releasing stores publish, acquiring loads consume, relaxed loads are used only for best-effort stats. There are no mutexes anywhere on the signal path. +3. **`Unmanaged` for cached references.** The engine caches things like the scope-tap target as `Unmanaged` so the RT thread can reach them without an ARC retain/release. Removal uses `Unmanaged.passRetained()` on the main thread and `Unmanaged.release()` on the free-worker — the RT thread only *moves* the pointer. +4. **Thread-local debug asserts.** The `RTThreadIdentity` TLS flag lets RT-illegal entry points (e.g. running a user `ValueComputable` closure) assert in `DEBUG`. The flag's key is warmed up off-RT in `CoreAudioDriver.init()` so even the first lookup doesn't allocate on the audio thread. + +This is the lens for "would this be RT-safe?": if your code, reachable from a generator's `_computeSamples` or `calculatedSamples`, would allocate, lock, log, or touch ARC, it belongs on the main thread or behind a queue — not in the render path. The catalog of helpers in `docs/protocols/writing-generators.md` §13 exists precisely so generator authors never have to hand-roll RT-unsafe boilerplate. + +--- + +## 7. Multi-core: ParallelGroup + +`ParallelGroup` is a `Synthesizer` that evaluates its children concurrently to use more than one core for a heavy graph. Its lifecycle inside one segment: + +```swift +// 1. Clear each child's scratch buses over the segment's sample range. +for slot in scratchSlots { slot.clearDirtyBuses(offset: offset, count: count) } + +// 2. Evaluate. +if children.count == 1 { + // Fast path: skip the dispatch entirely, render inline. + children[0].evaluate(graph: SynthGraph(..., scratchBuses: slots[0]), count: count) +} else { + DispatchQueue.concurrentPerform(iterations: children.count) { i in + // Each i renders into its own scratchSlots[i] — no shared write target, no race. + children[i].evaluate(graph: SynthGraph(..., scratchBuses: scratchSlots[i]), count: count) + } +} + +// 3. Barrier has passed. Merge dirty scratch buses into the engine buses. +for slot in scratchSlots { + for bus where slot.dirty[bus] { vDSP_vadd(slot.buses[bus], engine.audioBuses[bus], ...) } +} +``` + +Correctness rests on isolation and the segment serial: + +- **Isolation** — each worker writes only its own `ScratchBuses`, so concurrent `Out.Audio` writes never collide. The merge is sequential. +- **`_atomicSegmentSerial`** — incremented once (releasing) before the parallel region; workers read it (acquiring). Generator result caches key on this serial, so a stale cache from a previous segment is never reused inside a concurrent worker. + +Constraints that fall out of the model — useful when answering "why doesn't *X* work in parallel?": + +- **No cross-child fan-out.** Sharing one generator instance between two children races on its cache. Build a copy per child. +- **Control-bus writes aren't scratch-isolated.** Two children writing the same control bus race. +- **No nested ParallelGroups.** An inner merge would bypass the outer scratch. +- **Children are fixed at `build()`.** Adding/removing children while active is undefined. + +The single-child inline fast path matters: dispatching `concurrentPerform` for one child would cost more in scheduler overhead than it saves. + +--- + +## 8. Multiple engines: EngineHost and NRT batch rendering + +A process can run several engines — e.g. one real-time output plus a pool of offline renderers. `EngineHost` is the facade that owns them, keyed by an `EngineHostRole` (`.rtOutput(deviceID:)`, `.nrtRender(slot:)`, `.auxiliary(name:)`, `.custom(_)`). It enforces role uniqueness — a second engine claiming the same `.rtOutput(deviceID:)` throws `.duplicateRole`, because AUHAL output devices are exclusive. + +`startAll()` / `stopAll()` are transactional: engines are snapshotted under a (non-RT) lock, started without the lock, and if any one throws, the already-started engines are rolled back with `stop()` so the caller never sees a partial-start state. + +For offline batch work, `renderConcurrent(jobs:maxConcurrent:)` spawns short-lived engines on Swift `Task`s (not host-registered), defaulting `maxConcurrent` to `activeProcessorCount`. It uses a seed-and-refill pattern: launch the first `maxConcurrent` jobs, and each completion launches the next queued one. The first failure propagates and cancels the rest. (Caveat: an in-flight render may keep writing its CAF after the stream closes — orphan files are the caller's to clean up.) + +Cross-engine object sharing is governed by the binding rules in §2.4. The full ownership matrix lives in `docs/engine/multi-engine-host.md` and `docs/engine/multi-core.md`. + +--- + +## 9. Synthesizer lifecycle, end to end + +Putting the pieces together — what `engine.add(synth)` actually does: + +1. **(main)** Allocate the synth. +2. **(main)** `synth._bind(to: engine)` via the single-shot CAS (§2.4). +3. **(main)** `synth.build()` — construct the generator DAG, allocate every buffer. +4. **(main)** Wrap in a `PreparedNode`, retain it, enqueue `.add(node, at: time)` onto `pendingQueue`. +5. **(RT)** `processBlock` drains the event at the scheduled offset and links the node into the tree — pointer-only, no allocation (§4). +6. **(RT)** The synth renders from the next segment onward. + +And `engine.remove(synth)`: + +1. **(main)** `Unmanaged.passRetained(synth)` → `.remove(synth, retainedRef:, at:)` enqueued. +2. **(RT)** Unlink the node from the tree, push `retainedRef` to `freeQueue`, clear the binding CAS. No ARC, no dealloc on the RT thread. +3. **(free-worker)** Drain `freeQueue`, `Unmanaged.release()` → ARC deinit fires off-RT. + +`remove` returns `Bool` (it unbinds synchronously on successful enqueue), but there is a documented one-`processBlock` window between `remove` and a re-`add` of the same instance — the RT thread needs a block to actually unlink it. If `freeQueue` overflows, the framework logs one warning and leaks that single reference rather than risk the RT thread; a leaked voice is preferable to an audio dropout or crash. + +--- + +## Where to go deeper + +| Topic | Doc | +|---|---| +| Engine internals, render pass | `docs/engine/synthesis-engine.md` | +| Core Audio / AUHAL driver | `docs/engine/core-audio-driver.md` | +| Sample-accurate scheduling | `docs/engine/scheduling.md` | +| Bus memory / In / Out | `docs/engine/bus-system.md` | +| ParallelGroup / multi-core | `docs/engine/multi-core.md` | +| EngineHost / NRT batch pool | `docs/engine/multi-engine-host.md` | +| Signal evaluation order | `docs/signal-flow/signal-flow.md` | +| Writing RT-safe generators (helper catalog §13) | `docs/protocols/writing-generators.md` | diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..07324b1 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,361 @@ +# Lyrebird — Claude Context + +Native macOS/iOS audio synthesis framework in Swift. Users implement `Generator` and `Synthesizer` protocols; Lyrebird engine handles Core Audio I/O and signal-graph evaluation. No separate scripting language. + +## Pick the Right Agent First + +Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are mirrored into the repo at `.claude/agents/` (auto-discovered) and `claude/agents/` (installer source). Invoked automatically when task description matches; you can also invoke explicitly. + +| Agent | Use when | +|---|---| +| `lyrebird_demo_agent` | **Any demo work** — CLI demos, macOS GUI, iOS GUI, NoteController, Xcode project edits. | +| `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. | +| `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. | +| `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. | +| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. | +| `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** | +| `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. | +| `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. | + +**Repo mirror sync** (after editing working copies in `~/.claude/`): +``` +bash scripts/sync-claude-from-working.sh # dry-run +bash scripts/sync-claude-from-working.sh --apply +bash scripts/sync-claude-from-working.sh --check # CI: exit 1 on drift +``` +Edit only in `~/.claude/`. Script keeps `.claude/` and `claude/` in sync. New agents/skills must be added to the repo manually the first time, then this script keeps them in sync. + +**Pre-commit hook** (one-time setup per clone — blocks commits with stale repo mirror): +``` +git config core.hooksPath .githooks +``` +The `.githooks/pre-commit` hook calls `--check`. Skips silently when `~/.claude/agents/` is absent (contributors without working copies are not blocked). Bypass for one commit with `git commit --no-verify`. + +## Task → Doc Map + +**Engine / RT core** +- Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md` +- Bus memory / In / Out → `docs/engine/bus-system.md` +- Sample-accurate scheduling → `docs/engine/scheduling.md` +- ParallelGroup / multi-core → `docs/engine/multi-core.md` +- Multi-engine host (`EngineHost`) + NRT batch render pool → `docs/engine/multi-engine-host.md` + +**Generators** +- Generator protocol + DemandGenerator → `docs/protocols/generator.md` +- **Implementing a new Generator** → `docs/protocols/writing-generators.md` (§13 = shared helpers) +- Built-in generator catalog → `docs/stdlib/generators.md` +- Multi-channel / `outputChannelCount` / channel-aware operators → `docs/stdlib/multichannel.md` +- Musical math (MIDI↔Hz, dB, intervals) → `docs/stdlib/generators.md` (LyrebirdMusicMath section) +- Physical models (BowedString, Flute, Clarinet, ScannedSynthesizer) → `Sources/Lyrebird/Lyrebird.docc/Generators/PhysicalModels.md`, `Sources/Lyrebird/Lyrebird.docc/Generators/ScannedSynthesis.md` +- Oversampling primitives (`HalfbandUpsampler`/`HalfbandDownsampler` 2×/4×) → `Sources/Lyrebird/Lyrebird.docc/Generators/Oversampling.md` +- Spectral processors / FFT chain → `docs/stdlib/spectral.md` +- Extension SDK / out-of-tree generator packages (SPI surface, versioning) → `docs/protocols/extension-sdk.md` + +**Synthesizer / language side** +- Synthesizer protocol → `docs/protocols/synthesizer.md` +- Node tree / Group nesting / bus routing → `docs/protocols/node-tree.md` +- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md` +- `Pattern` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md` +- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md` +- Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md` +- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md` +- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md` +- Score / ScorePlayer / SMF / MusicXML → `Sources/Lyrebird/Lyrebird.docc/ScoreSystem.md` +- Performance event sequencing / `LyrebirdProcess` / `LyrebirdEventList` → `Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md` +- NRT / offline render → `docs/tooling/nrt-guide.md` + +**Tooling / project** +- CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md` +- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md` +- Dev workflow / phase branches / build → `docs/tooling/workflow.md` +- Xcode project templates → `docs/tooling/xcode-templates.md` +- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md` + +**UI** +- LyrebirdUI / parameter binding → `docs/ui/gui-system.md` +- Live-compile scratchpad (`LyrebirdScratchView`, `LyrebirdLiveCompile`, `LyrebirdLiveCompileUI`) → `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`. **Lives in the separate `LiveCompile/` SwiftPM sub-package** (Phase 167) — cross-package dependency forces `libLyrebirdLiveCompile.dylib` to dynamic-link `libLyrebird.dylib` instead of statically embedding it, eliminating the ObjC class double-registration crash that aborted full `swift test` runs in the single-package layout. Build sub-package with `(cd LiveCompile && swift build)` / `(cd LiveCompile && swift test)`. + +**Diagnostics** +- User-visible messages (`LyrebirdMessage`, `LyrebirdMessageCenter`, `LyrebirdMessageView` / Banner) + node-tree mirror (`NodeTreeMirror`, `NodeTreeSnapshot`, `LyrebirdNodeTreeView`) → `docs/diagnostics-guide.md` + +**Planning** +- What to build next → `docs/00-working-order.md` +- Completed phases → `docs/01-completed-working-order.md` + +## Hard Constraints + +One-liners. Detail and rationale lives in linked docs. + +**Platform / build** +- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15. +- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS. +- No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`). + +**RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md` +- No allocation, locks, blocking, `print`, `String` construction, or `is`/`as?` runtime type checks. Classify inputs at `init`. +- No `!` force unwraps. Use `guard let`, `if let`, `?? fallback`, or `throws`. +- All bus memory pre-allocated at `start()`. Never resized. +- Generator output buffers pre-allocated to `lyrebirdDefaultResultBufferSize` (512). `SynthesisEngine.init` enforces `blockSize ≤ 512`. Every `_computeSamples` opens with `_checkCount(count)` (inherited from `GeneratorBase`). No grow path. +- No shared mutable state between Synthesizer instances — graph-copy-per-instance. + +**Module layering** +- No `SwiftUI`, `AppKit`, or `UIKit` imports in core `Lyrebird` module. UI lives in `LyrebirdUI` only. +- Platform-specific input sources (e.g. AppKit `NSEvent` mouse monitors) live in `LyrebirdUI` and conform to a core protocol/base class (e.g. `MouseInputBridge`) that core Generators read from. Install via the registry (e.g. `MouseInput.install(_:)`) at app startup. + +**Generator protocol** — `docs/protocols/writing-generators.md` +- `GeneratorBase` is the required base class. Provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, **and `_result`** (mono, pre-allocated to `lyrebirdDefaultResultBufferSize`, zero-filled). Never redeclare these as stored properties. +- Mono generators inherit `_result` directly — no declaration, no init line. Multi-row generators call `super.init(channels: N)` from their designated `init` to allocate N rows in one shot. Dynamic channel counts pass `channels: outChannels` computed in `init`. +- Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate. +- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target. +- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer. +- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. +- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode. +- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule. +- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`. +- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`. + +## File Organisation + +**Every new `.swift` file starts with the MIT SPDX header.** First five lines, before any `import`: + +```swift +// .swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +``` + +(Blank line after the header, then the file body.) Applies to all source under `Sources/`, `Tests/`, `Demos/`, and `LiveCompile/`. **Exception:** Xcode file-template resources at `Sources/LyrebirdCLI/Resources/XcodeTemplates/*.xctemplate/___FILEBASENAME___.swift` — these keep only Xcode's injected `//___FILEHEADER___` (the header belongs to whoever instantiates the template, not to Lyrebird). Likewise, scaffolder/exporter code that *emits* user-facing Swift source must not bake the Lyrebird copyright into the generated string. Review-blocking: a new tracked `.swift` without the header is a violation. + +**One public type per Swift source file.** Generator enums, classes, protocols, support types each in their own file. + +- Generator family per file (`OscSawtooth.swift`, `LFSquare.swift`, `Clip.swift`, etc.). +- Shared file-scope helpers go in `*Helpers.swift` (e.g. `OscBandLimitedHelpers.swift`). Access `internal` (no modifier) so visible across files. +- Type-coupled support types (error enums, format enums) each in their own file (e.g. `DiskInError.swift`, `DiskOutFormat.swift`). +- One `@Suite` per test file, named `Tests.swift`. + +**Never drop new files at `Sources/Lyrebird/` root.** Every new `.swift` file goes into a subfolder grouped by function. Existing top-level subfolders (alphabetical): + +`AUv3/` `AudioDrivers/` `Buffers/` `Buses/` `Capture/` `Diagnostics/` `Distributions/` `Engine/` `Envelopes/` `External/` `GeneratorCore/` `Generators/` `Kinds/` `MIDI/` `Math/` `NodeTree/` `OSC/` `Oversampling/` `Parameters/` `Patterns/` `Process/` `Scheduling/` `Score/` `Spectral/` `Synthesizer/` `TemporalStream/` `Trigger/` `ValueCompute/` `Voices/` + +Rule: + +1. Place into an existing subfolder if function matches (`Generators/` = concrete `Generator` implementations, `GeneratorCore/` = protocol layer + `MulAdd`, `Engine/` = RT core, `Buses/` = bus memory + allocation, `NodeTree/` = `Group`/`ParallelGroup`/`NodePosition`/`PreparedNode`, `Math/` = constants + numeric utilities, `Kinds/` = cross-cutting enum descriptors, etc.). +2. If no folder fits, **propose a new subfolder in the PR description** (one-line rationale, list of files going in) rather than landing files at root. Reviewers accept or redirect. +3. Subfolder may have further nesting when a family is large (e.g. `Generators/BufferIO/`, `TemporalStream/Algorithms/`). + +Loose .swift at `Sources/Lyrebird/` root is a review-blocking violation. `Sources/Lyrebird/Lyrebird.docc/` is the only non-folder exception at root. + +Review agents flag any new file introducing a second unrelated public type without explicit prior approval, and flag any new .swift landed at `Sources/Lyrebird/` root. + +## Interface Conventions + +**Filter resonance parameter naming**: + +- `q:` — used for filters parameterised by a **quality factor** (RBJ cookbook, SVF, Butterworth cascade, resonator banks). `q = 1/sqrt(2) ≈ 0.707` is Butterworth (no peak); higher values produce sharper peaks. Range typically `[0.1, ~100]`. +- `resonance:` — used for filters parameterised by a **raw feedback factor** (Moog ladder and other emulation filters). Range typically `[0.0, ~1.0]` where `1.0` is the self-oscillation threshold. Engine may clamp slightly above 1.0 to avoid runaway. + +Both are documented at the parameter level; the distinction is principled (different DSP families parameterise resonance differently), and call-site choice should reflect the underlying model rather than a uniform name. New filters route to whichever parameter the underlying algorithm uses naturally. + +**`engine.add` / `engine.schedule` are throwing** (Phase 196). Replaced the legacy `Bool`-returning signatures with structured `throws` on all four add/schedule entry points: + +```swift +public func add(_ synth: any Synthesizer) throws +public func add(_ synth: any Synthesizer, position: NodePosition) throws +public func schedule(_ synth: any Synthesizer, at time: SampleTime) throws +public func schedule(_ synth: any Synthesizer, after seconds: Double) throws +``` + +Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `.doubleAdd(engine:)` (same-engine re-add), `.pendingQueueFull`, `.rebuildFailed(underlying:)`. Both UUIDs surface in cross-engine errors via `SynthesisEngine.identifier: UUID`. Internal `_bind(to:) throws` / `_unbind(from:)` on `SynthesizerBase` back the precondition via single-shot atomic CAS. `LyrebirdBuffer` has opt-in two-tier binding (`bindExclusive` / `bindReadOnly`) for cross-engine sharing — see `docs/engine/multi-core.md` § Object ownership rules. + +`engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance. + +Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern. + +## Swift Code Style Rules + +Hard rules. Review agents flag violations. + +### No force unwraps +Never `!` on optionals or `try!`. Hotspots: `UnsafeBufferPointer.baseAddress` in Accelerate calls, `Array.first!`/`last!` on output channels, `try!` in test helpers, `dict[key]!`. +```swift +// WRONG +vDSP_vsmulD(buf.baseAddress!, 1, &gain, out.baseAddress!, 1, n) +// RIGHT +buf.withUnsafeMutableBufferPointer { b in + guard let base = b.baseAddress else { return } + vDSP_vsmulD(base, 1, &gain, outBase, 1, n) +} +``` + +### No magic numbers +Every non-trivial literal needs a named `let`. Exempt: `0`, `1`, `-1`, `2` when arithmetic meaning is obvious. Hotspots: queue capacities, trig scale factors (`1.0/sqrt(2.0)`, `0.5*.pi`), vDSP delay-state sizes, normalisation/gain constants. +```swift +// WRONG: SPSCQueue(capacity: 32) +// RIGHT: let killQueueCapacity = 32; SPSCQueue(capacity: killQueueCapacity) +``` + +### Doc comments on public Generator init parameters +Every new public Generator type documents `init` parameters **in two places** so Xcode Quick Help works from both type name and call site: + +1. **Class-level `/// - Parameters:` block** on the `Audio` / `Control` class. +2. **Init-level `/// - Parameters:` block** on the `init` itself. + +Each entry states: what it does, unit (Hz / dB / seconds / ratio / [0, 1] / frames), valid range or clamping, default when non-obvious. + +```swift +/// Audio-rate lowpass filter. +/// +/// - Parameters: +/// - input: Signal to filter. +/// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist. +/// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`. +/// - mul: Output multiplier. Defaults to `1.0`. +/// - add: Output offset. Defaults to `0.0`. +public final class Audio: _Base, AudioGenerator { + /// - Parameters: + /// - input: Signal to filter. + /// - freq: Cutoff frequency in Hz. No internal clamping; stay below Nyquist. + /// - q: Resonance factor. `0.707` = Butterworth (no peak). Defaults to `0.707`. + /// - mul: Output multiplier. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. + public init(input: any ValidGeneratorInput, freq: any ValidGeneratorInput, + q: any ValidGeneratorInput = 0.707, + mul: any ValidGeneratorInput = 1.0, + add: any ValidGeneratorInput = 0.0) { … } +} +``` + +Exception: unary/binary math operators where the class-level formula makes every param self-evident (`Abs`, `Sign`, `Floor`, etc.) only need `/// - Parameter signal: Input signal.` at both levels. + +### Multi-line declarations +Multi-line format required when ≥ 2 type aliases or ≥ 2 init parameters: + +```swift +// GeneratorEnum +extension Wrap: GeneratorEnum { + public typealias AudioType = Wrap.Audio + public typealias ControlType = Wrap.Control +} + +// Init with ≥ 2 params +public init( + input: any ValidGeneratorInput, + freq: any ValidGeneratorInput, + q: any ValidGeneratorInput, + mul: any ValidGeneratorInput = 1.0 +) { … } + +// Single-param exception +public init(_ signal: any ValidGeneratorInput) { … } +``` + +### Explicit type annotations on bindings + +Every `let` / `var` binding — stored properties on classes/structs/enums, locals inside functions, and `for x in …` loops — must carry an explicit `: Type` annotation. Inferred bindings (`let x = expr`) are a review-blocking violation in new and modified code. + +```swift +// WRONG +let buf = LyrebirdBuffer(count: tableSize) +let intPhase = Int(phase) +let frac = phase - Double(intPhase) +for i in 0.., _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper. +- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`. +- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`. +- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`. +- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`. +- `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` — `ResultBuffer.swift`; replaces the `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literal +- `_mulAdd.applyIfNeeded(to:graph:count:)` +- `fillRampedResult(into:from:to:mulAdd:graph:count:)` +- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`. +- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` +- `xorshift64Next(_:)` +- `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`) + +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 + +`/lyrebird_review` required before every merge to `main`. Run on feature branch after all work complete. No merge with blocking findings — fix and re-run until clean. + +Skill behaviour: +1. `swift test` — stops on failure +2. Invokes `lyrebird_review_agent` (RT safety, bus rules, protocol correctness, helper usage, test coverage) +3. Clean pass → appends one-line phase-completion entry to `MEMORY.md` + +Phase completion checklist + branch policy: `docs/00-working-order.md`. After merging a phase to `main`, move its section from `docs/00-working-order.md` into `docs/01-completed-working-order.md` and update the summary table. + +## Protocol Hierarchy + +``` +Generator (base) +├── AudioGenerator (.audio rate — sample-rate processing) +└── ControlGenerator (.control rate — block-rate processing, may sub-block) + +DemandGenerator (NOT a Generator — pure value source, pull-based) +├── DemandSequence (sequential cycling) +└── DemandRandom (random pick, xorshift64 PRNG) + Consumed by Demand.Audio (sample-accurate) / Demand.Control (didTrigger gate) + one value per ≤0→>0 trigger edge. Owned by exactly one puller. + +ValidGeneratorInput +├── Float / Double / Int literals +├── any Generator +└── Closure (wraps ClosureBody) + +Synthesizer +└── DAG of Generator instances (direct wiring) + └── In/Out generators communicate via bus system + +Node tree +SynthesisEngine +└── rootGroup (Group, persistent) + ├── [pre-main nodes] ← .before(engine.mainGroup) + ├── mainGroup (Group, persistent) ← engine.add(_:) default target (head-insertion) + │ └── Synthesizer instances + └── [post-main nodes] ← .after(engine.mainGroup) +``` + +## Legacy Code + +`legacy/Lyrebird/LyrebirdSynth/Lyrebird/` — useful patterns: +- `LyrebirdTypes.swift` — ValidGeneratorInput protocol, type aliases +- `LyrebirdUgen.swift` — Generator base +- `LyrebirdNode.swift` — node tree / groups +- `LyrebirdGraph.swift` — build closure pattern, graph copy +- `UGens/` — oscillators, filters, envelopes, delays (modernize as Generators, don't copy) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..4ab735d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,197 @@ +# Contributing to Lyrebird + +Two distinct paths, depending on what you're building: + +1. **A new built-in Generator** that lands *in this repo* (`Sources/Lyrebird/Generators/…`) — for primitives that belong in the core standard library: oscillators, filters, effects, noise sources, math operators, bus I/O. +2. **An out-of-tree Swift package** that depends on Lyrebird and adds its own Generators / Synthesizers — for domain-specific or third-party libraries you publish and version yourself (e.g. `LyrebirdATK`). + +If you're unsure which you want: contribute in-tree only if the unit is small, general-purpose, and broadly useful. Anything large, opinionated, or with heavy data/dependencies belongs in its own package. + +This guide assumes you've read [`README.md`](README.md), [`ARCHITECTURE.md`](ARCHITECTURE.md) (especially the threading model), and [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md). + +--- + +## The one rule everything follows + +**The real-time audio thread never allocates, never locks, never blocks.** Every constraint below derives from that. If you internalize nothing else, internalize this: anything reachable from a generator's `_computeSamples` / `calculatedSamples` that allocates memory, takes a lock, logs, builds a `String`, force-unwraps, or does a runtime cast is a defect. See [`ARCHITECTURE.md`](ARCHITECTURE.md) §6 for how this is enforced and why. + +--- + +## Part 1 — Contributing a built-in Generator + +### Before you start + +- Read [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md) end to end. It is the authoritative spec; this section is a checklist, not a replacement. +- §13 of that doc is the **shared RT-safe helper catalog**. Inlining boilerplate that a helper already provides is a review-blocking violation. Skim it before writing a loop by hand. +- The hard constraints in [`CLAUDE.md`](CLAUDE.md) ("Hard Constraints", "Swift Code Style Rules", "Shared RT-Safe Helpers — Must Use") are enforced by the review agents. Read them. + +### Workflow + +1. **Branch.** Each unit of work lives on its own branch off `main` (`phase-` or a descriptive name). Never commit directly to `main`. +2. **Scaffold.** Use the Xcode file templates rather than copying an existing file by hand: + ```bash + lyrebird install-templates # one-time + ``` + Then **New File… ▸ Lyrebird** picks the right template: *Generator*, *Oscillator*, *Noise Generator*, *Filter*, *Multi-Channel Generator*, *DemandGenerator*, plus a *Generator Test Suite*. +3. **Implement** following the rules below. +4. **Test** — every new Generator needs a test suite (see checklist). +5. **Review** — run `/lyrebird_review` on your branch. No merge with blocking findings. + +### Decide: Audio rate or Control rate? + +- **`AudioGenerator`** — per-sample processing (`.audio` rate). Oscillators, filters, anything whose output must be sample-accurate. +- **`ControlGenerator`** — block-rate, may sub-block (`.control` rate). Envelopes, LFOs, slow modulation. Cheaper. A `ControlGenerator` feeds an `AudioGenerator` input transparently. + +If a unit is useful at both rates, implement both via the **enum namespace pattern** (`Foo.Audio` / `Foo.Control` + `GeneratorEnum` conformance). `docs/protocols/writing-generators.md` §1 walks this. + +### Hard rules for the generator body + +- **Subclass `GeneratorBase`.** It provides `_segmentSerial`, `_cachedResult`, `_subBlockBuffer`, and `_result` (mono, pre-allocated). Never redeclare these. +- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists. +- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals. +- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode. +- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list. +- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init. +- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline. +- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs). + +### Swift code style (review-blocking) + +- **No force unwraps.** No `!` on optionals, no `try!`. Use `guard let` / `if let` / `?? fallback` / `throws`. +- **No magic numbers.** Every non-trivial literal gets a named `let` (exempt: `0`, `1`, `-1`, `2` where arithmetic meaning is obvious). +- **Explicit type annotations on every binding** — `let x: Int = …`, `for i: Int in …`. (Exceptions: closure params, tuple destructures, pattern-match bindings.) Tool: `Tools/AnnotateBindings/annotate_bindings.py`. +- **Doc comments on every public `init` parameter, in two places** (class-level `/// - Parameters:` block *and* on the `init` itself) — state what it does, unit (Hz / dB / seconds / ratio / [0,1] / frames), range/clamping, default. This is what makes Xcode Quick Help useful from both the type and the call site. +- **Filter resonance naming:** `q:` for quality-factor filters (RBJ, SVF, Butterworth — `0.707` = Butterworth); `resonance:` for raw-feedback filters (Moog ladder, `[0,1]`). Route to whichever the algorithm uses naturally. +- **Multi-line declaration format** when ≥ 2 type aliases or ≥ 2 init params. + +### File organization (review-blocking) + +- **One public type per file.** Each Generator family in its own file (`OscSawtooth.swift`, `Clip.swift`). +- **Never drop a new `.swift` at `Sources/Lyrebird/` root.** Place into the matching subfolder (`Generators/`, `GeneratorCore/`, `Filters/`, `Math/`, etc.). If none fits, propose a new subfolder in the PR description — don't land at root. +- Shared file-scope helpers go in `*Helpers.swift` with `internal` access. + +### Testing checklist + +One `@Suite` per test file, named `Tests.swift`, using Swift Testing (`@Test`, `#expect`). At minimum: + +- Output is non-silent / correct for a known input. +- Audio and Control variants agree where both exist. +- Edge counts: `count` of 1, sub-block sizes, full block. +- Block-boundary instance reuse (state persists correctly across blocks). +- Multi-channel: `outputChannelCount` correct; operator broadcasting behaves. + +Run the suite: +```bash +swift test --no-parallel --filter Tests +``` +Full suite before merge: +```bash +swift test --no-parallel +``` +> Always `--no-parallel`. The default parallel runner SIGABRTs at xctest teardown on multi-engine combos — a known, production-irrelevant flake. One pre-existing flake (`RTThreadIdentity` retain-race) may show on the full run; the filtered suite is deterministic. + +### Submitting + +- Branch off `main`, implement, test, run `/lyrebird_review` until clean. +- PR description: one-line rationale, list of files, and (if you added a subfolder) why. +- Update DocC: add the type to the relevant `Sources/Lyrebird/Lyrebird.docc/` topic and, where appropriate, `docs/stdlib/generators.md`. + +--- + +## Part 2 — Contributing an out-of-tree Swift package + +For Generators / Synthesizers you publish and version yourself. The reference implementation is `LyrebirdATK` (ambisonics). Authoritative docs: + +- [`docs/protocols/extension-sdk.md`](docs/protocols/extension-sdk.md) — the stable public API surface (tier 1) and `@_spi(LyrebirdExtensions)` symbols (tier 2) you may rely on, plus versioning policy. +- [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md) — end-to-end walk-through building a package using LyrebirdATK as the model. + +### Why a separate package? + +In-tree contribution couples you to Lyrebird's release cycle and review bar. A separate package lets you own your source, ship your own releases, and pull heavy data or third-party dependencies that don't belong in core. Core users add your package and pin the version range they want. + +### Naming + +- Package and module: prefix with `Lyrebird` if it's a general toolkit (`LyrebirdATK`), or use your own namespace otherwise. +- Generators follow the same enum-namespace + `.Audio`/`.Control` conventions as core. Don't shadow core type names. + +### `Package.swift` shape + +```swift +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "LyrebirdMyExtension", + platforms: [.macOS(.v15), .iOS(.v18)], // match core's floor — Synchronization.Atomic + products: [ + .library(name: "LyrebirdMyExtension", targets: ["LyrebirdMyExtension"]), + ], + dependencies: [ + .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), + ], + targets: [ + .target( + name: "LyrebirdMyExtension", + dependencies: [.product(name: "Lyrebird", package: "Lyrebird")]), + .testTarget( + name: "LyrebirdMyExtensionTests", + dependencies: ["LyrebirdMyExtension"]), + ] +) +``` + +> Replace the URL with the real repository once published. During development, depend on a local checkout instead: `.package(name: "Lyrebird", path: "/path/to/LyrebirdII")`. + +### What you may import + +```swift +import LyrebirdSynth // tier-1 stable API — Generator/Synthesizer/GeneratorBase, engine types +import struct LyrebirdSynth.MulAddSpec // tier-2 symbols require @_spi +``` + +For tier-2 helpers (MulAdd helpers, the xorshift64 PRNG, test hooks): +```swift +@_spi(LyrebirdExtensions) import LyrebirdSynth +``` + +- **Tier 1** is the contract: it follows semver and won't break within a major version. +- **Tier 2** (`@_spi(LyrebirdExtensions)`) is available but may change between minor versions — pin a tight range if you depend on it. See `extension-sdk.md` § Versioning policy. + +### Same RT rules apply + +A Generator in your package runs on the same RT thread under the same contract. Everything in Part 1's "Hard rules for the generator body" and "Swift code style" applies identically — subclass `GeneratorBase`, `_checkCount(count)` first, pre-allocate in `init`, no allocation/locks/force-unwraps on the RT path. Reuse the tier-2 helpers (`sampleOrZero`, `resolveGeneratorOrScalar`, etc.) where they're `@_spi`-exposed rather than re-rolling them. + +### Testing, compatibility, publishing + +- Test with Swift Testing, same as core. Verify your package builds against the **minimum** Lyrebird version in your dependency range, not just the latest. +- Maintain a compatibility matrix (your version ↔ Lyrebird version) — see `extension-authors-guide.md` § Compatibility matrix. +- Tag releases semver. Document which Lyrebird major version each release targets. + +### Listing your package + +Once published, open a PR adding a row to the **Extensions** table in [`README.md`](README.md). One line: package name (linked) + short description. + +--- + +## Repo maintenance contributors + +If you also edit the Claude agent definitions or skills (maintainers working in `~/.claude/`): + +- Edit only the working copies in `~/.claude/`. Sync the repo mirrors with: + ```bash + bash scripts/sync-claude-from-working.sh --apply + bash scripts/sync-claude-from-working.sh --check # CI / pre-commit drift check + ``` +- Enable the pre-commit drift guard once per clone: `git config core.hooksPath .githooks`. + +--- + +## Questions + +Architecture / threading questions: [`ARCHITECTURE.md`](ARCHITECTURE.md). Generator authoring: [`docs/protocols/writing-generators.md`](docs/protocols/writing-generators.md). Extension packages: [`docs/extension-authors-guide.md`](docs/extension-authors-guide.md). Everything else: the task→doc map in [`CLAUDE.md`](CLAUDE.md). + +--- + +## License + +Lyrebird is MIT-licensed ([`LICENSE`](LICENSE)). By contributing in-tree, you agree your contributions are licensed under the same terms. Out-of-tree packages you publish keep whatever license you choose. diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.pbxproj b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3d9d45b --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.pbxproj @@ -0,0 +1,523 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + D900000000000000000000D1 /* LyrebirdAUv3DemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */; }; + D900000000000000000000D3 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D900000000000000000000D2 /* ContentView.swift */; }; + D900000000000000000000DA /* LyrebirdFMExtension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E5 /* LyrebirdFMExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + E900000000000000000000E1 /* LyrebirdFM.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E0 /* LyrebirdFM.swift */; }; + E900000000000000000000E3 /* LyrebirdFMAudioUnit.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */; }; + E900000000000000000000E7 /* LyrebirdFMAudioUnitViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */; }; + E900000000000000000000EC /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = F900000000000000000000FB /* LyrebirdUI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + D900000000000000000000DC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = F9000000000000000000001 /* Project object */; + proxyType = 1; + remoteGlobalIDString = E900000000000000000000E4; + remoteInfo = LyrebirdFMExtension; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + D900000000000000000000D9 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + D900000000000000000000DA /* LyrebirdFMExtension.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + D900000000000000000000C1 /* LyrebirdAUv3Demo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdAUv3Demo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdAUv3DemoApp.swift; sourceTree = ""; }; + D900000000000000000000D2 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + D900000000000000000000D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D900000000000000000000D5 /* LyrebirdAUv3Demo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdAUv3Demo.entitlements; sourceTree = ""; }; + E900000000000000000000E0 /* LyrebirdFM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFM.swift; sourceTree = ""; }; + E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFMAudioUnit.swift; sourceTree = ""; }; + E900000000000000000000E5 /* LyrebirdFMExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = LyrebirdFMExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdFMAudioUnitViewController.swift; sourceTree = ""; }; + E900000000000000000000E8 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E900000000000000000000E9 /* LyrebirdFMExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdFMExtension.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + D900000000000000000000C7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E900000000000000000000EA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E900000000000000000000EC /* LyrebirdUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + F9000000000000000000002 /* Main */ = { + isa = PBXGroup; + children = ( + D900000000000000000000CE /* LyrebirdAUv3Demo */, + E900000000000000000000EE /* LyrebirdFMExtension */, + F9000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + F9000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + D900000000000000000000C1 /* LyrebirdAUv3Demo.app */, + E900000000000000000000E5 /* LyrebirdFMExtension.appex */, + ); + name = Products; + sourceTree = ""; + }; + D900000000000000000000CE /* LyrebirdAUv3Demo */ = { + isa = PBXGroup; + children = ( + D900000000000000000000D0 /* LyrebirdAUv3DemoApp.swift */, + D900000000000000000000D2 /* ContentView.swift */, + D900000000000000000000D4 /* Info.plist */, + D900000000000000000000D5 /* LyrebirdAUv3Demo.entitlements */, + ); + path = LyrebirdAUv3Demo; + sourceTree = ""; + }; + E900000000000000000000EE /* LyrebirdFMExtension */ = { + isa = PBXGroup; + children = ( + E900000000000000000000E0 /* LyrebirdFM.swift */, + E900000000000000000000E2 /* LyrebirdFMAudioUnit.swift */, + E900000000000000000000E6 /* LyrebirdFMAudioUnitViewController.swift */, + E900000000000000000000E8 /* Info.plist */, + E900000000000000000000E9 /* LyrebirdFMExtension.entitlements */, + ); + path = LyrebirdFMExtension; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + D900000000000000000000C0 /* LyrebirdAUv3Demo */ = { + isa = PBXNativeTarget; + buildConfigurationList = D900000000000000000000CA /* Build configuration list for PBXNativeTarget "LyrebirdAUv3Demo" */; + buildPhases = ( + D900000000000000000000C6 /* Sources */, + D900000000000000000000C7 /* Frameworks */, + D900000000000000000000C8 /* Resources */, + D900000000000000000000D9 /* Embed App Extensions */, + ); + buildRules = ( + ); + dependencies = ( + D900000000000000000000DB /* PBXTargetDependency */, + ); + name = LyrebirdAUv3Demo; + productName = LyrebirdAUv3Demo; + productReference = D900000000000000000000C1 /* LyrebirdAUv3Demo.app */; + productType = "com.apple.product-type.application"; + }; + E900000000000000000000E4 /* LyrebirdFMExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = E900000000000000000000ED /* Build configuration list for PBXNativeTarget "LyrebirdFMExtension" */; + buildPhases = ( + E900000000000000000000EF /* Sources */, + E900000000000000000000EA /* Frameworks */, + E900000000000000000000F0 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdFMExtension; + packageProductDependencies = ( + F900000000000000000000FB /* LyrebirdUI */, + ); + productName = LyrebirdFMExtension; + productReference = E900000000000000000000E5 /* LyrebirdFMExtension.appex */; + productType = "com.apple.product-type.app-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + F9000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 0; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + D900000000000000000000C0 = { + CreatedOnToolsVersion = 16.0; + }; + E900000000000000000000E4 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = F9000000000000000000005 /* Build configuration list for PBXProject "LyrebirdAUv3Demo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = F9000000000000000000002; + packageReferences = ( + F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */, + ); + productRefGroup = F9000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + D900000000000000000000C0 /* LyrebirdAUv3Demo */, + E900000000000000000000E4 /* LyrebirdFMExtension */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + D900000000000000000000C8 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E900000000000000000000F0 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + D900000000000000000000C6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D900000000000000000000D1 /* LyrebirdAUv3DemoApp.swift in Sources */, + D900000000000000000000D3 /* ContentView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E900000000000000000000EF /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E900000000000000000000E1 /* LyrebirdFM.swift in Sources */, + E900000000000000000000E3 /* LyrebirdFMAudioUnit.swift in Sources */, + E900000000000000000000E7 /* LyrebirdFMAudioUnitViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + D900000000000000000000DB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = E900000000000000000000E4 /* LyrebirdFMExtension */; + targetProxy = D900000000000000000000DC /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + F9000000000000000000006 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Automatic; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_NS_ASSERTIONS = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + F9000000000000000000007 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Automatic; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + D900000000000000000000CB /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_ASSET_PATHS = ""; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = LyrebirdAUv3Demo/Info.plist; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + D900000000000000000000CC /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_ASSET_PATHS = ""; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = LyrebirdAUv3Demo/Info.plist; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + E900000000000000000000F1 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdFMExtension/LyrebirdFMExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = LyrebirdFMExtension/Info.plist; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@executable_path/../../../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo.LyrebirdFMExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + E900000000000000000000F2 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdFMExtension/LyrebirdFMExtension.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = LyrebirdFMExtension/Info.plist; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + "@executable_path/../../../../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdAUv3Demo.LyrebirdFMExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + F9000000000000000000005 /* Build configuration list for PBXProject "LyrebirdAUv3Demo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F9000000000000000000006 /* Debug */, + F9000000000000000000007 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D900000000000000000000CA /* Build configuration list for PBXNativeTarget "LyrebirdAUv3Demo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D900000000000000000000CB /* Debug */, + D900000000000000000000CC /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E900000000000000000000ED /* Build configuration list for PBXNativeTarget "LyrebirdFMExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E900000000000000000000F1 /* Debug */, + E900000000000000000000F2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + F900000000000000000000FB /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = F9000000000000000000004 /* XCLocalSwiftPackageReference "../.." */; + productName = LyrebirdUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = F9000000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..b74f789 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "8c7cdbbec3286a359d81508a5a793e75295e1a598c53be84529e7a375cad48be", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/xcshareddata/xcschemes/LyrebirdAUv3Demo.xcscheme b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/xcshareddata/xcschemes/LyrebirdAUv3Demo.xcscheme new file mode 100644 index 0000000..2030810 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj/xcshareddata/xcschemes/LyrebirdAUv3Demo.xcscheme @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/ContentView.swift b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/ContentView.swift new file mode 100644 index 0000000..5f19a5f --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/ContentView.swift @@ -0,0 +1,25 @@ +// ContentView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI + +struct ContentView: View { + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("LyrebirdFM AUv3") + .font(.title) + .bold() + Text("Run this app once so macOS registers the bundled AUv3 extension. After that, load **Realized Sound: LyrebirdFM** from any AUv3 host — Logic, GarageBand, AUM, Loopy Pro, etc.") + .font(.body) + Spacer() + Text("Lyrebird AUv3 demo") + .font(.caption) + .foregroundStyle(.secondary) + } + .padding(24) + .frame(minWidth: 480, minHeight: 240) + } +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/Info.plist b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/Info.plist new file mode 100644 index 0000000..8f06f96 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + + diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements new file mode 100644 index 0000000..18aff0c --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3Demo.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-only + + + diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3DemoApp.swift b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3DemoApp.swift new file mode 100644 index 0000000..b6bba19 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo/LyrebirdAUv3DemoApp.swift @@ -0,0 +1,23 @@ +// LyrebirdAUv3DemoApp.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI + +/// Container app for the LyrebirdFM AUv3 extension. +/// +/// Installing this app is what registers the bundled `.appex` extension +/// with the system AU registry. The app itself is a minimal SwiftUI +/// placeholder — its only purpose is to ship the extension. Use the AU +/// from any AUv3 host (Logic, GarageBand, AUM, Loopy Pro, etc.) after +/// running the app once. +@main +struct LyrebirdAUv3DemoApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/Info.plist b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/Info.plist new file mode 100644 index 0000000..e1a9999 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/Info.plist @@ -0,0 +1,59 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + LyrebirdFM + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + XPC! + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + NSExtension + + NSExtensionAttributes + + AudioComponentBundle + $(PRODUCT_BUNDLE_IDENTIFIER) + AudioComponents + + + name + Realized Sound: LyrebirdFM + description + Two-operator FM synthesizer (Lyrebird demo) + type + aumu + subtype + LBFM + manufacturer + RLZS + version + 65536 + sandboxSafe + + tags + + Synth + + + + + NSExtensionPointIdentifier + com.apple.AudioUnit-UI + NSExtensionPrincipalClass + LyrebirdFMExtension.LyrebirdFMAudioUnitViewController + + + diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFM.swift b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFM.swift new file mode 100644 index 0000000..96401ef --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFM.swift @@ -0,0 +1,44 @@ +// LyrebirdFM.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Two-operator FM synthesizer used by the AUv3 demo extension. +/// +/// Carrier and modulator are both `OscSin.Audio`. The modulator's output is +/// added to the carrier's frequency input; modulation depth is +/// `modIndex * carrierFreq` so the index reads as a unitless ratio (1.0 ≈ +/// one octave of FM bandwidth at the carrier). +/// +/// All four `@LiveParam`s map onto AU parameters in `LyrebirdFMAudioUnit`'s +/// `parameterMetadata()` table. +final class LyrebirdFM: SynthesizerBase { + + /// Carrier frequency in Hz. Range [20, 8000]. Default 440 (A4). + @LiveParam var carrierFreq: Double = 440.0 + + /// Modulator-to-carrier frequency ratio. Range [0.25, 16]. Default 2.0 + /// (one octave above carrier — produces an even-harmonic-rich timbre). + @LiveParam var modRatio: Double = 2.0 + + /// Modulation index (unitless). Range [0, 8]. Default 0.5 — mild + /// modulation; sounds close to a sine with extra brightness. + @LiveParam var modIndex: Double = 0.5 + + /// Output amplitude. Range [0, 1]. Default 0.3 — leaves headroom. + @LiveParam var amp: Double = 0.3 + + override func build() { + let modFreq = $carrierFreq * $modRatio + let modDepth = $modIndex * $carrierFreq + let modulator = OscSin.Audio(freq: modFreq, mul: modDepth) + let carrier = OscSin.Audio(freq: $carrierFreq + modulator) + let voice = carrier * $amp + // Mono → both stereo channels for AUv3 host compatibility. + output(bus: 0, source: voice) + output(bus: 1, source: voice) + } +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnit.swift b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnit.swift new file mode 100644 index 0000000..e44c4e0 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnit.swift @@ -0,0 +1,33 @@ +// LyrebirdFMAudioUnit.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import AVFoundation +import AudioToolbox + +/// AUv3 wrapper around `LyrebirdFM`. Subclasses ``LyrebirdAudioUnit`` and +/// only overrides the two required hooks: `makeSynthesizer()` and +/// `parameterMetadata()`. +/// +/// The `AudioComponentDescription` (type `aumu`, subtype `LBFM`, +/// manufacturer `RLZS`) is declared in `Info.plist`'s `AudioComponents` +/// array; this class is instantiated by the AU host via +/// `NSExtensionPrincipalClass` resolution. +public final class LyrebirdFMAudioUnit: LyrebirdAudioUnit { + + public override class func makeSynthesizer() -> SynthesizerBase { + LyrebirdFM() + } + + public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { + [ + "carrierFreq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Carrier Freq"), + "modRatio": .init(min: 0.25, max: 16, unit: .generic, displayName: "Mod Ratio"), + "modIndex": .init(min: 0, max: 8, unit: .generic, displayName: "Mod Index"), + "amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Output Amp"), + ] + } +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnitViewController.swift b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnitViewController.swift new file mode 100644 index 0000000..7f59e40 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMAudioUnitViewController.swift @@ -0,0 +1,38 @@ +// LyrebirdFMAudioUnitViewController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import CoreAudioKit +import AVFoundation + +/// AUv3 view controller + factory. +/// +/// `AUAudioUnitFactory` conformance is how AUv3 hosts instantiate the +/// underlying `AUAudioUnit` — the host loads this view controller as the +/// extension's `NSExtensionPrincipalClass`, calls +/// `createAudioUnit(with:)`, and the resulting AU is what handles render. +/// +/// Ships an empty placeholder view. Drop in `LyrebirdSynthView` (from +/// `LyrebirdUI`) to get a Mirror-driven SwiftUI parameter grid. +public final class LyrebirdFMAudioUnitViewController: AUViewController, AUAudioUnitFactory { + + /// Strong reference to the AU once `createAudioUnit(with:)` builds it. + /// The host keeps a separate reference; this is held so a SwiftUI view + /// added on top can read parameters from the same instance. + public private(set) var audioUnit: AUAudioUnit? + + public override func viewDidLoad() { + super.viewDidLoad() + // Empty stub — install a SwiftUI host (e.g. `LyrebirdSynthView`) here. + } + + public func createAudioUnit( + with componentDescription: AudioComponentDescription + ) throws -> AUAudioUnit { + let au = try LyrebirdFMAudioUnit(componentDescription: componentDescription) + audioUnit = au + return au + } +} diff --git a/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMExtension.entitlements b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMExtension.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/LyrebirdFMExtension.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/Demos/LyrebirdAUv3Demo/README.md b/Demos/LyrebirdAUv3Demo/README.md new file mode 100644 index 0000000..becd4e7 --- /dev/null +++ b/Demos/LyrebirdAUv3Demo/README.md @@ -0,0 +1,156 @@ +# LyrebirdAUv3Demo + +Reference AUv3 plugin built on Lyrebird's `LyrebirdAudioUnit`. Ships +**Realized Sound: LyrebirdFM** — a two-operator FM synthesizer — as an +`aumu` instrument loadable in any AUv3 host (Logic, GarageBand, AUM, +Loopy Pro, etc.). + +Copy this directory as the starting point for your own Lyrebird-based +AUv3 plugin. + +## Layout + +``` +LyrebirdAUv3Demo/ + LyrebirdAUv3Demo.xcodeproj Hand-written Xcode project (app + extension) + LyrebirdAUv3Demo/ Container app target (.app) + LyrebirdAUv3DemoApp.swift SwiftUI app entry — minimal + ContentView.swift One-screen "installer" view + Info.plist + LyrebirdAUv3Demo.entitlements App sandbox + LyrebirdFMExtension/ AUv3 extension target (.appex) + LyrebirdFM.swift The two-op FM SynthesizerBase subclass + LyrebirdFMAudioUnit.swift LyrebirdAudioUnit subclass (metadata + factory) + LyrebirdFMAudioUnitViewController.swift AUViewController + AUAudioUnitFactory stub + Info.plist AudioComponents (aumu / LBFM / RLZS) + LyrebirdFMExtension.entitlements App-extension sandbox +``` + +## Build + +### From the command line + +```bash +xcodebuild \ + -project Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj \ + -scheme LyrebirdAUv3Demo \ + -configuration Release \ + CODE_SIGN_IDENTITY="-" \ + CODE_SIGNING_REQUIRED=NO \ + CODE_SIGNING_ALLOWED=NO \ + SWIFT_USE_INTEGRATED_DRIVER=NO \ + build +``` + +`SWIFT_USE_INTEGRATED_DRIVER=NO` is the Xcode 26 workaround documented +elsewhere in the Lyrebird build notes; it disables explicit-module-build +so SPM dynamic-framework modules resolve correctly. The +`CODE_SIGN_IDENTITY="-"` triple disables signing entirely for local +builds — for distribution you must set `DEVELOPMENT_TEAM` to your Apple +Developer Team ID and use `Automatic` signing. + +### From Xcode + +1. Open `LyrebirdAUv3Demo.xcodeproj`. +2. Pick the **LyrebirdAUv3Demo** scheme. +3. In each target's Signing & Capabilities tab, set your Team. The + bundle ID `net.realizedsound.LyrebirdAUv3Demo` is a Realized-Sound + placeholder — change to a prefix you own. +4. Add `SWIFT_USE_INTEGRATED_DRIVER = NO` under each target's + Build Settings → User-Defined (or set it project-wide). Required on + Xcode 26+. +5. **Build & Run** the container app once. This registers the embedded + extension with the AU registry. + +## Validate with auval + +After running the container app at least once so the extension is +registered: + +```bash +auval -v aumu LBFM RLZS +``` + +A `PASS` summary is what you want. Common gotchas the wrapper already +handles: + +- `latency` returns 0 (`LyrebirdAudioUnit.latency`). +- `tailTime` returns 0 (instrument has no internal tail). +- `parameterTree` is populated synchronously in `init`, so `auval` + sees it before render. +- `internalRenderBlock` returns `noErr` and writes valid samples. +- `maximumFramesToRender` is honoured by `AUv3Driver` via ring sizing. + +If you see "Cannot get Component's Name strings" or "didn't find the +component", the extension was not registered. Either the container app +has not been launched yet, or `lsregister` did not pick it up. Re-run +the container app from Xcode, then re-run `auval`. + +## Smoke test in a host + +1. **Logic Pro / GarageBand**: Track → New Software Instrument → AU + Instruments → Realized Sound → LyrebirdFM. Play a few MIDI notes + (this template ships no MIDI handler — the plugin instantiates and + accepts parameter automation, but won't respond to note input until + you wire `LyrebirdAudioUnit.midiHandler`; see [`AUv3.md`](../../Sources/Lyrebird/Lyrebird.docc/AUv3.md)). +2. **AUM / Loopy Pro** (iOS): same idea once the iOS variant of this + demo lands. + +## What's in the wrapper + +`LyrebirdFMAudioUnit` is the entire wrapper: + +```swift +public final class LyrebirdFMAudioUnit: LyrebirdAudioUnit { + public override class func makeSynthesizer() -> SynthesizerBase { LyrebirdFM() } + public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] { + [ + "carrierFreq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Carrier Freq"), + "modRatio": .init(min: 0.25, max: 16, unit: .generic, displayName: "Mod Ratio"), + "modIndex": .init(min: 0, max: 8, unit: .generic, displayName: "Mod Index"), + "amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Output Amp"), + ] + } +} +``` + +`LyrebirdAudioUnit` does the rest: parameter tree from `Mirror`, engine +lifecycle, ring-buffered render, `fullState` save / restore. See +[`Sources/Lyrebird/Lyrebird.docc/AUv3.md`](../../Sources/Lyrebird/Lyrebird.docc/AUv3.md) +for the full API surface. + +## Copying this template + +To ship your own AUv3 plugin: + +1. Duplicate `Demos/LyrebirdAUv3Demo/` under a new name. +2. Replace `LyrebirdFM` with your own `SynthesizerBase` subclass. +3. Update `componentSubType` (4-char code, must be unique to your + plugin) and `manufacturer` (your 4-char manufacturer code) in + the extension's `Info.plist → NSExtension → NSExtensionAttributes + → AudioComponents`. +4. Update `PRODUCT_BUNDLE_IDENTIFIER` in both targets' + build settings to your own reverse-DNS prefix. +5. Replace `Realized Sound: LyrebirdFM` strings with your own + manufacturer + plugin name. +6. Rebuild, run, `auval -v `. + +## Not yet wired in this template + +The framework supports all of the following — this particular demo +template just doesn't include them yet. Each is a follow-up exercise +when copying the template: + +- MIDI note input — set `au.midiHandler` and dispatch via + ``LyrebirdAUVoicePoolBinding``. +- SwiftUI parameter UI in the view controller — drop in + ``LyrebirdSynthView`` (see [`LyrebirdSynthView`](../../Sources/LyrebirdUI/LyrebirdSynthView.swift)). +- Source-slot preset save/restore — conform any source generator to + ``LyrebirdAUPresetCodable`` and register it. +- Effect-type AU (`aufx`) — override ``LyrebirdAudioUnit/lyrebirdInputChannels`` + and read host audio via ``AUInput/Audio``. +- iOS container app target — duplicate the Mac app target and switch + the platform. + +The demo deliberately ships the smallest cut that proves the wrapper +loads and validates. diff --git a/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7fa1545 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.pbxproj @@ -0,0 +1,400 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7BF2FAC451300952EAF /* GVerbTest.swift */; }; + 0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */; }; + 035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */; }; + 035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */; }; + 035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */; }; + 035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */; }; + 035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */; }; + 035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035A2F462FAA6950007F6289 /* PercTimeStretch.swift */; }; + 035B00012FAB0000007F0001 /* DemoProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035B00032FAB0000007F0001 /* DemoProtocol.swift */; }; + 035B00022FAB0000007F0001 /* BufferDemos.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035B00042FAB0000007F0001 /* BufferDemos.swift */; }; + C1A000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000006 /* main.swift */; }; + C1A000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C1A000000000000000000012 /* Lyrebird */; }; + C1A000000000000000000016 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000014 /* SineTone.swift */; }; + C1A000000000000000000017 /* DelaySample.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000015 /* DelaySample.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 0306C7BF2FAC451300952EAF /* GVerbTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GVerbTest.swift; sourceTree = ""; }; + 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReverbDemo.swift; sourceTree = ""; }; + 035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercBufferRead.swift; sourceTree = ""; }; + 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPitchShift.swift; sourceTree = ""; }; + 035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercPlayBuffer.swift; sourceTree = ""; }; + 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercSpectralPitchShift.swift; sourceTree = ""; }; + 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercSpectralStereoDiffuse.swift; sourceTree = ""; }; + 035A2F462FAA6950007F6289 /* PercTimeStretch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PercTimeStretch.swift; sourceTree = ""; }; + 035B00032FAB0000007F0001 /* DemoProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoProtocol.swift; sourceTree = ""; }; + 035B00042FAB0000007F0001 /* BufferDemos.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BufferDemos.swift; sourceTree = ""; }; + C1A000000000000000000004 /* LyrebirdDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdDemo; sourceTree = BUILT_PRODUCTS_DIR; }; + C1A000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + C1A000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = ""; }; + C1A000000000000000000015 /* DelaySample.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelaySample.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C1A000000000000000000009 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C1A000000000000000000013 /* Lyrebird in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 035B00052FAB0000007F0001 /* Demos */ = { + isa = PBXGroup; + children = ( + 0306C7C12FAC45F200952EAF /* ReverbDemo.swift */, + 035B00032FAB0000007F0001 /* DemoProtocol.swift */, + 035B00042FAB0000007F0001 /* BufferDemos.swift */, + ); + path = Demos; + sourceTree = ""; + }; + 035B00062FAB0000007F0001 /* Buffer */ = { + isa = PBXGroup; + children = ( + 035A2F3E2FAA4F67007F6289 /* PercBufferRead.swift */, + 035A2F402FAA4F67007F6289 /* PercPlayBuffer.swift */, + ); + path = Buffer; + sourceTree = ""; + }; + 035B00072FAB0000007F0001 /* Granular */ = { + isa = PBXGroup; + children = ( + 035A2F3F2FAA4F67007F6289 /* PercPitchShift.swift */, + 035A2F462FAA6950007F6289 /* PercTimeStretch.swift */, + ); + path = Granular; + sourceTree = ""; + }; + 035B00082FAB0000007F0001 /* Spectral */ = { + isa = PBXGroup; + children = ( + 035A2F412FAA4F67007F6289 /* PercSpectralPitchShift.swift */, + 035A2F492FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift */, + ); + path = Spectral; + sourceTree = ""; + }; + 035B00092FAB0000007F0001 /* General */ = { + isa = PBXGroup; + children = ( + C1A000000000000000000015 /* DelaySample.swift */, + C1A000000000000000000014 /* SineTone.swift */, + ); + path = General; + sourceTree = ""; + }; + C1A000000000000000000002 = { + isa = PBXGroup; + children = ( + C1A000000000000000000005 /* LyrebirdDemo */, + C1A000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C1A000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C1A000000000000000000004 /* LyrebirdDemo */, + ); + name = Products; + sourceTree = ""; + }; + C1A000000000000000000005 /* LyrebirdDemo */ = { + isa = PBXGroup; + children = ( + C1A000000000000000000006 /* main.swift */, + 035B00052FAB0000007F0001 /* Demos */, + C1A000000000000000000018 /* Synthesizers */, + ); + path = LyrebirdDemo; + sourceTree = ""; + }; + C1A000000000000000000018 /* Synthesizers */ = { + isa = PBXGroup; + children = ( + 0306C7BF2FAC451300952EAF /* GVerbTest.swift */, + 035B00062FAB0000007F0001 /* Buffer */, + 035B00072FAB0000007F0001 /* Granular */, + 035B00082FAB0000007F0001 /* Spectral */, + 035B00092FAB0000007F0001 /* General */, + ); + path = Synthesizers; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C1A00000000000000000000A /* LyrebirdDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = C1A00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdDemo" */; + buildPhases = ( + C1A000000000000000000008 /* Sources */, + C1A000000000000000000009 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdDemo; + packageProductDependencies = ( + C1A000000000000000000012 /* Lyrebird */, + ); + productName = LyrebirdDemo; + productReference = C1A000000000000000000004 /* LyrebirdDemo */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C1A000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C1A00000000000000000000A = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C1A00000000000000000000E /* Build configuration list for PBXProject "LyrebirdDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C1A000000000000000000002; + packageReferences = ( + C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */, + ); + productRefGroup = C1A000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C1A00000000000000000000A /* LyrebirdDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + C1A000000000000000000008 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 035B00012FAB0000007F0001 /* DemoProtocol.swift in Sources */, + 035B00022FAB0000007F0001 /* BufferDemos.swift in Sources */, + 0306C7C02FAC451300952EAF /* GVerbTest.swift in Sources */, + 035A2F422FAA4F67007F6289 /* PercPitchShift.swift in Sources */, + 035A2F432FAA4F67007F6289 /* PercSpectralPitchShift.swift in Sources */, + 035A2F482FAA4F67007F6289 /* PercSpectralStereoDiffuse.swift in Sources */, + 035A2F442FAA4F67007F6289 /* PercBufferRead.swift in Sources */, + 0306C7C22FAC45F200952EAF /* ReverbDemo.swift in Sources */, + 035A2F452FAA4F67007F6289 /* PercPlayBuffer.swift in Sources */, + C1A000000000000000000007 /* main.swift in Sources */, + C1A000000000000000000016 /* SineTone.swift in Sources */, + 035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */, + C1A000000000000000000017 /* DelaySample.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C1A00000000000000000000C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + }; + name = Debug; + }; + C1A00000000000000000000D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + DEAD_CODE_STRIPPING = YES; + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + }; + name = Release; + }; + C1A00000000000000000000F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C1A000000000000000000010 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C1A00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C1A00000000000000000000C /* Debug */, + C1A00000000000000000000D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C1A00000000000000000000E /* Build configuration list for PBXProject "LyrebirdDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C1A00000000000000000000F /* Debug */, + C1A000000000000000000010 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C1A000000000000000000012 /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = C1A000000000000000000011 /* XCLocalSwiftPackageReference "../.." */; + productName = Lyrebird; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C1A000000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..073b396 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "2c98cd4172bcfb3eff9cb6e34a538f80f5e424aa73fbd5bea2b20cf0c8b539b7", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdDemo.xcscheme b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdDemo.xcscheme new file mode 100644 index 0000000..5407b6c --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdDemo.xcscheme @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift new file mode 100644 index 0000000..cb363ea --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift @@ -0,0 +1,136 @@ +// BufferDemos.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +final class BufferDemos: DemoProtocol { + + private let engine: SynthesisEngine + + init(engine: SynthesisEngine) { + self.engine = engine + } + + func runDemo() { + // BufferDemos.swift lives at .../Demos/LyrebirdDemo/LyrebirdDemo/Demos/BufferDemos.swift + // — 4 components up to reach .../Demos/ where Perc.aiff lives. + let percURL = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // .../Demos/ + .deletingLastPathComponent() // .../LyrebirdDemo/ + .deletingLastPathComponent() // .../LyrebirdDemo (package)/ + .deletingLastPathComponent() // .../Demos/ + .appendingPathComponent("Mozart.aiff") + + let percBuffer: LyrebirdBuffer + do { + percBuffer = try LyrebirdBuffer.load(url: percURL) + print("Loaded \(percURL.lastPathComponent): \(percBuffer.count) frames, SR \(percBuffer.sampleRate.map { "\($0) Hz" } ?? "unknown")") + } catch { + print("Failed to load Perc.aiff: \(error)") + engine.stop() + exit(1) + } + + let sampleRate = engine.sampleRate + + LyrebirdTask.run(engine: engine) { ctx in + // Demo 1 — PlayBuffer (looping at native rate) + + print("\n── Demo 1: PlayBuffer (looping) ──") + let demo1 = PercPlayBuffer(buffer: percBuffer, engineSampleRate: sampleRate) + ctx.add(demo1) + try ctx.wait(seconds: 6) + ctx.remove(demo1) + try ctx.wait(seconds: 0.2) + + // Demo 2 — BufferRead (sine-wave position scan) + print("\n── Demo 2: BufferRead (sine-wave position scan) ──") + let demo2 = PercBufferRead(buffer: percBuffer) + ctx.add(demo2) + try ctx.wait(seconds: 6) + ctx.remove(demo2) + try ctx.wait(seconds: 0.2) + + // Demo 3 — PlayBuffer → PitchShift (cycling through pitch ratios) + print("\n── Demo 3: PlayBuffer → PitchShift ──") + let demo3 = PercPitchShift(buffer: percBuffer, engineSampleRate: sampleRate) + ctx.add(demo3) + + let pitchSteps: [(Double, String)] = [ + (0.5, "0.5 — octave down"), + (0.75, "0.75 — minor third down"), + (1.0, "1.0 — original pitch"), + (1.5, "1.5 — perfect fifth up"), + (2.0, "2.0 — octave up"), + ] + for (ratio, label) in pitchSteps { + print(" pitchRatio \(label)") + demo3.pitchRatio = ratio + try ctx.wait(seconds: 3) + } + ctx.remove(demo3) + try ctx.wait(seconds: 0.5) + + // Demo 4 — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift) + print("\n── Demo 4: PlayBuffer → SpectralChain.Audio (SpectralPitchShift) ──") + + let spectralRatios: [(Double, String)] = [ + (0.5, "0.5 — octave down (phase vocoder)"), + (1.0, "1.0 — no shift (phase vocoder passthrough)"), + (1.5, "1.5 — perfect fifth up (phase vocoder)"), + (2.0, "2.0 — octave up (phase vocoder)"), + ] + for (ratio, label) in spectralRatios { + print(" pitchRatio \(label)") + let demo4 = PercSpectralPitchShift(buffer: percBuffer, pitchRatio: ratio, engineSampleRate: sampleRate) + ctx.add(demo4) + try ctx.wait(seconds: 5) + ctx.remove(demo4) + try ctx.wait(seconds: 0.3) + } + + // Demo 5 — SpectralChain.Audio fan-out (mono → 2-channel decorrelated stereo) + print("\n── Demo 5: SpectralChain.Audio fan-out (SpectralStereoDiffuse) ──") + + let diffuseSteps: [(Double, String)] = [ + (0.0, "0.0 — bypass (mono passthrough on both channels)"), + (0.5, "0.5 — half decorrelation"), + (1.0, "1.0 — full per-channel phase randomisation"), + ] + for (amount, label) in diffuseSteps { + print(" amount \(label)") + let demo5 = PercSpectralStereoDiffuse( + buffer: percBuffer, amount: amount, engineSampleRate: sampleRate) + ctx.add(demo5) + try ctx.wait(seconds: 5) + ctx.remove(demo5) + try ctx.wait(seconds: 0.3) + } + + // Demo 6 — TimeStretch (granular, pitch-preserved time stretching + compression) + print("\n── Demo 6: TimeStretch (granular time-stretch / compression) ──") + + let stretchSteps: [(Double, String)] = [ + (3.0, "3.0 — 3× stretch (one-third speed, pitch preserved)"), + (1.5, "1.5 — 1.5× stretch (three-quarter speed, pitch preserved)"), + (1.0, "1.0 — native speed (no stretch)"), + (0.5, "0.5 — 2× compression (double speed, pitch preserved)"), + (0.33, "0.33 — 3× compression (triple speed, pitch preserved)"), + ] + for (factor, label) in stretchSteps { + print(" stretchFactor \(label)") + let demo6 = PercTimeStretch(buffer: percBuffer, stretchFactor: factor) + ctx.add(demo6) + try ctx.wait(seconds: 6) + ctx.remove(demo6) + try ctx.wait(seconds: 0.3) + } + + print("\nAll buffer demos complete.") + } + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/DemoProtocol.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/DemoProtocol.swift new file mode 100644 index 0000000..c237561 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/DemoProtocol.swift @@ -0,0 +1,11 @@ +// DemoProtocol.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +protocol DemoProtocol { + func runDemo() +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift new file mode 100644 index 0000000..21f103f --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Demos/ReverbDemo.swift @@ -0,0 +1,42 @@ +// ReverbDemo.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// +// BufferDemos 2.swift +// LyrebirdDemo +// +// Created by Joshua Parmenter on 5/6/26. +// + + +import Foundation +import LyrebirdSynth + +final class ReverbDemo: DemoProtocol { + + private let engine: SynthesisEngine + + init(engine: SynthesisEngine) { + self.engine = engine + } + + func runDemo() { + + let sampleRate = engine.sampleRate + // sets up its own thread / timing, etc + LyrebirdTask.run(engine: engine) { [sampleRate] ctx in + ctx.tempo = 60.0 + let reverbDemo = GVerbTest( + sampleRate: sampleRate + ) + ctx.add(reverbDemo) + try ctx.wait(beats: 6) // could also use seconds + ctx.remove(reverbDemo) + print("\nAll buffer demos complete.") + } + } +} + diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercBufferRead.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercBufferRead.swift new file mode 100644 index 0000000..cab05c6 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercBufferRead.swift @@ -0,0 +1,36 @@ +// PercBufferRead.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// BufferRead demo — normalized-position random-access playback driven by a sine-wave position. +/// +/// `BufferRead.Audio` has no internal play-head; position `[0,1]` is entirely external. +/// Here an `OscSin` at the buffer's natural loop frequency is mapped from `[-1, 1]` to `[0, 1]` +/// to sweep forward and backward through the sample sinusoidally. This produces a natural +/// pitch-warping effect as the scan accelerates through the middle and slows at the ends. +/// +/// For a true sawtooth scan (constant-speed linear loop), replace the position expression +/// with a dedicated `Phasor.Audio` when available in the stdlib. +final class PercBufferRead: SynthesizerBase { + let buffer: LyrebirdBuffer + + init(buffer: LyrebirdBuffer) { + self.buffer = buffer + super.init() + } + + override func build() { + // phasorFrequency: frequency at which a linear phasor sweeps 0→1 in one buffer duration. + let scanFreq = buffer.phasorFrequency ?? 1.0 + + // Sine at scanFreq maps [-1, 1] → [0, 1] giving a smooth forward+backward position sweep. + let position = (OscSin.Audio(freq: scanFreq) + 1.0) * 0.5 + + let reader = BufferRead.Audio(buffer: buffer, position: position, interpolation: .linear) + output(bus: 0, source: Pan2(input: reader[0], mul: 0.6)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercPlayBuffer.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercPlayBuffer.swift new file mode 100644 index 0000000..2a1113b --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Buffer/PercPlayBuffer.swift @@ -0,0 +1,30 @@ +// PercPlayBuffer.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Looping PlayBuffer demo — plays `Perc.aiff` in a continuous loop at native sample rate. +/// +/// `nativeRateScale` compensates for any mismatch between the file's sample rate and the +/// engine's sample rate. For a stereo engine the mono buffer's single channel is centred +/// via `Pan2`. +final class PercPlayBuffer: SynthesizerBase { + let buffer: LyrebirdBuffer + let engineSampleRate: Double + + init(buffer: LyrebirdBuffer, engineSampleRate: Double) { + self.buffer = buffer + self.engineSampleRate = engineSampleRate + super.init() + } + + override func build() { + // Compensate for any file SR ≠ engine SR (e.g. 44.1 kHz file in 48 kHz engine). + let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate) + let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale) + output(bus: 0, source: Pan2(input: player[0], mul: 0.6)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/GVerbTest.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/GVerbTest.swift new file mode 100644 index 0000000..50b72b0 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/GVerbTest.swift @@ -0,0 +1,35 @@ +// GVerbTest.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// +// GVerbTest.swift +// LyrebirdDemo +// +// Created by Joshua Parmenter on 5/6/26. +// + +import LyrebirdSynth + +final class GVerbTest: SynthesizerBase { + private let sampleRate: Double + + init(sampleRate: Double) { + self.sampleRate = sampleRate + } + + override func build() { + let impulse = Impulse.Audio(freq: 0.5) + let reverb = GVerb.Audio(source: impulse, + roomSize: 70.0, + reverbTime: 3.0, + earlyLevel: 0.4, + tailLevel: 0.9, + dryLevel: 0.1, + sampleRate: sampleRate + ) + output(bus: 0, source: reverb) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/DelaySample.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/DelaySample.swift new file mode 100644 index 0000000..166612a --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/DelaySample.swift @@ -0,0 +1,30 @@ +// DelaySample.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +final class DelaySample: SynthesizerBase { + let delayTime: any ValidGeneratorInput + let amp: any ValidGeneratorInput + + init(delayTime: any ValidGeneratorInput, amp: any ValidGeneratorInput = 0.2) { + self.delayTime = delayTime + self.amp = amp + super.init() + } + + override func build() { + let testTone = OscSin.Audio(freq: 220.0) * 0.1 + let delay = DelayLine( + input: testTone, + maxDelay: 2.0, + delay: delayTime + (OscSin.Audio(freq: 0.4) * 0.05), + interpolation: DelayInterpolation.cubic + ) + output(bus: 0, source: testTone) + output(bus: 1, source: delay) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/SineTone.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/SineTone.swift new file mode 100644 index 0000000..d507636 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/General/SineTone.swift @@ -0,0 +1,46 @@ +// SineTone.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Stereo sine tone with runtime-updatable frequency and amplitude. +/// +/// Parameters are declared as `@LiveParam` properties, backed by `ParameterNode` — a +/// lock-free atomic `AudioGenerator`. Setting a property on the main thread issues a +/// releasing atomic store; the RT thread picks up the new value at the start of the next +/// block and linearly ramps to it over the block, preventing clicks on frequency jumps. +/// +/// Usage: +/// ```swift +/// let tone = SineTone() +/// try engine.add(tone) +/// Thread.sleep(forTimeInterval: 2.0) +/// tone.freq = 880.0 // no try, no string — RT-safe atomic write +/// ``` +final class SineTone: SynthesizerBase { + let freq: any ValidGeneratorInput + let amp: any ValidGeneratorInput + let outbus: AudioBus + + init( + freq: any ValidGeneratorInput, + amp: any ValidGeneratorInput = 0.2, + outbus: AudioBus + ) { + self.freq = freq + self.amp = amp + self.outbus = outbus + super.init() + } + + + override func build() { + // $freq and $amp are ParameterNodes (AudioGenerator) — OscSin detects them as + // generators and requests a full per-sample interpolated block each block. + let osc = OscSin.Audio(freq: freq) + output(bus: outbus.index, source: Pan2(input: osc * amp)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercPitchShift.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercPitchShift.swift new file mode 100644 index 0000000..e688201 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercPitchShift.swift @@ -0,0 +1,47 @@ +// PercPitchShift.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Granular pitch-shift demo — looping PlayBuffer fed into TuneablePitchShift.Audio. +/// +/// `pitchRatio` is a `@LiveParam`-backed `ParameterNode` wired directly into +/// `TuneablePitchShift.Audio`. Updating `synth.pitchRatio` on the main thread issues an +/// atomic store; the RT thread ramps to the new value at the next block boundary. +/// +/// Pitch ratios: +/// 0.5 = one octave down +/// 0.75 = a minor third down +/// 1.0 = no shift (original pitch) +/// 1.5 = a perfect fifth up +/// 2.0 = one octave up +final class PercPitchShift: SynthesizerBase { + let buffer: LyrebirdBuffer + let engineSampleRate: Double + @LiveParam var pitchRatio: Double = 1.0 + + init(buffer: LyrebirdBuffer, engineSampleRate: Double) { + self.buffer = buffer + self.engineSampleRate = engineSampleRate + super.init() + } + + override func build() { + let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate) + let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale) + + // $pitchRatio is a ParameterNode — polled once per block by TuneablePitchShift. + let shifted = TuneablePitchShift.Audio( + input: player[0], + pitchRatio: $pitchRatio, + windowSize: 0.11, + overlap: 4, + timeDispersion: 0.01, + interpolation: .cubic + ) + output(bus: 0, source: Pan2(input: shifted, mul: 0.5)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercTimeStretch.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercTimeStretch.swift new file mode 100644 index 0000000..1fc9c00 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Granular/PercTimeStretch.swift @@ -0,0 +1,66 @@ +// PercTimeStretch.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Granular time-stretch demo — drives `TimeStretch.Audio` with a looping position pointer +/// that advances at a rate determined by `stretchFactor`. +/// +/// - `stretchFactor > 1.0` = time stretch (e.g. 2.0 = half speed, pitch preserved) +/// - `stretchFactor = 1.0` = native speed +/// - `stretchFactor < 1.0` = time compression (e.g. 0.5 = double speed, pitch preserved) +/// +/// `pos` is driven by a `Closure` that maintains a block-rate accumulator, +/// wrapping 0→1 to loop the buffer continuously. The closure is lazily initialised on +/// the first RT block so it can read `sampleRate` and `blockSize` from the live engine. +final class PercTimeStretch: SynthesizerBase { + let buffer: LyrebirdBuffer + let stretchFactor: Double + + init(buffer: LyrebirdBuffer, stretchFactor: Double) { + self.buffer = buffer + self.stretchFactor = max(0.01, stretchFactor) + super.init() + } + + override func build() { + let nativeDuration = Double(buffer.count) / (buffer.sampleRate ?? 44100.0) + let sf = stretchFactor + + var posAccum: Double = 0.0 + var posIncPerBlock: Double = 0.0 + var posIncInitialized: Bool = false + + let posGen = Closure { graph, _ in + if !posIncInitialized { + let sr = Double(graph.engine.sampleRate) + let blockSize = Double(graph.engine.blockSize) + // Advance pos by this much each block to traverse 0→1 in (nativeDuration*sf) sec. + posIncPerBlock = blockSize / (sr * nativeDuration * sf) + posIncInitialized = true + } + let pos = posAccum + posAccum += posIncPerBlock + if posAccum >= 1.0 { posAccum -= 1.0 } + return pos + } + + let ts = TimeStretch.Audio( + buffer: buffer, + pos: posGen, + pitchRatio: 1.0, + windowSize: 0.11, + overlap: 6, + timeDispersion: 0.009, + grainDurationJitter: 0.05, + loop: true + ) + ts.amp = 0.8 + + // Perc.aiff is mono — ts[0] picks channel 0; Pan2 centers it. + output(bus: 0, source: Pan2(input: ts, mul: 1.0)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralPitchShift.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralPitchShift.swift new file mode 100644 index 0000000..1bb1fe1 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralPitchShift.swift @@ -0,0 +1,58 @@ +// PercSpectralPitchShift.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Phase-vocoder spectral pitch-shift demo — PlayBuffer → SpectralChain.Audio (with SpectralPitchShift). +/// +/// Signal chain: +/// 1. `PlayBuffer.Audio` reads Perc.aiff in a loop at native rate. +/// 2. `SpectralChain.Audio` bins the signal into polar (magnitude + phase) spectral +/// frames every `hopSize` samples, dispatches the registered `SpectralPitchShift` +/// processor, and resynthesises audio via overlap-add. +/// +/// The phase vocoder introduces latency of approximately `fftSize` samples (≈ 43 ms at 48 kHz +/// with fftSize = 2048). Transient sharpness is reduced compared to granular pitch shifting — +/// this sounds more "smeared" but with better tonal coherence on sustained sounds. +/// +/// Pitch ratios > 1.0 shift up; < 1.0 shift down. Range is (0, 4]. +final class PercSpectralPitchShift: SynthesizerBase { + let buffer: LyrebirdBuffer + let pitchRatio: Double + let engineSampleRate: Double + + init(buffer: LyrebirdBuffer, pitchRatio: Double = 1.5, engineSampleRate: Double) { + self.buffer = buffer + self.pitchRatio = pitchRatio + self.engineSampleRate = engineSampleRate + super.init() + } + + override func build() { + let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate) + let player = PlayBuffer.Audio( + buffer: buffer, + loop: true, + rate: rateScale + ) + + let fftSize = 2048 + let hopSize = 512 + + // SpectralPitchShift is a SpectralProcessor — runs inside SpectralChain.Audio each hop. + let shifter = SpectralPitchShift(fftSize: fftSize, hopSize: hopSize, pitchRatio: pitchRatio) + + // Single Generator owns the analysis + processor + IFFT pipeline. + let chain = SpectralChain.Audio( + input: player[0], + fftSize: fftSize, + hopSize: hopSize, + stages: [.mono(shifter)] + ) + + output(bus: 0, source: Pan2(input: chain, mul: 0.5)) + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralStereoDiffuse.swift b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralStereoDiffuse.swift new file mode 100644 index 0000000..7c20518 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/Synthesizers/Spectral/PercSpectralStereoDiffuse.swift @@ -0,0 +1,58 @@ +// PercSpectralStereoDiffuse.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// SpectralChain.Audio fan-out demo — mono PlayBuffer → SpectralChain.Audio +/// (with SpectralStereoDiffuse) → 2-channel decorrelated stereo output. +/// +/// Signal chain: +/// 1. `PlayBuffer.Audio` reads Perc.aiff in a loop at native rate. +/// 2. `SpectralChain.Audio` runs the forward FFT once, then dispatches +/// `SpectralStereoDiffuse` as a `SpectralFanOutProcessor` to write +/// two independent destination buffers (anti-correlated phase +/// randomisation per bin, magnitudes preserved). +/// 3. Two IFFT bank channels resynthesise to a 2-channel output. The +/// chain output is multi-row — wire `chain[0]` to bus 0, `chain[1]` +/// to bus 1. +/// +/// `amount = 0` is exact bypass (both channels match the input). +/// `amount = 1` is full per-channel randomisation — wide decorrelated stereo. +final class PercSpectralStereoDiffuse: SynthesizerBase { + let buffer: LyrebirdBuffer + let amount: Double + let engineSampleRate: Double + + init(buffer: LyrebirdBuffer, amount: Double = 0.8, engineSampleRate: Double) { + self.buffer = buffer + self.amount = amount + self.engineSampleRate = engineSampleRate + super.init() + } + + override func build() { + let rateScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate) + let player = PlayBuffer.Audio(buffer: buffer, loop: true, rate: rateScale) + + let fftSize = 2048 + let hopSize = 512 + + let diffuser = SpectralStereoDiffuse(amount: amount, seed: 0xDEADBEEF) + + // Fan-out path: SpectralChain.Audio runs forward FFT once, then + // populates two destination buffers via the fanOut processor, then + // runs two IFFTs to produce a 2-channel output. + let chain = SpectralChain.Audio( + input: player[0], + fftSize: fftSize, + hopSize: hopSize, + fanOut: diffuser, + mul: 0.5 + ) + + output(bus: 0, source: chain) // 2 channels out + } +} diff --git a/Demos/LyrebirdDemo/LyrebirdDemo/main.swift b/Demos/LyrebirdDemo/LyrebirdDemo/main.swift new file mode 100644 index 0000000..15ebb43 --- /dev/null +++ b/Demos/LyrebirdDemo/LyrebirdDemo/main.swift @@ -0,0 +1,27 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +let engine = SynthesisEngine( + blockSize: 512, + sampleRate: 48000, + numOutputChannels: 2, + numInputChannels: 2, + driver: CoreAudioDriver() +) + +do { + try engine.start() +} catch { + print("Engine failed to start: \(error)") + exit(1) +} + +BufferDemos(engine: engine).runDemo() +//ReverbDemo(engine: engine).runDemo() +engine.stop() diff --git a/Demos/LyrebirdDemo/Package.resolved b/Demos/LyrebirdDemo/Package.resolved new file mode 100644 index 0000000..94f71c1 --- /dev/null +++ b/Demos/LyrebirdDemo/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "6f06852651ad22a81b6dc75b6f4ee00fbaffb3782ac523486a02978ee45ac96b", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdDemo/Package.swift b/Demos/LyrebirdDemo/Package.swift new file mode 100644 index 0000000..f6196eb --- /dev/null +++ b/Demos/LyrebirdDemo/Package.swift @@ -0,0 +1,25 @@ +// Package.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "LyrebirdDemo", + platforms: [.macOS(.v15)], + dependencies: [ + .package(path: "../.."), + ], + targets: [ + .executableTarget( + name: "LyrebirdDemo", + dependencies: [ + .product(name: "Lyrebird", package: "LyrebirdII"), + ], + path: "LyrebirdDemo" + ), + ] +) diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4fa622a --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.pbxproj @@ -0,0 +1,389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + B9A00000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000007 /* main.swift */; }; + B9A00000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000008 /* AppDelegate.swift */; }; + B9A00000000000000000000E /* NoteController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000009 /* NoteController.swift */; }; + B9A00000000000000000000F /* SineToneUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000000A /* SineToneUI.swift */; }; + B9A000000000000000000010 /* SineToneView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000000B /* SineToneView.swift */; }; + B9A00000000000000000001F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = B9A00000000000000000001D /* LyrebirdUI */; }; + B9A000000000000000000030 /* SpectralBinDelayUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002D /* SpectralBinDelayUI.swift */; }; + B9A000000000000000000031 /* BinDelayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002E /* BinDelayController.swift */; }; + B9A000000000000000000032 /* BinDelayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A00000000000000000002F /* BinDelayView.swift */; }; + B9A000000000000000000036 /* VectorOscillatorUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000033 /* VectorOscillatorUI.swift */; }; + B9A000000000000000000037 /* VectorOscillatorController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000034 /* VectorOscillatorController.swift */; }; + B9A000000000000000000038 /* VectorOscillatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9A000000000000000000035 /* VectorOscillatorView.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + B9A000000000000000000004 /* LyrebirdMacOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdMacOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + B9A000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B9A000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + B9A000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + B9A000000000000000000009 /* NoteController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteController.swift; sourceTree = ""; }; + B9A00000000000000000000A /* SineToneUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneUI.swift; sourceTree = ""; }; + B9A00000000000000000000B /* SineToneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneView.swift; sourceTree = ""; }; + B9A00000000000000000002D /* SpectralBinDelayUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpectralBinDelayUI.swift; sourceTree = ""; }; + B9A00000000000000000002E /* BinDelayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayController.swift; sourceTree = ""; }; + B9A00000000000000000002F /* BinDelayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayView.swift; sourceTree = ""; }; + B9A000000000000000000033 /* VectorOscillatorUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorUI.swift; sourceTree = ""; }; + B9A000000000000000000034 /* VectorOscillatorController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorController.swift; sourceTree = ""; }; + B9A000000000000000000035 /* VectorOscillatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorView.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + B9A000000000000000000012 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B9A00000000000000000001F /* LyrebirdUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + B9A000000000000000000002 = { + isa = PBXGroup; + children = ( + B9A000000000000000000005 /* LyrebirdMacOSDemo */, + B9A000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + B9A000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + B9A000000000000000000004 /* LyrebirdMacOSDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + B9A000000000000000000005 /* LyrebirdMacOSDemo */ = { + isa = PBXGroup; + children = ( + B9A000000000000000000007 /* main.swift */, + B9A000000000000000000008 /* AppDelegate.swift */, + B9A000000000000000000020 /* UI */, + B9A000000000000000000021 /* Synthesizers */, + B9A000000000000000000006 /* Info.plist */, + ); + path = LyrebirdMacOSDemo; + sourceTree = ""; + }; + B9A000000000000000000020 /* UI */ = { + isa = PBXGroup; + children = ( + B9A000000000000000000009 /* NoteController.swift */, + B9A00000000000000000000B /* SineToneView.swift */, + B9A00000000000000000002E /* BinDelayController.swift */, + B9A00000000000000000002F /* BinDelayView.swift */, + B9A000000000000000000034 /* VectorOscillatorController.swift */, + B9A000000000000000000035 /* VectorOscillatorView.swift */, + ); + path = UI; + sourceTree = ""; + }; + B9A000000000000000000021 /* Synthesizers */ = { + isa = PBXGroup; + children = ( + B9A00000000000000000000A /* SineToneUI.swift */, + B9A00000000000000000002D /* SpectralBinDelayUI.swift */, + B9A000000000000000000033 /* VectorOscillatorUI.swift */, + ); + path = Synthesizers; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + B9A000000000000000000014 /* LyrebirdMacOSDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = B9A000000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdMacOSDemo" */; + buildPhases = ( + B9A000000000000000000011 /* Sources */, + B9A000000000000000000012 /* Frameworks */, + B9A000000000000000000013 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdMacOSDemo; + packageProductDependencies = ( + B9A00000000000000000001D /* LyrebirdUI */, + ); + productName = LyrebirdMacOSDemo; + productReference = B9A000000000000000000004 /* LyrebirdMacOSDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + B9A000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + B9A000000000000000000014 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = B9A000000000000000000018 /* Build configuration list for PBXProject "LyrebirdMacOSDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = B9A000000000000000000002; + packageReferences = ( + B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */, + ); + productRefGroup = B9A000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + B9A000000000000000000014 /* LyrebirdMacOSDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + B9A000000000000000000013 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + B9A000000000000000000011 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B9A00000000000000000000C /* main.swift in Sources */, + B9A00000000000000000000D /* AppDelegate.swift in Sources */, + B9A00000000000000000000E /* NoteController.swift in Sources */, + B9A00000000000000000000F /* SineToneUI.swift in Sources */, + B9A000000000000000000010 /* SineToneView.swift in Sources */, + B9A000000000000000000030 /* SpectralBinDelayUI.swift in Sources */, + B9A000000000000000000031 /* BinDelayController.swift in Sources */, + B9A000000000000000000032 /* BinDelayView.swift in Sources */, + B9A000000000000000000036 /* VectorOscillatorUI.swift in Sources */, + B9A000000000000000000037 /* VectorOscillatorController.swift in Sources */, + B9A000000000000000000038 /* VectorOscillatorView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + B9A000000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdMacOSDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdMacOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + B9A000000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdMacOSDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdMacOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + B9A000000000000000000019 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + B9A00000000000000000001A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + B9A000000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdMacOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B9A000000000000000000016 /* Debug */, + B9A000000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B9A000000000000000000018 /* Build configuration list for PBXProject "LyrebirdMacOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B9A000000000000000000019 /* Debug */, + B9A00000000000000000001A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + B9A00000000000000000001D /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = B9A00000000000000000001B /* XCLocalSwiftPackageReference "../.." */; + productName = LyrebirdUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = B9A000000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..d4338f9 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "2f86be2113a80b402938cb09ebb72fe8cb9830066fe5b03aa1d174fcf50e2574", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdMacOSDemo.xcscheme b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdMacOSDemo.xcscheme new file mode 100644 index 0000000..88e4d3b --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdMacOSDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift new file mode 100644 index 0000000..2537f49 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/AppDelegate.swift @@ -0,0 +1,77 @@ +// AppDelegate.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AppKit +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +// ── Demo selector ───────────────────────────────────────────────────────────── +// Change `demo` to `.sineTone` or `.binDelay` to switch demos. +private enum Demo { case vector, binDelay, sineTone } +private let demo: Demo = .binDelay +// ────────────────────────────────────────────────────────────────────────────── + +final class AppDelegate: NSObject, NSApplicationDelegate { + + let engine: SynthesisEngine + // Vector oscillator demo controller (used when demo == .vector) + let vectorController: VectorOscillatorController + // Sine-tone demo controller (used when demo == .sineTone) + let sineController: NoteController + // Bin-delay demo controller (used when demo == .binDelay) + let binDelayController: BinDelayController + var window: LyrebirdWindow? + + init(engine: SynthesisEngine) { + let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048) + engine.scopeTap = scopeCapture + self.engine = engine + self.vectorController = VectorOscillatorController( + engine: engine, + synth: VectorOscillatorUI(), + scopeCapture: scopeCapture + ) + self.sineController = NoteController( + engine: engine, + synth: SineToneUI(), + scopeCapture: scopeCapture + ) + self.binDelayController = BinDelayController( + engine: engine, + scopeCapture: scopeCapture + ) + } + + @MainActor + func applicationDidFinishLaunching(_ notification: Notification) { + switch demo { + case .vector: + window = LyrebirdWindow(title: "Lyrebird — Vector Oscillator", width: 380, height: 580) + window?.open { + VectorOscillatorView(controller: self.vectorController) + } + case .binDelay: + window = LyrebirdWindow(title: "Lyrebird — Spectral Bin Delay", width: 440, height: 620) + window?.open { + BinDelayView(controller: self.binDelayController) + } + case .sineTone: + window = LyrebirdWindow(title: "Lyrebird — Sine Tone", width: 360, height: 540) + window?.open { + SineToneView(controller: self.sineController) + } + } + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + true + } + + func applicationWillTerminate(_ notification: Notification) { + engine.stop() + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Info.plist b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Info.plist new file mode 100644 index 0000000..433e3a0 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSPrincipalClass + NSApplication + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + + diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SineToneUI.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SineToneUI.swift new file mode 100644 index 0000000..912b857 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SineToneUI.swift @@ -0,0 +1,26 @@ +// SineToneUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable from the UI. +final class SineToneUI: SynthesizerBase { + + /// Frequency in Hz. Slider range: 440–880 Hz. + @UIParam var frequency: Double = 440.0 + + /// Output amplitude (linear gain). Knob range: 0–1. + @UIParam var amplitude: Double = 0.25 + + /// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right). + @UIParam var pan: Double = 0.0 + + override func build() { + let osc = OscSin.Audio(freq: $frequency) + output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan)) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SpectralBinDelayUI.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SpectralBinDelayUI.swift new file mode 100644 index 0000000..8205af9 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/SpectralBinDelayUI.swift @@ -0,0 +1,108 @@ +// SpectralBinDelayUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Spectral-bin-delay synthesizer demo. +/// +/// An `Impulse.Audio` at 0.2 Hz (one fire per 5 s) drives an FFT analysis chain +/// that includes a `SpectralBinDelay`. The delayed spectral frames are resynthesised +/// via `IFFTSynthesis` and panned to centre stereo on bus 0. +/// +/// Two `LyrebirdBuffer`s — `delayTimes` and `feedbacks` — are exposed as public +/// stored properties so the UI can write into them live via `MultiSlider`. +/// Both buffers are pre-allocated at `init` and never reallocated. +/// +/// - Note: `sampleRate` must be passed at construction time because +/// `SpectralBinDelay` needs it to convert delay-seconds → hop-frames. +/// Create this synthesizer *after* the engine has started so that +/// `engine.sampleRate` reflects the committed hardware rate. +final class SpectralBinDelayUI: SynthesizerBase { + + // MARK: - Constants + + /// FFT frame size used throughout the analysis/synthesis chain. + static let fftSize: Int = 1024 + + /// Number of new samples between FFT hops (75 % overlap). + static let hopSize: Int = 256 + + /// `fftSize / 2` — the number of independent magnitude/phase bins. + static let halfSize: Int = fftSize / 2 + + /// Maximum delay time accepted by `SpectralBinDelay` (seconds). + /// Keep below `lyrebirdSpectralBinDelayMaxFrames * hopSize / sampleRate`. + static let maxDelaySeconds: Double = 1.0 + + // MARK: - Engine sample rate (captured at init — needed in build()) + + /// Audio sample rate in Hz. Captured from the engine before `build()` runs. + private let engineSampleRate: Double + + // MARK: - Parameter buffers (public — UI writes via MultiSlider) + + /// Per-bin delay times in seconds. Mono, `halfSize` frames. + /// Default: 0 (clean pass-through until the UI writes new values). + let delayTimes: LyrebirdBuffer + + /// Per-bin feedback gains in [0, 0.95). Mono, `halfSize` frames. + /// Default: 0 (clean pass-through until the UI writes new values). + let feedbacks: LyrebirdBuffer + + // MARK: - Initialisation + + /// - Parameter sampleRate: The engine's committed sample rate (Hz). + /// `SynthesisEngine.sampleRate` is a `let` initialised in `init`, so it + /// is valid as soon as the engine is constructed. + init(sampleRate: Double) { + let halfSize = SpectralBinDelayUI.halfSize + + self.engineSampleRate = sampleRate + + let dt = LyrebirdBuffer(count: halfSize) + dt.fill(with: 0.0) + + let fb = LyrebirdBuffer(count: halfSize) + fb.fill(with: 0.0) + + self.delayTimes = dt + self.feedbacks = fb + + super.init() + } + + // MARK: - Signal graph + + override func build() { + let fftSize = SpectralBinDelayUI.fftSize + let hopSize = SpectralBinDelayUI.hopSize + + // Source: sparse impulse that fires at 0.2 Hz (once every 5 s). + let impulseFreq = 0.2 + let impulse = Impulse.Audio(freq: impulseFreq) + + // SpectralBinDelay processor — allocated here inside build() which + // runs off the RT thread before the synthesizer is added to the engine. + let bd = SpectralBinDelay( + fftSize: fftSize, + hopSize: hopSize, + maxDelaySeconds: SpectralBinDelayUI.maxDelaySeconds, + sampleRate: engineSampleRate, + delayTimes: delayTimes, + feedbacks: feedbacks + ) + + let binDelay = SpectralChain.Audio( + input: impulse, + fftSize: fftSize, + hopSize: hopSize, + stages: [.mono(bd)] + ) + + // Pan to centre; the effect is mono but we send it to stereo bus 0. + output(bus: 0, source: Pan2(input: binDelay, pan: 0.0)) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/VectorOscillatorUI.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/VectorOscillatorUI.swift new file mode 100644 index 0000000..a3c0ef9 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/Synthesizers/VectorOscillatorUI.swift @@ -0,0 +1,78 @@ +// VectorOscillatorUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A stereo vector oscillator whose XY position, frequency, and amplitude are +/// live-controllable from the UI. +/// +/// Four corner wavetables are crossfaded on a 2D XY plane: +/// +/// C (triangle) ── D (Hanning) (y = 1) +/// │ │ +/// A (sine) ──── B (saw-ish) (y = 0) +/// x=0 x=1 +/// +/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix. +final class VectorOscillatorUI: SynthesizerBase { + + /// X-axis blend position. 0 = corner A/C, 1 = corner B/D. + /// Normalized [0, 1]. XY pad range: 0…1. + @UIParam var x: Double = 0.5 + + /// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D). + /// Normalized [0, 1]. XY pad range: 0…1. + @UIParam var y: Double = 0.5 + + /// Oscillator frequency in Hz. Slider range: 40–2000 Hz. + @UIParam var frequency: Double = 220.0 + + /// Output amplitude (linear gain). Knob range: 0–1. + @UIParam var amplitude: Double = 0.25 + + private let bufferA: LyrebirdBuffer // corner A: sine + private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish + private let bufferC: LyrebirdBuffer // corner C: triangle + private let bufferD: LyrebirdBuffer // corner D: Hanning window shape + + override init() { + let tableSize = lyrebirdDefaultTableSize + + let a = LyrebirdBuffer(count: tableSize) + a.fillSine() + + let b = LyrebirdBuffer(count: tableSize) + b.fill(partials: 16) + + let c = LyrebirdBuffer(count: tableSize) + c.fillTriangle() + + let d = LyrebirdBuffer(count: tableSize) + d.fillHanning() + + self.bufferA = a + self.bufferB = b + self.bufferC = c + self.bufferD = d + + super.init() + } + + override func build() { + let osc = VectorOscillator.Audio( + bufferA: bufferA, + bufferB: bufferB, + bufferC: bufferC, + bufferD: bufferD, + freq: $frequency, + x: $x, + y: $y, + mul: $amplitude + ) + output(bus: 0, source: Pan2(input: osc, pan: 0.0)) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift new file mode 100644 index 0000000..146665d --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayController.swift @@ -0,0 +1,74 @@ +// BinDelayController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +/// Controller for the spectral-bin-delay demo view. +/// +/// Unlike `NoteController`, the synthesizer is created lazily when the user +/// first taps "Start Synthesizer" — this is necessary because +/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed +/// sample rate, which is only valid after `engine.start()` returns. +@Observable +final class BinDelayController { + + let engine: SynthesisEngine + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + /// The live synthesizer instance. `nil` until first "Start Synthesizer" tap. + private(set) var synth: SpectralBinDelayUI? + + init(engine: SynthesisEngine, scopeCapture: ScopeCapture) { + self.engine = engine + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying, let s = synth { + engine.remove(s) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + if let s = synth { + engine.remove(s) + } + isPlaying = false + } else { + guard engineRunning else { return } + // Create the synthesizer lazily so we don't put it in the node tree + // until the user requests it. + if synth == nil { + synth = SpectralBinDelayUI(sampleRate: engine.sampleRate) + } + if let s = synth { + do { + try engine.add(s) + isPlaying = true + } catch { + print("[Lyrebird] BinDelayController.toggle add failed: \(error)") + } + } + } + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayView.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayView.swift new file mode 100644 index 0000000..ed6a994 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/BinDelayView.swift @@ -0,0 +1,123 @@ +// BinDelayView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +/// Main view for the spectral bin-delay demo (macOS). +/// +/// Shows engine and synth toggle buttons, two `MultiSlider` rows for +/// per-bin delay times and feedbacks, an engine status strip, and a scope. +/// +/// Every spectral bin is exposed: each `MultiSlider` row contains +/// `SpectralBinDelayUI.halfSize` (512) thin bars, one per FFT bin. The window +/// is sized wide so the full spectrum is visible at once — the demo's purpose +/// is to show that per-bin spectral control is possible, not to make any one +/// bin precisely tweakable. +struct BinDelayView: View { + + let controller: BinDelayController + + private let sliderHeight: CGFloat = 160 + private let maxFeedback = 0.95 + + var body: some View { + VStack(alignment: .leading, spacing: 20) { + + // MARK: Engine row + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + // MARK: Synth row + HStack { + VStack(alignment: .leading, spacing: 2) { + Text("Spectral Bin Delay") + .font(.headline) + Text("Impulse source · 0.2 Hz · fftSize 1024 · hop 256") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + Divider() + + // MARK: Delay times slider + Text("Delay Times (all 512 bins, range 0–1 s)") + .font(.caption) + .foregroundStyle(.secondary) + + if let synth = controller.synth { + MultiSlider( + buffer: synth.delayTimes, + count: SpectralBinDelayUI.halfSize, + range: 0.0...1.0, + height: sliderHeight + ) + } else { + placeholderSlider(label: "Start synthesizer to enable") + } + + // MARK: Feedback slider + Text("Feedbacks (all 512 bins, range 0–0.95)") + .font(.caption) + .foregroundStyle(.secondary) + + if let synth = controller.synth { + MultiSlider( + buffer: synth.feedbacks, + count: SpectralBinDelayUI.halfSize, + range: 0.0...maxFeedback, + height: sliderHeight + ) + } else { + placeholderSlider(label: "Start synthesizer to enable") + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + } + .padding(20) + .frame(minWidth: 1100) + } + + // MARK: - Helpers + + @ViewBuilder + private func placeholderSlider(label: String) -> some View { + ZStack { + Color.lyrebirdControlBackground + Text(label) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(height: sliderHeight) + .overlay(Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1)) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift new file mode 100644 index 0000000..641a6d6 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/NoteController.swift @@ -0,0 +1,57 @@ +// NoteController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +@Observable +final class NoteController { + + let engine: SynthesisEngine + let synth: SineToneUI + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + init(engine: SynthesisEngine, synth: SineToneUI, scopeCapture: ScopeCapture) { + self.engine = engine + self.synth = synth + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying { + engine.remove(synth) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + engine.remove(synth) + isPlaying = false + } else { + do { + try engine.add(synth) + isPlaying = true + } catch { + print("[Lyrebird] NoteController.toggle add failed: \(error)") + } + } + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/SineToneView.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/SineToneView.swift new file mode 100644 index 0000000..794a89f --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/SineToneView.swift @@ -0,0 +1,111 @@ +// SineToneView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +struct SineToneView: View { + + let controller: NoteController + + var body: some View { + VStack(alignment: .leading, spacing: 20) { + + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + HStack { + Text("Sine Tone") + .font(.headline) + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + ParameterSlider( + "Frequency", + node: controller.synth.$frequency, + range: 440.0...880.0 + ) + + HStack(spacing: 24) { + ParameterKnob( + "Amplitude", + node: controller.synth.$amplitude, + range: 0.0...1.0 + ) + ParameterKnob( + "Pan", + node: controller.synth.$pan, + range: -1.0...1.0 + ) + ParameterLabel("Level", node: controller.synth.$amplitude) + Spacer() + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + + Divider() + + Text("Envelope") + .font(.caption) + .foregroundStyle(.secondary) + + LyrebirdEnvelopeView( + Envelope( + levels: [0.0001, 1, 0.6, 0.4, 0.0001], + durations: [0.05, 0.15, 0.4, 0.3], + curves: [.exponential, .exponential, .lin, .exponential], + loopNode: 2, + releaseNode: 4 + ), + width: 300, + height: 100 + ) + + Divider() + + Text("Distribution Preview (Gaussian, 200 samples)") + .font(.caption) + .foregroundStyle(.secondary) + + LyrebirdScatterView( + DemandTemporalTendency(distribution: .gauss, + parX: .value(0.5), parY: .value(0.15), + seed: 42) + .samples(count: 200), + yRange: 0.0...1.0, + pointColor: .cyan, + width: 300, + height: 100 + ) + } + .padding(20) + .frame(minWidth: 340) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift new file mode 100644 index 0000000..a2de487 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorController.swift @@ -0,0 +1,61 @@ +// VectorOscillatorController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +@Observable +final class VectorOscillatorController { + + let engine: SynthesisEngine + let synth: VectorOscillatorUI + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + init( + engine: SynthesisEngine, + synth: VectorOscillatorUI, + scopeCapture: ScopeCapture + ) { + self.engine = engine + self.synth = synth + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying { + engine.remove(synth) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + engine.remove(synth) + isPlaying = false + } else { + do { + try engine.add(synth) + isPlaying = true + } catch { + print("[Lyrebird] VectorOscillatorController.toggle add failed: \(error)") + } + } + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorView.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorView.swift new file mode 100644 index 0000000..985ca99 --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/UI/VectorOscillatorView.swift @@ -0,0 +1,79 @@ +// VectorOscillatorView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +struct VectorOscillatorView: View { + + let controller: VectorOscillatorController + + var body: some View { + VStack(alignment: .leading, spacing: 20) { + + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + HStack { + Text("Vector Oscillator") + .font(.headline) + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + ParameterXY( + xLabel: "X (A↔B)", + xNode: controller.synth.$x, + xRange: 0.0...1.0, + yLabel: "Y (AB↔CD)", + yNode: controller.synth.$y, + yRange: 0.0...1.0 + ) + .frame(width: 240, height: 240) + + HStack(spacing: 24) { + ParameterKnob( + "Frequency", + node: controller.synth.$frequency, + range: 40.0...2000.0 + ) + ParameterKnob( + "Amplitude", + node: controller.synth.$amplitude, + range: 0.0...1.0 + ) + Spacer() + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + } + .padding(20) + .frame(minWidth: 340) + } +} diff --git a/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift new file mode 100644 index 0000000..1b62a2a --- /dev/null +++ b/Demos/LyrebirdMacOSDemo/LyrebirdMacOSDemo/main.swift @@ -0,0 +1,22 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AppKit +import LyrebirdSynth + +let engine = SynthesisEngine( + blockSize: 512, + sampleRate: 48000, + numOutputChannels: 2, + numInputChannels: 0, + driver: CoreAudioDriver() +) + +let delegate = AppDelegate(engine: engine) +let app = NSApplication.shared +app.setActivationPolicy(.regular) +app.delegate = delegate +app.run() diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..41f4375 --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/project.pbxproj @@ -0,0 +1,328 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + E3C000000000000000000007 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000006 /* main.swift */; }; + E3C000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = E3C000000000000000000012 /* Lyrebird */; }; + E3C000000000000000000015 /* FMTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = E3C000000000000000000014 /* FMTone.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + E3C000000000000000000004 /* LyrebirdNRTDemo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = LyrebirdNRTDemo; sourceTree = BUILT_PRODUCTS_DIR; }; + E3C000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + E3C000000000000000000014 /* FMTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FMTone.swift; sourceTree = ""; }; + E3C000000000000000000017 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E3C000000000000000000018 /* LyrebirdNRTDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdNRTDemo.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + E3C000000000000000000009 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E3C000000000000000000013 /* Lyrebird in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + E3C000000000000000000002 = { + isa = PBXGroup; + children = ( + E3C000000000000000000005 /* LyrebirdNRTDemo */, + E3C000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + E3C000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + E3C000000000000000000004 /* LyrebirdNRTDemo */, + ); + name = Products; + sourceTree = ""; + }; + E3C000000000000000000005 /* LyrebirdNRTDemo */ = { + isa = PBXGroup; + children = ( + E3C000000000000000000006 /* main.swift */, + E3C000000000000000000016 /* Synthesizers */, + E3C000000000000000000017 /* Info.plist */, + E3C000000000000000000018 /* LyrebirdNRTDemo.entitlements */, + ); + path = LyrebirdNRTDemo; + sourceTree = ""; + }; + E3C000000000000000000016 /* Synthesizers */ = { + isa = PBXGroup; + children = ( + E3C000000000000000000014 /* FMTone.swift */, + ); + path = Synthesizers; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + E3C00000000000000000000A /* LyrebirdNRTDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdNRTDemo" */; + buildPhases = ( + E3C000000000000000000008 /* Sources */, + E3C000000000000000000009 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdNRTDemo; + packageProductDependencies = ( + E3C000000000000000000012 /* Lyrebird */, + ); + productName = LyrebirdNRTDemo; + productReference = E3C000000000000000000004 /* LyrebirdNRTDemo */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + E3C000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + E3C00000000000000000000A = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdNRTDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = E3C000000000000000000002; + packageReferences = ( + E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */, + ); + productRefGroup = E3C000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + E3C00000000000000000000A /* LyrebirdNRTDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + E3C000000000000000000008 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E3C000000000000000000007 /* main.swift in Sources */, + E3C000000000000000000015 /* FMTone.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + E3C00000000000000000000C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements; + CODE_SIGN_IDENTITY = "-"; + CODE_SIGN_STYLE = Manual; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdNRTDemo/Info.plist; + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdNRTDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + }; + name = Debug; + }; + E3C00000000000000000000D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements; + CODE_SIGN_IDENTITY = "-"; + CODE_SIGN_STYLE = Manual; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdNRTDemo/Info.plist; + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdNRTDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + }; + name = Release; + }; + E3C00000000000000000000F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + E3C000000000000000000010 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + E3C00000000000000000000B /* Build configuration list for PBXNativeTarget "LyrebirdNRTDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E3C00000000000000000000C /* Debug */, + E3C00000000000000000000D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E3C00000000000000000000E /* Build configuration list for PBXProject "LyrebirdNRTDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E3C00000000000000000000F /* Debug */, + E3C000000000000000000010 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + E3C000000000000000000012 /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = E3C000000000000000000011 /* XCLocalSwiftPackageReference "../.." */; + productName = Lyrebird; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = E3C000000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdNRTDemo.xcscheme b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdNRTDemo.xcscheme new file mode 100644 index 0000000..c3b19d4 --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdNRTDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Info.plist b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Info.plist new file mode 100644 index 0000000..cbcb6bb --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Info.plist @@ -0,0 +1,14 @@ + + + + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleVersion + 1 + NSDesktopFolderUsageDescription + LyrebirdNRTDemo writes rendered audio files to the Desktop. + NSDocumentsFolderUsageDescription + LyrebirdNRTDemo writes rendered audio files to Documents. + + diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements new file mode 100644 index 0000000..80fbf9c --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/LyrebirdNRTDemo.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + + diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Synthesizers/FMTone.swift b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Synthesizers/FMTone.swift new file mode 100644 index 0000000..59f6b1f --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/Synthesizers/FMTone.swift @@ -0,0 +1,50 @@ +// FMTone.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// FM tone with an ASR envelope and stereo panning. +/// +/// A sine modulator at `modFreq` drives the carrier frequency, producing +/// classic FM timbre. The `pan` argument places the voice in the stereo field +/// (-1 = hard left, 0 = centre, 1 = hard right). +final class FMTone: SynthesizerBase { + let carrierFreq: Double + let modFreq: Double + let modIndex: Double + let amp: Double + let pan: Double + let envelope: Envelope + + init(carrierFreq: Double, + modFreq: Double = 220.0, + modIndex: Double = 3.0, + amp: Double = 0.18, + pan: Double = 0.0, + envelope: Envelope = Envelope( + levels: [0, 1, 0.7, 0], + durations: [0.02, 1.5, 0.5], + curves: [2, 0, -3.5] + ) + ) { + self.carrierFreq = carrierFreq + self.modFreq = modFreq + self.modIndex = modIndex + self.amp = amp + self.pan = pan + self.envelope = envelope + super.init() + } + + override func build() { + let env = EnvelopeGen.Control( + envelope: envelope + ) + let mod = OscSin.Audio(freq: modFreq) * (carrierFreq * modIndex) + let sig = OscSin.Audio(freq: carrierFreq + mod) * env * amp + output(bus: 0, source: Pan2(input: sig, pan: pan)) + } +} diff --git a/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/main.swift b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/main.swift new file mode 100644 index 0000000..c100ded --- /dev/null +++ b/Demos/LyrebirdNRTDemo/LyrebirdNRTDemo/main.swift @@ -0,0 +1,93 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +// Output to the Desktop — triggers the NSDesktopFolderUsageDescription TCC prompt on first run. +let outputURL = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Desktop/nrt_output.caf") + +// Render parameters. +let sampleRate: Double = 48000 +let blockSize: Int = 512 +let attackTime: Double = 0.02 +let sustainTime: Double = 1.5 +let releaseTime: Double = 0.5 +let voiceLength: Double = attackTime + sustainTime + releaseTime + +// Six FM voices — carrier frequencies, mod ratios, panning positions, start times. +struct VoiceSpec { + var carrier: Double + var modFreq: Double + var pan: Double + var start: Double +} + +let voices: [VoiceSpec] = [ + VoiceSpec(carrier: 110.0, modFreq: 55.0, pan: -0.6, start: 0.0), + VoiceSpec(carrier: 220.0, modFreq: 110.0, pan: 0.4, start: 0.25), + VoiceSpec(carrier: 330.0, modFreq: 220.0, pan: -0.2, start: 0.5), + VoiceSpec(carrier: 440.0, modFreq: 330.0, pan: 0.6, start: 0.75), + VoiceSpec(carrier: 550.0, modFreq: 110.0, pan: -0.8, start: 1.0), + VoiceSpec(carrier: 660.0, modFreq: 440.0, pan: 0.2, start: 1.25), +] + +let sustainLevel: Double = 1.0 / 2.0.squareRoot() // -3 dBFS (1/√2 ≈ sustainLevel) +let interSetDelay: Double = 1.0 +let tailDuration: Double = 0.1 + +let lastStart = voices.map(\.start).max() ?? 0.0 +let totalDur = lastStart + interSetDelay + voiceLength + tailDuration + +let driver = NRTDriver(outputURL: outputURL, duration: totalDur) +let engine = SynthesisEngine( + blockSize: blockSize, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + driver: driver +) + +do { + for v in voices { + try engine.schedule( + FMTone(carrierFreq: v.carrier, modFreq: v.modFreq, pan: v.pan, + envelope: Envelope( + levels: [0.0, 1.0, sustainLevel, 0.0], + durations: [attackTime, sustainTime, releaseTime], + curves: [4.0, -4.0, -10.0]) + ), + after: v.start + ) + } + + for v in voices { + try engine.schedule( + FMTone(carrierFreq: v.carrier * 1.2, modFreq: v.modFreq, pan: v.pan, + envelope: Envelope( + levels: [0.0, 1.0, sustainLevel, 0.0], + durations: [attackTime, sustainTime, releaseTime], + curves: [4.0, -4.0, -10.0]) + ), + after: v.start + interSetDelay + ) + } +} catch { + fputs("engine.schedule failed: \(error)\n", stderr) + exit(1) +} + +print("Rendering \(String(format: "%.2f", totalDur)) s → \(outputURL.path)") + +do { + try engine.start() + print("Done.") +} catch { + fputs("Render failed: \(error)\n", stderr) + exit(1) +} + diff --git a/Demos/LyrebirdNRTDemo/Package.resolved b/Demos/LyrebirdNRTDemo/Package.resolved new file mode 100644 index 0000000..7f92c5f --- /dev/null +++ b/Demos/LyrebirdNRTDemo/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "53d0f0966ba1616e4ff8eec85e7a64bec7b25b8f9158e10a7813f0cc29c5b538", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdNRTDemo/Package.swift b/Demos/LyrebirdNRTDemo/Package.swift new file mode 100644 index 0000000..8ea9550 --- /dev/null +++ b/Demos/LyrebirdNRTDemo/Package.swift @@ -0,0 +1,25 @@ +// Package.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "LyrebirdNRTDemo", + platforms: [.macOS(.v15)], + dependencies: [ + .package(path: "../.."), + ], + targets: [ + .executableTarget( + name: "LyrebirdNRTDemo", + dependencies: [ + .product(name: "Lyrebird", package: "LyrebirdII"), + ], + path: "LyrebirdNRTDemo" + ), + ] +) diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3387d8d --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/project.pbxproj @@ -0,0 +1,362 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + C8D0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000007 /* main.swift */; }; + C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; }; + C8D0000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdUI */; }; + C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001F /* LyrebirdLiveCompile */; }; + C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C8D00000000000000000012 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C8D0000000000000000000F /* LyrebirdUI in Frameworks */, + C8D00000000000000000021 /* LyrebirdLiveCompile in Frameworks */, + C8D00000000000000000022 /* LyrebirdLiveCompileUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C8D00000000000000000002 = { + isa = PBXGroup; + children = ( + C8D00000000000000000005 /* LyrebirdScratchDemo */, + C8D00000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C8D00000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C8D00000000000000000004 /* LyrebirdScratchDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + C8D00000000000000000005 /* LyrebirdScratchDemo */ = { + isa = PBXGroup; + children = ( + C8D00000000000000000007 /* main.swift */, + C8D00000000000000000008 /* AppDelegate.swift */, + C8D00000000000000000006 /* Info.plist */, + C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */, + ); + path = LyrebirdScratchDemo; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C8D00000000000000000014 /* LyrebirdScratchDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */; + buildPhases = ( + C8D00000000000000000011 /* Sources */, + C8D00000000000000000012 /* Frameworks */, + C8D00000000000000000013 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdScratchDemo; + packageProductDependencies = ( + C8D0000000000000000001D /* LyrebirdUI */, + C8D0000000000000000001F /* LyrebirdLiveCompile */, + C8D00000000000000000020 /* LyrebirdLiveCompileUI */, + ); + productName = LyrebirdScratchDemo; + productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C8D00000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C8D00000000000000000014 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C8D00000000000000000002; + packageReferences = ( + C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */, + C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */, + ); + productRefGroup = C8D00000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C8D00000000000000000014 /* LyrebirdScratchDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C8D00000000000000000013 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C8D00000000000000000011 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C8D0000000000000000000C /* main.swift in Sources */, + C8D0000000000000000000D /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C8D00000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + C8D00000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + C8D00000000000000000019 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C8D0000000000000000001A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C8D00000000000000000016 /* Debug */, + C8D00000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C8D00000000000000000019 /* Debug */, + C8D0000000000000000001A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; + C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../../LiveCompile; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C8D0000000000000000001D /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = C8D0000000000000000001B /* XCLocalSwiftPackageReference "../.." */; + productName = LyrebirdUI; + }; + C8D0000000000000000001F /* LyrebirdLiveCompile */ = { + isa = XCSwiftPackageProductDependency; + package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */; + productName = LyrebirdLiveCompile; + }; + C8D00000000000000000020 /* LyrebirdLiveCompileUI */ = { + isa = XCSwiftPackageProductDependency; + package = C8D0000000000000000001E /* XCLocalSwiftPackageReference "../../LiveCompile" */; + productName = LyrebirdLiveCompileUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C8D00000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScratchDemo.xcscheme b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScratchDemo.xcscheme new file mode 100644 index 0000000..b141ff8 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdScratchDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift new file mode 100644 index 0000000..3b4a976 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift @@ -0,0 +1,59 @@ +// AppDelegate.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AppKit +import SwiftUI +import LyrebirdSynth +import LyrebirdUI +import LyrebirdLiveCompile +import LyrebirdLiveCompileUI + +final class AppDelegate: NSObject, NSApplicationDelegate { + + let engine: SynthesisEngine + let session: LiveSession + var model: LyrebirdScratchModel? + var menuController: LyrebirdScratchMenuController? + var window: LyrebirdWindow? + + init(engine: SynthesisEngine) { + self.engine = engine + self.session = LiveSession(engine: engine) + } + + @MainActor + func applicationDidFinishLaunching(_ notification: Notification) { + do { + try engine.start() + } catch { + print("[LyrebirdScratchDemo] Engine failed to start: \(error)") + } + + let model = LyrebirdScratchModel(session: session) + self.model = model + let menuController = LyrebirdScratchMenuController(model: model) + menuController.installMainMenu() + self.menuController = menuController + + window = LyrebirdWindow( + title: "Lyrebird — Live Scratch", + width: 720, + height: 560 + ) + window?.open { + LyrebirdScratchView(model: model) + } + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + true + } + + func applicationWillTerminate(_ notification: Notification) { + engine.stop() + session.clearTracked() + } +} diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/Info.plist b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/Info.plist new file mode 100644 index 0000000..433e3a0 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSPrincipalClass + NSApplication + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + + diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements new file mode 100644 index 0000000..a1e8b01 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements @@ -0,0 +1,45 @@ + + + + + + + + com.apple.security.cs.disable-library-validation + + + diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift new file mode 100644 index 0000000..d7ee605 --- /dev/null +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/main.swift @@ -0,0 +1,23 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AppKit +import LyrebirdSynth +import LyrebirdLiveCompile + +let engine = SynthesisEngine( + blockSize: 512, + sampleRate: 48000, + numOutputChannels: 2, + numInputChannels: 0, + driver: CoreAudioDriver() +) + +let delegate = AppDelegate(engine: engine) +let app = NSApplication.shared +app.setActivationPolicy(.regular) +app.delegate = delegate +app.run() diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.pbxproj b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7dfe01d --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.pbxproj @@ -0,0 +1,389 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + B9C00000000000000000000B /* LyrebirdiOSDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */; }; + B9C00000000000000000000C /* NoteController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000008 /* NoteController.swift */; }; + B9C00000000000000000000D /* SineToneUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000009 /* SineToneUI.swift */; }; + B9C00000000000000000000E /* SineToneView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C00000000000000000000A /* SineToneView.swift */; }; + B9C00000000000000000000F /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = B9C00000000000000000001C /* LyrebirdUI */; }; + B9C000000000000000000020 /* SpectralBinDelayUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C00000000000000000001F /* SpectralBinDelayUI.swift */; }; + B9C000000000000000000022 /* BinDelayController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000021 /* BinDelayController.swift */; }; + B9C000000000000000000024 /* BinDelayView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000023 /* BinDelayView.swift */; }; + B9C000000000000000000028 /* VectorOscillatorUI.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000025 /* VectorOscillatorUI.swift */; }; + B9C000000000000000000029 /* VectorOscillatorController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000026 /* VectorOscillatorController.swift */; }; + B9C00000000000000000002A /* VectorOscillatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9C000000000000000000027 /* VectorOscillatorView.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + B9C000000000000000000004 /* LyrebirdiOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdiOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + B9C000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LyrebirdiOSDemoApp.swift; sourceTree = ""; }; + B9C000000000000000000008 /* NoteController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteController.swift; sourceTree = ""; }; + B9C000000000000000000009 /* SineToneUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneUI.swift; sourceTree = ""; }; + B9C00000000000000000000A /* SineToneView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineToneView.swift; sourceTree = ""; }; + B9C00000000000000000001F /* SpectralBinDelayUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpectralBinDelayUI.swift; sourceTree = ""; }; + B9C000000000000000000021 /* BinDelayController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayController.swift; sourceTree = ""; }; + B9C000000000000000000023 /* BinDelayView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BinDelayView.swift; sourceTree = ""; }; + B9C000000000000000000025 /* VectorOscillatorUI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorUI.swift; sourceTree = ""; }; + B9C000000000000000000026 /* VectorOscillatorController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorController.swift; sourceTree = ""; }; + B9C000000000000000000027 /* VectorOscillatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VectorOscillatorView.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + B9C000000000000000000011 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B9C00000000000000000000F /* LyrebirdUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + B9C000000000000000000002 = { + isa = PBXGroup; + children = ( + B9C000000000000000000005 /* LyrebirdiOSDemo */, + B9C000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + B9C000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + B9C000000000000000000004 /* LyrebirdiOSDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + B9C000000000000000000005 /* LyrebirdiOSDemo */ = { + isa = PBXGroup; + children = ( + B9C000000000000000000007 /* LyrebirdiOSDemoApp.swift */, + B9C00000000000000000001D /* UI */, + B9C00000000000000000001E /* Synthesizers */, + B9C000000000000000000006 /* Info.plist */, + ); + path = LyrebirdiOSDemo; + sourceTree = ""; + }; + B9C00000000000000000001D /* UI */ = { + isa = PBXGroup; + children = ( + B9C000000000000000000008 /* NoteController.swift */, + B9C00000000000000000000A /* SineToneView.swift */, + B9C000000000000000000021 /* BinDelayController.swift */, + B9C000000000000000000023 /* BinDelayView.swift */, + B9C000000000000000000026 /* VectorOscillatorController.swift */, + B9C000000000000000000027 /* VectorOscillatorView.swift */, + ); + path = UI; + sourceTree = ""; + }; + B9C00000000000000000001E /* Synthesizers */ = { + isa = PBXGroup; + children = ( + B9C000000000000000000009 /* SineToneUI.swift */, + B9C00000000000000000001F /* SpectralBinDelayUI.swift */, + B9C000000000000000000025 /* VectorOscillatorUI.swift */, + ); + path = Synthesizers; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + B9C000000000000000000013 /* LyrebirdiOSDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = B9C000000000000000000014 /* Build configuration list for PBXNativeTarget "LyrebirdiOSDemo" */; + buildPhases = ( + B9C000000000000000000010 /* Sources */, + B9C000000000000000000011 /* Frameworks */, + B9C000000000000000000012 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = LyrebirdiOSDemo; + packageProductDependencies = ( + B9C00000000000000000001C /* LyrebirdUI */, + ); + productName = LyrebirdiOSDemo; + productReference = B9C000000000000000000004 /* LyrebirdiOSDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + B9C000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + B9C000000000000000000013 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = B9C000000000000000000017 /* Build configuration list for PBXProject "LyrebirdiOSDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = B9C000000000000000000002; + packageReferences = ( + B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */, + ); + productRefGroup = B9C000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + B9C000000000000000000013 /* LyrebirdiOSDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + B9C000000000000000000012 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + B9C000000000000000000010 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B9C00000000000000000000B /* LyrebirdiOSDemoApp.swift in Sources */, + B9C00000000000000000000C /* NoteController.swift in Sources */, + B9C00000000000000000000D /* SineToneUI.swift in Sources */, + B9C00000000000000000000E /* SineToneView.swift in Sources */, + B9C000000000000000000020 /* SpectralBinDelayUI.swift in Sources */, + B9C000000000000000000022 /* BinDelayController.swift in Sources */, + B9C000000000000000000024 /* BinDelayView.swift in Sources */, + B9C000000000000000000028 /* VectorOscillatorUI.swift in Sources */, + B9C000000000000000000029 /* VectorOscillatorController.swift in Sources */, + B9C00000000000000000002A /* VectorOscillatorView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + B9C000000000000000000015 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdiOSDemo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdiOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + B9C000000000000000000016 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = LyrebirdiOSDemo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdiOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + B9C000000000000000000018 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = HE5VJFE9E4; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + B9C000000000000000000019 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = HE5VJFE9E4; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + B9C000000000000000000014 /* Build configuration list for PBXNativeTarget "LyrebirdiOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B9C000000000000000000015 /* Debug */, + B9C000000000000000000016 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B9C000000000000000000017 /* Build configuration list for PBXProject "LyrebirdiOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + B9C000000000000000000018 /* Debug */, + B9C000000000000000000019 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + B9C00000000000000000001C /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = B9C00000000000000000001A /* XCLocalSwiftPackageReference "../.." */; + productName = LyrebirdUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = B9C000000000000000000001 /* Project object */; +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..d4338f9 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "2f86be2113a80b402938cb09ebb72fe8cb9830066fe5b03aa1d174fcf50e2574", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdiOSDemo.xcscheme b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdiOSDemo.xcscheme new file mode 100644 index 0000000..6a5c4cd --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo.xcodeproj/xcshareddata/xcschemes/LyrebirdiOSDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Info.plist b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Info.plist new file mode 100644 index 0000000..fee6b25 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Info.plist @@ -0,0 +1,33 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + NSMicrophoneUsageDescription + Lyrebird uses the microphone for audio input processing. + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UILaunchScreen + + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + + diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift new file mode 100644 index 0000000..44ddcb5 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/LyrebirdiOSDemoApp.swift @@ -0,0 +1,80 @@ +// LyrebirdiOSDemoApp.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import AVFoundation +import LyrebirdSynth +import LyrebirdUI + +// ── Demo selector ───────────────────────────────────────────────────────────── +// Change `demo` to `.sineTone` or `.binDelay` to switch demos. +private enum Demo { case vector, binDelay, sineTone } +private let demo: Demo = .vector +// ────────────────────────────────────────────────────────────────────────────── + +@main +struct LyrebirdiOSDemoApp: App { + + let engine: SynthesisEngine + // Vector oscillator demo controller (used when demo == .vector) + let vectorController: VectorOscillatorController + // Sine-tone demo controller (used when demo == .sineTone) + let sineController: NoteController + // Bin-delay demo controller (used when demo == .binDelay) + let binDelayController: BinDelayController + + init() { + // Pre-activate AVAudioSession to discover the hardware's committed sample rate + // before constructing SynthesisEngine. iOS devices often lock to 48000 Hz regardless + // of the preferred rate — using the actual rate avoids pitch errors and choppy audio. + let session = AVAudioSession.sharedInstance() + try? session.setCategory(.playback, mode: .default) + try? session.setActive(true) + let sampleRate = session.sampleRate // actual hardware rate (44100 or 48000) + + let driver = iOSAudioDriver() + let eng = SynthesisEngine( + blockSize: 512, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + driver: driver + ) + let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048) + eng.scopeTap = scopeCapture + self.engine = eng + self.vectorController = VectorOscillatorController( + engine: eng, + synth: VectorOscillatorUI(), + scopeCapture: scopeCapture + ) + self.sineController = NoteController( + engine: eng, + synth: SineToneUI(), + scopeCapture: scopeCapture + ) + self.binDelayController = BinDelayController( + engine: eng, + scopeCapture: scopeCapture + ) + } + + var body: some Scene { + WindowGroup { + switch demo { + case .vector: + VectorOscillatorView(controller: vectorController) + .onDisappear { engine.stop() } + case .binDelay: + BinDelayView(controller: binDelayController) + .onDisappear { engine.stop() } + case .sineTone: + SineToneView(controller: sineController) + .onDisappear { engine.stop() } + } + } + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SineToneUI.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SineToneUI.swift new file mode 100644 index 0000000..912b857 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SineToneUI.swift @@ -0,0 +1,26 @@ +// SineToneUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A stereo sine tone whose frequency, amplitude, and pan are live-controllable from the UI. +final class SineToneUI: SynthesizerBase { + + /// Frequency in Hz. Slider range: 440–880 Hz. + @UIParam var frequency: Double = 440.0 + + /// Output amplitude (linear gain). Knob range: 0–1. + @UIParam var amplitude: Double = 0.25 + + /// Stereo pan position. Knob range: -1 (hard left) … 0 (center) … +1 (hard right). + @UIParam var pan: Double = 0.0 + + override func build() { + let osc = OscSin.Audio(freq: $frequency) + output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan)) + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SpectralBinDelayUI.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SpectralBinDelayUI.swift new file mode 100644 index 0000000..8205af9 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/SpectralBinDelayUI.swift @@ -0,0 +1,108 @@ +// SpectralBinDelayUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Spectral-bin-delay synthesizer demo. +/// +/// An `Impulse.Audio` at 0.2 Hz (one fire per 5 s) drives an FFT analysis chain +/// that includes a `SpectralBinDelay`. The delayed spectral frames are resynthesised +/// via `IFFTSynthesis` and panned to centre stereo on bus 0. +/// +/// Two `LyrebirdBuffer`s — `delayTimes` and `feedbacks` — are exposed as public +/// stored properties so the UI can write into them live via `MultiSlider`. +/// Both buffers are pre-allocated at `init` and never reallocated. +/// +/// - Note: `sampleRate` must be passed at construction time because +/// `SpectralBinDelay` needs it to convert delay-seconds → hop-frames. +/// Create this synthesizer *after* the engine has started so that +/// `engine.sampleRate` reflects the committed hardware rate. +final class SpectralBinDelayUI: SynthesizerBase { + + // MARK: - Constants + + /// FFT frame size used throughout the analysis/synthesis chain. + static let fftSize: Int = 1024 + + /// Number of new samples between FFT hops (75 % overlap). + static let hopSize: Int = 256 + + /// `fftSize / 2` — the number of independent magnitude/phase bins. + static let halfSize: Int = fftSize / 2 + + /// Maximum delay time accepted by `SpectralBinDelay` (seconds). + /// Keep below `lyrebirdSpectralBinDelayMaxFrames * hopSize / sampleRate`. + static let maxDelaySeconds: Double = 1.0 + + // MARK: - Engine sample rate (captured at init — needed in build()) + + /// Audio sample rate in Hz. Captured from the engine before `build()` runs. + private let engineSampleRate: Double + + // MARK: - Parameter buffers (public — UI writes via MultiSlider) + + /// Per-bin delay times in seconds. Mono, `halfSize` frames. + /// Default: 0 (clean pass-through until the UI writes new values). + let delayTimes: LyrebirdBuffer + + /// Per-bin feedback gains in [0, 0.95). Mono, `halfSize` frames. + /// Default: 0 (clean pass-through until the UI writes new values). + let feedbacks: LyrebirdBuffer + + // MARK: - Initialisation + + /// - Parameter sampleRate: The engine's committed sample rate (Hz). + /// `SynthesisEngine.sampleRate` is a `let` initialised in `init`, so it + /// is valid as soon as the engine is constructed. + init(sampleRate: Double) { + let halfSize = SpectralBinDelayUI.halfSize + + self.engineSampleRate = sampleRate + + let dt = LyrebirdBuffer(count: halfSize) + dt.fill(with: 0.0) + + let fb = LyrebirdBuffer(count: halfSize) + fb.fill(with: 0.0) + + self.delayTimes = dt + self.feedbacks = fb + + super.init() + } + + // MARK: - Signal graph + + override func build() { + let fftSize = SpectralBinDelayUI.fftSize + let hopSize = SpectralBinDelayUI.hopSize + + // Source: sparse impulse that fires at 0.2 Hz (once every 5 s). + let impulseFreq = 0.2 + let impulse = Impulse.Audio(freq: impulseFreq) + + // SpectralBinDelay processor — allocated here inside build() which + // runs off the RT thread before the synthesizer is added to the engine. + let bd = SpectralBinDelay( + fftSize: fftSize, + hopSize: hopSize, + maxDelaySeconds: SpectralBinDelayUI.maxDelaySeconds, + sampleRate: engineSampleRate, + delayTimes: delayTimes, + feedbacks: feedbacks + ) + + let binDelay = SpectralChain.Audio( + input: impulse, + fftSize: fftSize, + hopSize: hopSize, + stages: [.mono(bd)] + ) + + // Pan to centre; the effect is mono but we send it to stereo bus 0. + output(bus: 0, source: Pan2(input: binDelay, pan: 0.0)) + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/VectorOscillatorUI.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/VectorOscillatorUI.swift new file mode 100644 index 0000000..a3c0ef9 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/Synthesizers/VectorOscillatorUI.swift @@ -0,0 +1,78 @@ +// VectorOscillatorUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A stereo vector oscillator whose XY position, frequency, and amplitude are +/// live-controllable from the UI. +/// +/// Four corner wavetables are crossfaded on a 2D XY plane: +/// +/// C (triangle) ── D (Hanning) (y = 1) +/// │ │ +/// A (sine) ──── B (saw-ish) (y = 0) +/// x=0 x=1 +/// +/// Moving X blends A↔B (and C↔D); moving Y blends the AB mix into the CD mix. +final class VectorOscillatorUI: SynthesizerBase { + + /// X-axis blend position. 0 = corner A/C, 1 = corner B/D. + /// Normalized [0, 1]. XY pad range: 0…1. + @UIParam var x: Double = 0.5 + + /// Y-axis blend position. 0 = bottom (A, B), 1 = top (C, D). + /// Normalized [0, 1]. XY pad range: 0…1. + @UIParam var y: Double = 0.5 + + /// Oscillator frequency in Hz. Slider range: 40–2000 Hz. + @UIParam var frequency: Double = 220.0 + + /// Output amplitude (linear gain). Knob range: 0–1. + @UIParam var amplitude: Double = 0.25 + + private let bufferA: LyrebirdBuffer // corner A: sine + private let bufferB: LyrebirdBuffer // corner B: 16-partial saw-ish + private let bufferC: LyrebirdBuffer // corner C: triangle + private let bufferD: LyrebirdBuffer // corner D: Hanning window shape + + override init() { + let tableSize = lyrebirdDefaultTableSize + + let a = LyrebirdBuffer(count: tableSize) + a.fillSine() + + let b = LyrebirdBuffer(count: tableSize) + b.fill(partials: 16) + + let c = LyrebirdBuffer(count: tableSize) + c.fillTriangle() + + let d = LyrebirdBuffer(count: tableSize) + d.fillHanning() + + self.bufferA = a + self.bufferB = b + self.bufferC = c + self.bufferD = d + + super.init() + } + + override func build() { + let osc = VectorOscillator.Audio( + bufferA: bufferA, + bufferB: bufferB, + bufferC: bufferC, + bufferD: bufferD, + freq: $frequency, + x: $x, + y: $y, + mul: $amplitude + ) + output(bus: 0, source: Pan2(input: osc, pan: 0.0)) + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift new file mode 100644 index 0000000..146665d --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift @@ -0,0 +1,74 @@ +// BinDelayController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +/// Controller for the spectral-bin-delay demo view. +/// +/// Unlike `NoteController`, the synthesizer is created lazily when the user +/// first taps "Start Synthesizer" — this is necessary because +/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed +/// sample rate, which is only valid after `engine.start()` returns. +@Observable +final class BinDelayController { + + let engine: SynthesisEngine + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + /// The live synthesizer instance. `nil` until first "Start Synthesizer" tap. + private(set) var synth: SpectralBinDelayUI? + + init(engine: SynthesisEngine, scopeCapture: ScopeCapture) { + self.engine = engine + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying, let s = synth { + engine.remove(s) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + if let s = synth { + engine.remove(s) + } + isPlaying = false + } else { + guard engineRunning else { return } + // Create the synthesizer lazily so we don't put it in the node tree + // until the user requests it. + if synth == nil { + synth = SpectralBinDelayUI(sampleRate: engine.sampleRate) + } + if let s = synth { + do { + try engine.add(s) + isPlaying = true + } catch { + print("[Lyrebird] BinDelayController.toggle add failed: \(error)") + } + } + } + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayView.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayView.swift new file mode 100644 index 0000000..33e0481 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayView.swift @@ -0,0 +1,131 @@ +// BinDelayView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +/// Main view for the spectral bin-delay demo (iOS). +/// +/// Shows engine and synth toggle buttons, two `MultiSlider` rows for +/// per-bin delay times and feedbacks, an engine status strip, and a scope. +/// Wrapped in a vertical `ScrollView` for compact-height device compatibility; +/// each `MultiSlider` is also wrapped in a horizontal `ScrollView` so all +/// `SpectralBinDelayUI.halfSize` (512) bin bars remain draggable on narrow +/// iPhone screens. The demo's purpose is to show that per-bin spectral control +/// is possible, not to make any one bin precisely tweakable. +struct BinDelayView: View { + + let controller: BinDelayController + + private let sliderHeight: CGFloat = 160 + private let sliderRowWidth: CGFloat = 1280 + private let maxFeedback = 0.95 + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 20) { + + // MARK: Engine row + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + // MARK: Synth row + HStack { + VStack(alignment: .leading, spacing: 2) { + Text("Spectral Bin Delay") + .font(.headline) + Text("Impulse source · 0.2 Hz · fftSize 1024 · hop 256") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + Divider() + + // MARK: Delay times slider + Text("Delay Times (all 512 bins, range 0–1 s)") + .font(.caption) + .foregroundStyle(.secondary) + + if let synth = controller.synth { + ScrollView(.horizontal, showsIndicators: true) { + MultiSlider( + buffer: synth.delayTimes, + count: SpectralBinDelayUI.halfSize, + range: 0.0...1.0, + height: sliderHeight + ) + .frame(width: sliderRowWidth) + } + } else { + placeholderSlider(label: "Start synthesizer to enable") + } + + // MARK: Feedback slider + Text("Feedbacks (all 512 bins, range 0–0.95)") + .font(.caption) + .foregroundStyle(.secondary) + + if let synth = controller.synth { + ScrollView(.horizontal, showsIndicators: true) { + MultiSlider( + buffer: synth.feedbacks, + count: SpectralBinDelayUI.halfSize, + range: 0.0...maxFeedback, + height: sliderHeight + ) + .frame(width: sliderRowWidth) + } + } else { + placeholderSlider(label: "Start synthesizer to enable") + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + } + .padding(20) + } + } + + // MARK: - Helpers + + @ViewBuilder + private func placeholderSlider(label: String) -> some View { + ZStack { + Color.lyrebirdControlBackground + Text(label) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(height: sliderHeight) + .frame(maxWidth: .infinity) + .overlay(Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1)) + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift new file mode 100644 index 0000000..641a6d6 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/NoteController.swift @@ -0,0 +1,57 @@ +// NoteController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +@Observable +final class NoteController { + + let engine: SynthesisEngine + let synth: SineToneUI + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + init(engine: SynthesisEngine, synth: SineToneUI, scopeCapture: ScopeCapture) { + self.engine = engine + self.synth = synth + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying { + engine.remove(synth) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + engine.remove(synth) + isPlaying = false + } else { + do { + try engine.add(synth) + isPlaying = true + } catch { + print("[Lyrebird] NoteController.toggle add failed: \(error)") + } + } + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/SineToneView.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/SineToneView.swift new file mode 100644 index 0000000..d19c9a5 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/SineToneView.swift @@ -0,0 +1,112 @@ +// SineToneView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +struct SineToneView: View { + + let controller: NoteController + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 20) { + + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + HStack { + Text("Sine Tone") + .font(.headline) + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + ParameterSlider( + "Frequency", + node: controller.synth.$frequency, + range: 440.0...880.0 + ) + + HStack(spacing: 24) { + ParameterKnob( + "Amplitude", + node: controller.synth.$amplitude, + range: 0.0...1.0 + ) + ParameterKnob( + "Pan", + node: controller.synth.$pan, + range: -1.0...1.0 + ) + ParameterLabel("Level", node: controller.synth.$amplitude) + Spacer() + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + + Divider() + + Text("Envelope") + .font(.caption) + .foregroundStyle(.secondary) + + LyrebirdEnvelopeView( + Envelope( + levels: [0.0001, 1, 0.6, 0.4, 0.0001], + durations: [0.05, 0.15, 0.4, 0.3], + curves: [.exponential, .exponential, .lin, .exponential], + loopNode: 2, + releaseNode: 4 + ), + width: 300, + height: 100 + ) + + Divider() + + Text("Distribution Preview (Gaussian, 200 samples)") + .font(.caption) + .foregroundStyle(.secondary) + + LyrebirdScatterView( + DemandTemporalTendency(distribution: .gauss, + parX: .value(0.5), parY: .value(0.15), + seed: 42) + .samples(count: 200), + yRange: 0.0...1.0, + pointColor: .cyan, + width: 300, + height: 100 + ) + } + .padding(20) + } + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift new file mode 100644 index 0000000..a2de487 --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorController.swift @@ -0,0 +1,61 @@ +// VectorOscillatorController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Observation +import LyrebirdSynth + +@Observable +final class VectorOscillatorController { + + let engine: SynthesisEngine + let synth: VectorOscillatorUI + let scopeCapture: ScopeCapture + + private(set) var engineRunning: Bool = false + private(set) var isPlaying: Bool = false + + init( + engine: SynthesisEngine, + synth: VectorOscillatorUI, + scopeCapture: ScopeCapture + ) { + self.engine = engine + self.synth = synth + self.scopeCapture = scopeCapture + } + + func toggleEngine() { + if engineRunning { + if isPlaying { + engine.remove(synth) + isPlaying = false + } + engine.stop() + engineRunning = false + } else { + do { + try engine.start() + engineRunning = true + } catch { + print("Engine failed to start: \(error)") + } + } + } + + func toggle() { + if isPlaying { + engine.remove(synth) + isPlaying = false + } else { + do { + try engine.add(synth) + isPlaying = true + } catch { + print("[Lyrebird] VectorOscillatorController.toggle add failed: \(error)") + } + } + } +} diff --git a/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorView.swift b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorView.swift new file mode 100644 index 0000000..4430b1f --- /dev/null +++ b/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/VectorOscillatorView.swift @@ -0,0 +1,80 @@ +// VectorOscillatorView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdSynth +import LyrebirdUI + +struct VectorOscillatorView: View { + + let controller: VectorOscillatorController + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 20) { + + HStack { + Text("Engine") + .font(.headline) + Spacer() + Button(controller.engineRunning ? "Stop Engine" : "Start Engine") { + controller.toggleEngine() + } + .buttonStyle(.borderedProminent) + .tint(controller.engineRunning ? .red : .green) + } + + Divider() + + HStack { + Text("Vector Oscillator") + .font(.headline) + Spacer() + Button(controller.isPlaying ? "Stop" : "Start") { + controller.toggle() + } + .buttonStyle(.bordered) + .tint(controller.isPlaying ? .red : .green) + .disabled(!controller.engineRunning) + } + + ParameterXY( + xLabel: "X (A↔B)", + xNode: controller.synth.$x, + xRange: 0.0...1.0, + yLabel: "Y (AB↔CD)", + yNode: controller.synth.$y, + yRange: 0.0...1.0 + ) + .frame(width: 240, height: 240) + + HStack(spacing: 24) { + ParameterKnob( + "Frequency", + node: controller.synth.$frequency, + range: 40.0...2000.0 + ) + ParameterKnob( + "Amplitude", + node: controller.synth.$amplitude, + range: 0.0...1.0 + ) + Spacer() + } + + Divider() + + LyrebirdStatusView(engine: controller.engine) + + Divider() + + LyrebirdScopeView(capture: controller.scopeCapture) + .frame(height: 120) + } + .padding(20) + } + } +} diff --git a/Demos/Mozart.aiff b/Demos/Mozart.aiff new file mode 100644 index 0000000..f50cf2a Binary files /dev/null and b/Demos/Mozart.aiff differ diff --git a/Demos/Perc.aiff b/Demos/Perc.aiff new file mode 100755 index 0000000..5d5f563 Binary files /dev/null and b/Demos/Perc.aiff differ diff --git a/INSTALLATION_AND_USAGE.md b/INSTALLATION_AND_USAGE.md new file mode 100644 index 0000000..a7f0f98 --- /dev/null +++ b/INSTALLATION_AND_USAGE.md @@ -0,0 +1,282 @@ +# Lyrebird — Installation & Usage + +How to add Lyrebird to a project and scaffold the five kinds of app it supports: real-time, real-time + UI, non-real-time (offline) render, AUv3 plugin, and iOS. + +The package is hosted at . + +--- + +## Requirements + +| Platform | OS | Xcode | Swift | +|---|---|---|---| +| macOS | 15+ | 16+ | 6.0 | +| iOS | 18+ | 16+ | 6.0 | + +The macOS 15 / iOS 18 floor is hard: Lyrebird's lock-free queues use `Synchronization.Atomic`, which is unavailable earlier. + +--- + +## Adding the package + +### Swift Package Manager (`Package.swift`) + +```swift +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "MyPiece", + platforms: [.macOS(.v15), .iOS(.v18)], + dependencies: [ + .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"), + ], + targets: [ + .executableTarget( + name: "MyPiece", + dependencies: [ + .product(name: "Lyrebird", package: "Lyrebird"), + .product(name: "LyrebirdUI", package: "Lyrebird"), // only if you need the GUI module + ]), + ] +) +``` + +The package vends three products: + +| Product | Kind | Use | +|---|---|---| +| `Lyrebird` | dynamic library | Core framework — Generators, Synthesizers, engine, drivers. | +| `LyrebirdUI` | library | SwiftUI parameter controls (`ParameterKnob`, scope/envelope views, `LyrebirdWindow`). | +| `LyrebirdCLI` | executable | The `lyrebird` command-line tool (scaffolding, REPL). | + +### In Xcode + +**File ▸ Add Package Dependencies…**, paste the repository URL, choose **Up to Next Major Version** from `1.0.0`, and add the `Lyrebird` (and optionally `LyrebirdUI`) products to your target. + +### Local checkout (development) + +To build against a local clone instead of the remote, use a path dependency: + +```swift +.package(name: "Lyrebird", path: "/Users/me/Documents/LyrebirdII") +``` + +The scaffolder (below) does this automatically with `--lyrebird-path`. + +### The dynamic-library note + +`Lyrebird` is declared `type: .dynamic` in `Package.swift`. This is a deliberate workaround for an Xcode 26 SwiftPM regression and will revert to `.static` once that is fixed. If you hit `dyld: Library not loaded` under a hardened runtime (sandboxed app or AUv3 extension), add to your entitlements: + +```xml +com.apple.security.cs.disable-library-validation + +``` + +then clean-build (⇧⌘K). The generated Xcode-project templates already do this; the workspace also sets `SWIFT_USE_INTEGRATED_DRIVER = NO` and `parallelizeBuildables = NO`. + +--- + +## The `lyrebird` CLI + +Project scaffolding goes through the `lyrebird` CLI. Install it once onto your `$PATH`: + +```bash +swift build -c release --product LyrebirdCLI +cp .build/release/LyrebirdCLI /usr/local/bin/lyrebird +lyrebird --version # verify +``` + +(From a checkout you can also use `swift run lyrebird …` without installing.) + +| Command | Purpose | +|---|---| +| `lyrebird new [--template ] [--lyrebird-path

]` | Scaffold a new project. | +| `lyrebird run [--release]` | Build and run the project in the current directory. | +| `lyrebird export [--to

] [--overwrite]` | Emit a standalone `SynthesizerBase` template file. | +| `lyrebird install-templates [--force]` | Install the Xcode file templates (New File… ▸ Lyrebird). | +| `lyrebird uninstall-templates` | Remove them. | +| `lyrebird repl` | Swift REPL with `import LyrebirdSynth` available. | +| `lyrebird` (no args) | Interactive `lyrebird>` shell. | + +Full reference: [`docs/tooling/cli-guide.md`](docs/tooling/cli-guide.md). + +--- + +## Generating projects + +`lyrebird new --template