Architecture
This chapter explains what happens between the text you write and the sound you hear. It is for the curious, and for anyone who wants to build on Sonata.
The pipeline
source text
→ tokens (lexer: every token knows its place in the file)
→ syntax tree (parser: recovers from errors and reports several at once)
→ resolved program (names, modules, kinds, argument counts)
→ Musical IR (the piece: notes with exact times, tempo map, automation, routing)
→ Audio DSP IR (the mixing graph for one sample rate, with latencies)
→ execution plan (instruments, effects and buffers prepared in memory)
→ audio (played in real time, or rendered to a file)Three things follow from this shape.
One compiler. The app, the command line and the editor services all call the same compiler. The Studio does not parse or time anything itself: it draws what the compiler returns. That is why the timeline, the score, a MIDI export and a render always agree.
The program is run at compile time. Loops, functions and random choices are executed while compiling; the result, the Musical IR, is a plain list of events. Playback never executes your code, so it cannot stall the audio.
An execution plan, not machine code. The compiled piece is a prepared graph that the runtime interprets block by block. Sonata 0.1 does not generate machine code.
You can look at every stage: sonata build piece.sonata --emit ast, --emit ir,
--emit graph, or the Compiler space (Compiler).
The Musical IR
A compiled composition (a Program) contains:
- the tempo map and the time signatures;
- tracks, each with its instrument (engine and parameter values), its mixer settings, its effects and its notes;
- for each note: its exact musical start and duration, the same in seconds, its pitch (a fractional MIDI number), its velocity, its voice, its articulation, any pitch bend, and the place in the source that produced it;
- automation lanes, buses, sends, the master settings and markers.
The source position kept with each note is what lets a click on a note in the Studio or the Score take you to the right line of code.
Time
Musical positions are exact fractions of a whole note, held as two 64-bit integers. They are never rounded: a thousand triplets end exactly where they should. An overflow is an error (Q6005), never a silent wrap.
Seconds come from the tempo map. For a constant tempo, a whole note lasts 240 / bpm
seconds. A tempo ramp moves the duration of a whole note in a straight line between its two
ends, and the time it takes is the area under that line (a trapezoid).
A time in seconds becomes a sample index by one rule, used by the renderer, the real-time engine and the rulers alike:
sample = floor(seconds × sample_rate + 0.5)A quarter note at 120 bpm starts 0.5 s after the previous one: sample 24 000 at 48 kHz, 22 050 at 44.1 kHz. The piece is the same at every sample rate; only the rounding to samples differs.
The mixing graph
For a given sample rate the compiler turns the tracks, buses and master into a graph of nodes:
instrument sources, effects, faders, sends, sums, the limiter and the output. It checks that
the graph has no cycle, orders the nodes, computes the latency along every path and inserts
pure delays where paths of different latency meet, so that everything is aligned at each sum.
sonata inspect prints the number of nodes and the total latency.
The audio engine
The engine has two halves. The processor runs on the audio thread and produces sound. The controller is used by everything else — the transport, the mixer, the editor — and talks to the processor through lock-free queues.
The audio thread follows strict rules, because a late block is an audible click:
- it never allocates or frees memory — voices, buffers and delay lines are created when the piece is prepared;
- it never waits for a lock, reads a file, writes a log or compiles;
- it works in chunks of at most 64 frames, cut at every note and automation boundary, so events are exact to the sample whatever the block size of the audio device;
- it checks its own output: a value that is not a finite number is replaced by silence and counted; the output to the device is clamped as a last resort.
These rules are enforced by tests. One of them counts every memory allocation during thousands of audio callbacks, with every effect inserted and commands and program swaps arriving, and requires the count to be zero.
Playback and export are the same code. The offline renderer drives the same processor, so a render equals what the engine plays: the tests compare renders made with block sizes of 32, 64, 128, 256, 1 024 frames and one single block, and require identical samples.
Hot reload
When you edit while the piece plays, the new version is compiled and prepared away from the audio thread. The finished program is handed to the processor, which switches at a block boundary with a 30 ms equal-power crossfade, keeps the transport position and the mixer state, and restarts the notes that should be sounding at that position. The old program is handed back and freed elsewhere. If the new code has an error, nothing is swapped: the last valid program keeps playing.
The registry
Engines, effects and patch nodes describe themselves: names, parameters, units, ranges,
defaults, presets, latency. This description — the registry — is the single source for three
things: the compiler validates your code against it, the inspectors of the app are built from
it, and the reference chapters of this manual are generated from it
(Scripts/gen-reference.sh; a test fails when they are out of date). A parameter cannot
exist in one place and not in the others.
Safety of a composition
A Sonata file is data, not a script with access to your machine. It can import modules and name audio files, both confined to its project. There is no file, network or process access in the language, loops are bounded and resources have quotas (Algorithmic composition). Opening a piece from someone else can make noise and nothing more — and the master limiter is on by default for that.
Where things are
| Part | Location |
|---|---|
| Shared definitions: exact time, diagnostics, Musical IR, DSP IR, registry types | crates/sonata-ir |
| Lexer, parser and formatter, semantics, compiler | crates/sonata-lexer, -parser, -semantics, -compiler |
| DSP building blocks, effects, analysis (FFT, loudness, pitch) | crates/sonata-dsp |
| Instrument engines | crates/sonata-instruments |
| Real-time engine, offline renderer and file formats | crates/sonata-runtime, crates/sonata-render |
| MIDI and MusicXML | crates/sonata-interop |
| Command line, C interface for the app | crates/sonata-cli, crates/sonata-ffi |
| The app | Apps/ORIXSonata, Packages/SonataUI, SonataBridge, SonataProject |
| Standard library, in Sonata | StandardLibrary/std |