Repository Public
1# Architecture Overview23ORIX DJ is a native macOS application made of two parts:45- **`ORIXDJCore`**, a Swift package (`Packages/ORIXDJCore`) that contains everything that is not interface: DSP,6 analysis, the library, MIDI, the ORIX Script language, and the audio engine. No SwiftUI is imported anywhere in the7 package, so the whole engine can be built and tested from the command line with `swift test`.8- **The application** (`App/Sources`), a SwiftUI and AppKit front end that owns one session object and draws its9 state. The Xcode project is generated from `project.yml` by XcodeGen.1011There is no third-party code in either part. The package links only system frameworks and libraries: Accelerate,12AudioToolbox, CoreAudio, AVFoundation, CoreMIDI and `sqlite3`.1314This page is the map. Each area has its own document, linked from the tables below.1516## Module map1718The package is split into targets with a strict dependency direction (from `Package.swift`):1920```mermaid21flowchart TD22 APP["ORIX DJ application (SwiftUI + AppKit + Metal)"]23 CORE["ORIXDJCore (umbrella, re-exports every module)"]24 ENGINE["ORIXDJEngine"]25 SCRIPT["ORIXScript"]26 DSP["ORIXDSP"]27 ANALYSIS["ORIXAnalysis"]28 LIBRARY["ORIXLibrary"]29 MIDI["ORIXMIDI"]30 BENCH["orix-dj-bench (command-line tool)"]3132 APP --> CORE33 CORE --> ENGINE34 BENCH --> ENGINE35 ENGINE --> SCRIPT36 ENGINE --> DSP37 ENGINE --> ANALYSIS38 ENGINE --> LIBRARY39 ENGINE --> MIDI40 SCRIPT --> DSP41```4243`ORIXDSP`, `ORIXAnalysis`, `ORIXLibrary` and `ORIXMIDI` depend on nothing but system frameworks. `ORIXScript`44depends on `ORIXDSP` only for the effect catalogue, from which part of the language schema is generated.45`ORIXDJEngine` is the only target that knows about all the others.4647| Target | Contents | Document |48|---|---|---|49| `ORIXDSP` | `Primitives.swift` (gain maths, biquads, smoothers, delay lines, the lock-free single-producer single-consumer queue), `EffectUnit.swift` (base class of every effect), `EffectCatalog.swift` (the single table of 18 effect kinds and their parameters), `Effects/*` | [DSP](dsp.md) |50| `ORIXAnalysis` | FFT helper, onset strength, tempo and beat grid, key, loudness, waveform summary, and `SignalSynth` (deterministic synthetic audio for tests and demo material) | [Analysis](analysis.md), [Waveform](waveform.md) |51| `ORIXLibrary` | `SQLiteDatabase` (wrapper over the SQLite C API), `LibraryStore` (schema, migrations, tracks, collections, scripts), `SmartCrateSQL`, `MediaImporter` | [Persistence](persistence.md) |52| `ORIXMIDI` | `MIDIManager` (CoreMIDI client, hot-plug, input, learn, output), `MIDIParser`, mapping profiles and the pure mapping engine | [Automation](automation.md) for the shared parameter space; [Testing](../development/testing.md) for what is verified |53| `ORIXScript` | Lexer, parser, AST, compiler, plan, runtime, simulator and debugger, schema, generated reference, presets, editor tools | [Automation](automation.md) |54| `ORIXDJEngine` | `TrackBuffer`, `DeckVoice`, `RenderCore`, `AudioOutput`, `DJEngine`, `AutomationHost`, `Recorder`, `DJSession`, `AutoDJ`, `Project`, `ControlSurface`, `Anthropic/*` | [Audio engine](audio-engine.md), [Deck engine](deck-engine.md), [Mixer](mixer.md), [Recording](recording.md), [AI integration](ai-integration.md) |55| `orix-dj-bench` | Benchmarks, documentation generation, script validation, real-music analysis and offline mixes | [Performance](../development/performance.md), [Setup](../development/setup.md) |5657The application is organised by feature under `App/Sources/Features`: Studio (decks and mixer), Decks, Mixer,58Effects, Waveforms, Library, Auto DJ, Automation Studio, Docs, Claude Studio, Recording, MIDI, Performance and59Settings. `App/Sources/App` holds the entry point, the application model and the root layout;60`App/Sources/DesignSystem` holds the tokens and shared controls (see [design system](../design/design-system.md)).6162## Overall architecture6364```mermaid65flowchart TD66 subgraph UI["Application process, main thread"]67 VIEWS["SwiftUI and AppKit views"]68 MODEL["AppModel (main actor)"]69 METAL["Waveform renderer (Metal)"]70 end7172 subgraph CONTROL["Control plane (any thread, lock protected)"]73 SESSION["DJSession"]74 ENGINE["DJEngine"]75 HOST["AutomationHost"]76 SURFACE["ControlSurface"]77 LIB["LibraryStore (SQLite)"]78 MIDI["MIDIManager (CoreMIDI)"]79 REC["Recorder"]80 AI["ScriptAssistant + AnthropicClient"]81 end8283 subgraph RT["Audio render thread (Core Audio)"]84 CORE["RenderCore"]85 VOICES["4 x DeckVoice"]86 FX["Effect racks + master limiter"]87 end8889 DEVICE["Output device (AUHAL)"]90 API["api.anthropic.com (optional, user key)"]9192 VIEWS --> MODEL93 MODEL --> SESSION94 SESSION --> ENGINE95 SESSION --> HOST96 SESSION --> LIB97 SESSION --> REC98 MIDI --> SURFACE99 SURFACE --> ENGINE100 HOST --> ENGINE101 ENGINE -- "timestamped control events (lock-free queue)" --> CORE102 CORE -- "state snapshots + notices" --> ENGINE103 CORE --> VOICES104 CORE --> FX105 CORE --> DEVICE106 CORE -- "master audio (lock-free ring)" --> REC107 MODEL --> AI108 AI --> API109 MODEL --> METAL110```111112The central design rule is the boundary between the control plane and the render thread:113114- **Into the render thread** there is exactly one path for behaviour: `ControlEvent` values pushed onto a bounded115 lock-free queue (`SPSCQueue<ControlEvent>` with a minimum capacity of 4096 in `RenderCore`). Each event carries the116 engine sample time at which it applies; zero means "as soon as possible". Output routing is the one exception: the117 channel indices are atomics read by the render thread.118- **Out of the render thread** there are three paths, none of which can block it: sequence-locked state snapshots119 (`SnapshotCell`) for positions, meters and timing counters; a notice queue (`SPSCQueue<RenderNotice>`, minimum120 capacity 1024) for "track ended", "brake finished" and "release this object"; and the recording ring.121122On-screen controls, MIDI controllers and ORIX Script all address the same parameter space (`ParamAddress` in123`DJEngine.swift`). There is no separate code path for automation: a script that sets `deck.A.volume` and a fader that124does so produce the same kind of event.125126Objects that the render thread uses but did not create (decoded tracks, effect units) are created on the control127side, handed over as unmanaged pointers inside events, and handed back through a notice when replaced, so that they128are released off the render thread.129130## Threads131132| Thread | Created by | What runs on it | Rules |133|---|---|---|---|134| Audio render thread | Core Audio, through the AUHAL render callback in `AudioOutput.swift` | `RenderCore.render`: event intake, the four deck voices, channel strips, racks, crossfader, master rack, limiter, meters, cue bus, recording tap, snapshot publication | Written to avoid allocation, locks and blocking calls. The honest caveats are listed in [audio engine](audio-engine.md). |135| Automation scheduler thread | `AutomationHost.startScheduler()`; thread name `ai.spboucher.orix.dj.automation` | `tick()` every 4 ms: services the engine (drains notices, advances the master clock, maintains sync), advances every running automation to the clock plus a look-ahead, and emits their commands as timestamped control events | Runs under the Mach time-constraint policy (period 4 ms, computation 0.4 ms, constraint 2 ms, preemptible). Never touches audio buffers. The default look-ahead is 30 ms (`lookaheadSeconds = 0.03`); the application clamps the user setting to 5 to 50 ms. The benchmark report's heading says 15 ms, but the benchmark code does not change the default; see [automation](automation.md). |136| Main thread | AppKit | SwiftUI and AppKit views, `AppModel` (a main-actor class). A timer refreshes live state (positions, meters) 30 times per second and slower state 5 times per second by reading the engine's snapshots. The Metal waveform view draws here. | Never decodes, analyses or queries the library synchronously for large results. |137| Background work | Dispatch queues in `DJSession`: `ai.spboucher.orix.dj.work` (concurrent, user-initiated) and `ai.spboucher.orix.dj.analysis` (serial, utility) | Track decoding into `TrackBuffer`, analysis, import, the Auto DJ timer | Results reach the interface through `DJSession.onChange`. |138| Recorder writer | Dispatch queue `ai.spboucher.orix.dj.recorder` (utility) with a timer | Drains the recording ring and writes the CAF take | See [recording](recording.md). |139| CoreMIDI | A dedicated run-loop thread (`MIDIRunLoopThread`) plus CoreMIDI's own callback thread and the queue `ai.spboucher.orixdj.midi` | Device notifications, incoming event lists, mapping dispatch into `ControlSurface` | Mapping logic itself is pure and has no CoreMIDI dependency. |140| Device notifications | Dispatch queue `ai.spboucher.orix.dj.devices` | Core Audio property listeners for device list and default output changes | |141| Network | `URLSession` (ephemeral configuration) | The Anthropic client only | See [AI integration](ai-integration.md). |142143When no audio device is running (unit tests, the benchmark tool, offline mixes), `DJEngine.renderOffline` calls the144same `RenderCore.render` from the calling thread and services the engine after each block. This is how audio145behaviour is tested without hardware; see [testing](../development/testing.md).146147## Data flow148149### From a file to sound1501511. `MediaImporter` validates a file (extension, readable by AVFoundation, not DRM-protected), reads its tags and152 stores a row in the SQLite library with a bookmark to the file. The audio itself is never copied.1532. Loading a deck decodes the whole file on a background queue into a `TrackBuffer`: two planar arrays of 32-bit154 float at the file's own sample rate. Files longer than 150 minutes are refused.1553. Analysis runs on the decoded buffer (tempo and beat grid, key, loudness, peak, waveform summary). The result is156 stored in the library, zlib-compressed JSON, so a track is analysed once. See [analysis](analysis.md).1574. `DJEngine` hands the buffer to the render thread in a `deckSetTrack` event. From then on the render thread reads158 only memory.1595. The waveform summary (not the audio) is uploaded once as a texture and drawn by a Metal fragment shader. See160 [waveform](waveform.md).161162### Audio signal flow163164One call to `RenderCore.render` produces one device buffer. Internally the buffer is rendered in chunks of at most16564 frames, and a chunk is cut short when a timed event falls inside it, so that an event takes effect on its exact166sample.167168```mermaid169flowchart LR170 subgraph DECK["Per deck (x4)"]171 V["DeckVoice: resampled or time-stretched playback"]172 T["Trim"]173 EQ["EQ (3 or 4 bands)"]174 F["High-pass / low-pass"]175 R["Channel rack (8 slots)"]176 FAD["Fader"]177 end178 XF["Crossfader (side A, side B or through)"]179 SUM["Master sum"]180 MR["Master rack (8 slots)"]181 MV["Master volume"]182 LIM["Limiter"]183 OUT["Master output pair"]184 RECTAP["Recording ring"]185 CUE["Cue bus: pre-fader channels blended with master"]186 COUT["Cue output pair, or split cue"]187188 V --> T --> EQ --> F --> R --> FAD --> XF --> SUM --> MR --> MV --> LIM --> OUT189 R -- "pre-fader listen" --> CUE190 LIM --> RECTAP191 LIM -- "cue mix" --> CUE192 CUE --> COUT193```194195The details of each stage (filter frequencies, crossfader formulas, limiter, metering) are in [mixer](mixer.md) and196[DSP](dsp.md); the two playback paths of a deck are in [deck engine](deck-engine.md).197198### From a control gesture to the render thread199200```mermaid201sequenceDiagram202 participant S as Source (view, MIDI mapping or script)203 participant E as DJEngine (control plane)204 participant Q as Event queue (lock-free)205 participant R as RenderCore (render thread)206 S->>E: set parameter or trigger action207 E->>E: validate, quantise, compute target sample time208 E->>Q: push ControlEvent(time, kind, values)209 R->>Q: pop at the start of the next render call210 R->>R: apply now, or insert into the time-ordered pending list211 R->>R: split the chunk at the event time and apply on that sample212 R-->>E: state snapshot and notices213```214215A manual gesture carries time zero and is applied at the start of the next buffer, so its latency is at most one216buffer plus the device latency. An automation command is computed ahead of the clock by the scheduler and carries an217exact sample time; the render core counts how many such tracked events arrived after their target sample. The218measured results are in [performance](../development/performance.md).219220### Automation221222ORIX Script source is compiled to a plan, which the runtime executes as cooperative tasks in beat time. The live223`AutomationHost` and the offline simulator drive the same runtime; only the target differs (the engine, or a224simulated rig). Auto DJ and the Claude Studio proposals are ordinary scripts and go through the same compiler. See225[automation](automation.md) and [AI integration](ai-integration.md).226227### Persistence228229| Data | Where | Document |230|---|---|---|231| Library, analysis results, cues, crates, playlists, history, saved scripts, MIDI profiles, settings documents | One SQLite database (WAL mode) managed by `LibraryStore` | [Persistence](persistence.md) |232| Projects | `.orixdjproject` packages: decks, mixer, effect chains, routing, scripts and MIDI mapping; audio is referenced, never copied | [Persistence](persistence.md) |233| Recordings | 32-bit float CAF takes and exported files | [Recording](recording.md) |234| User preferences | `UserDefaults` (`AppSettings`) | [Setup](../development/setup.md) |235| Anthropic API key | Keychain only | [Security report](../reports/security.md) |236237## What the architecture does not contain238239- No audio input path (no microphone, line input, DVS or timecode).240- No plug-in hosting (Audio Units or VST).241- No disk streaming of audio: tracks are fully decoded in memory.242- No network use other than the optional Anthropic client.243- No variable-tempo beat grid.244245The reasons for these choices, and the alternatives that were considered, are in the246[technology evaluation](../research/technology-evaluation.md). The comparison with existing software is in the247[competitive analysis](../research/competitive-analysis.md).248249## Verification status250251The engine package had 241 tests in 44 suites passing in the run of 2026-11-21 (see252[testing](../development/testing.md)). They render audio offline and use CoreMIDI virtual endpoints, temporary SQLite253files and an in-process stub transport for the Anthropic client. Not covered by any test or manual check so far: listening evaluation, physical MIDI254hardware, multi-channel audio interfaces, the live Anthropic API, and long live sessions. The UI test target contains255nine end-to-end tests added on 2026-11-21; no run of them is recorded in this documentation.256