Integration reference · [Satie documentation](/docs)

# SATIE portable core

An experimental C++17 runtime shared by native Godot and browser WebAssembly.
The current `satie.portable.stereo/1` profile runs realized sample loops, oneshots,
material-specific contacts, seeded take variation, host movement, listener
movement and gain/pitch controls. It is a working migration slice, **not a full
port of the existing Web Audio engine**.

The compiler uses SATIE's existing TypeScript parser and rejects unsupported
syntax. Native and web adapters execute the same C++ source. Playback needs no
SATIE account, agent, MCP connection or network request once assets are local.
MCP remains the authoring/asset-realization layer. Hosted MCP does not yet emit
this bundle or distribute native binaries.

## Read first

- Contract: binary layout, units, clocks, concurrency, ownership,
  errors, rendering laws and explicit limits.
- Patterns: coding decisions and primary-source references.
- Validation: exact checks, evidence and unverified claims.
- Godot demo: installation and game wiring.
- Migration: how this becomes the shared production renderer.

## Build and test the native core

Requires CMake >=3.20 and a C++17 compiler. No runtime dependencies.
Run these commands from the SATIE repository root:

```sh
cmake -S packages/satie-core -B .satie/core-debug -DCMAKE_BUILD_TYPE=Debug -DSATIE_SANITIZE=ON
cmake --build .satie/core-debug --parallel 4
ctest --test-dir .satie/core-debug --output-on-failure
npm run test:portable
npm run check:portable
```

Use a separate `-DSATIE_TSAN=ON` build for thread-race checks; do not combine
TSan and ASan. Use a Release build for `satie_benchmark`; sanitizer timings are
not meaningful real-time budgets. The native tests include a C translation unit,
allocation guard, malformed bundle mutations and real concurrent producers.

The test allocation guard supplies both sized and unsized C++17 delete forms,
so GCC's sized deallocation matches its malloc-backed allocation under ASan.
MSVC's intentional-padding diagnostic C4324 is scoped off only around the
cache-line-aligned SPSC queue; `/W4 /WX` remains enabled for the core.
Godot 4.5 CI imports with a one-second frame delay before shutdown to avoid
its [extension-documentation teardown race](https://github.com/godotengine/godot/issues/111048).
The subsequent lifecycle, real audio callback and PCM comparisons still run.

On the development Mac, AppleClang 21's default search missed the SDK's libc++
headers. The local build used
`-DCMAKE_CXX_FLAGS="-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1"`.
This is a machine-specific workaround, not a project toolchain requirement.

## Compile a scene

Every source needs `source_id` and exactly one of `at <host>` or `bed`.
Inputs are already-realized WAV assets. PCM16/float32 WAV with a canonical
16-byte format chunk is supported; point sounds must be mono. All asset files
share one sample rate. The CLI does not download, generate or normalize audio.

```satie
on contact_concrete concrete
  source_id left_contact
  at player
  volume 0.7to0.9

loop engine
  source_id engine
  at vehicle
  volume follow load 0to1 0.3to1
  pitch follow rpm 0to6000 0.5to2
```

Create `inputs.json` beside your audio files:

```json
{
  "seed": 7,
  "hosts": { "player": [0, 0, 0], "vehicle": [3, 0, 0] },
  "assets": {
    "concrete": ["concrete-1.wav", "concrete-2.wav"],
    "engine": ["engine.wav"]
  }
}
```

```sh
node --import tsx packages/satie-core/compiler/cli.ts scene.satie inputs.json output
```

The output is `scene.satp` (validated executable scene and PCM) and
`scene.manifest.json` (stable source names, host/event/control mappings, profile and
hashes). Asset paths must stay within the input directory, including through
symlinks. Commit the source, assets and manifest/bundle revision together in a real
game. Generated demonstration files are ignored because their generator is
tracked and reproducible.

Supported source heads are `loop <clip>`, `oneshot <clip>` and `on <event> <clip>`.
Supported properties are `source_id`, `at`, `bed`, `volume` and `pitch` (constant,
ascending random range, or `follow` binding). Realized variant pools live in the
input asset map. No `gen`, groups, entities, templates, `place`, autonomous timing,
SPL, reverb, HRTF, occlusion or other unlisted feature is silently approximated.
Unsupported programs fail before output files are written.

## Compile a composed scene (the scene profile)

A scene the MCP composed does not fit the first profile (it has dB levels, timed
oneshots, states, surface banks). Export it with `satie_export`, which writes
`scene.json` (`satie.placement/v1`) and downloads the takes; then:

```sh
node --import tsx packages/satie-core/compiler/placement-cli.ts \
  path/to/scene.json path/to/audio output [--rate 48000] [--seed 7]
```

`ffmpeg` must be on the path: takes are decoded, resampled to one rate and evened
to the runtime's clip loudness here. The output is `scene.satp` (`SATIEP02`) and
`scene.manifest.json` (`satie.portable.bundle/2`): names to indices for events,
signals, states and hosts, and `notRendered`, the list of what the scene asked for
that this profile does not execute. The compile refuses a scene that needs `when`
bands, `quiet` gates or `emit` chains unless `--allow-unrendered` is passed.

Hear it without an engine (the renderer is built with the core):

```sh
.satie/core-debug/satie_render_scene output/scene.satp scene.wav 30 [trace.satc]
```

It writes a 16-bit WAV and prints the level of every second, clipping, dropped
voices and rejected commands as JSON. `compiler/session.ts` (`PortableSession`)
builds a trace by name (`event`, `signal`, `state`, `moveHost`, `listener`) the
way an adapter drives the core; `tests/placement.test.ts` shows it.

Not in this profile: rooms and reverb, occlusion, HRTF, per-voice DSP, movement
paths, entities. See the contract for the format and the
semantics, and migration for what the profile decided.

## WebAssembly and AudioWorklet

Pinned verification toolchain: Emscripten 4.0.15. A normal `emsdk` installation is
sufficient. With `em++` on PATH:

```sh
node packages/satie-core/adapters/web/build.mjs .satie/portable-web
cp packages/satie-core/adapters/web/{runtime,processor,client}.mjs .satie/portable-web/
```

Or set `EMXX` to an explicit compiler path. The generated module includes its
Wasm bytes, has fixed 64 MiB memory and no filesystem. The web adapter caps input
bundles at 16 MiB. It runs without cross-origin isolation. Serve the four modules
from the same local/site origin; HTTPS or localhost is required for AudioWorklet.

```js
import { createSatieNode } from './client.mjs';
// Start this flow from the application's audio-enable gesture.
const context = new AudioContext();
await context.resume();
const node = await createSatieNode(context, './processor.mjs', bundleBytes, manifest.bundleSha256);
node.port.addEventListener('message', ({ data }) => {
  if (data.type === 'error') reportAudioError(data.message);
});
node.connect(context.destination);
// frame is SATIE's timeline, not AudioContext.currentTime's absolute origin.
node.port.postMessage({ type: 'command', command: {
  frame: 0, kind: 1, source: 0, sequence: 1, values: [1, 0, -2]
}});
// On teardown:
node.disconnect();
node.port.postMessage({ type: 'dispose' });
```

Initialization precedes connection. There is no production hot-reload protocol
or automatic clock calibration yet. The standalone adapter is not installed into
the existing SATIE web application.

## The synthesizer

`src/synth.cpp` (interface: `include/satie/synth.h`) is Satie's own synthesizer for native targets. It plays a
synthesizer program: a flat list of numbers that `src/engine/synth/program.ts` compiles from a patch and its
instruments (an instrument is a small graph of oscillators, noise, mixes, delays and resonators, as data). The
TypeScript engine `src/engine/synth/vm.ts` plays the same program in browsers, on the server and in a Lens; the
two do the same arithmetic in the same order. `docs/wiki/engine/synth.md` has the model.

```sh
cmake -S packages/satie-core -B build/portable -DCMAKE_BUILD_TYPE=Release
cmake --build build/portable --target satie_synth_render
SATIE_SYNTH_RENDER=build/portable/satie_synth_render npm run test:portable
```

The test renders four patches through both engines with every control moved while they play and compares the
samples (identical on the machine it was written on; 1e-6 allowed for another math library), then feeds the C++
engine a thousand programs with one number changed to something hostile: each is played or refused, none
crashes. Run it under `-DSATIE_SANITIZE=ON` after changing how a program is read. A program is untrusted:
creation checks every count, index and number, and rendering never allocates.

The interface is six functions: `satie_synth_create(program, count, sample_rate, channels)`,
`satie_synth_render(synth, left, right, frames)`, `satie_synth_set(synth, control, value)` (pitch, brightness,
tempo, loudness evening, quality; safe from another thread), `satie_synth_destroy`, and
`satie_synth_reset` and `satie_synth_program_version`. It is in the static and the shared library.

The core uses it itself (ABI 6): `satie_attach_synth` makes a loop source of a compiled scene take its samples
from a synthesizer instead of its take, and `satie_synth_follow` binds its brightness and tempo. The scene
compiler writes what to attach into the manifest's `synthList`; the Unity adapter attaches it. `docs/contract.md`
has the rules. `tests/synth-scene.test.ts` covers it (set `SATIE_SYNTH_SCENE` to the built `satie_synth_scene`,
and `SATIE_CORE_LIBRARY` to a shared library for the Unity adapter's part).

## Repository layout

```text
include/satie/core.h       C ABI; opaque ownership and explicit results
src/core.cpp              bundle validation, execution, rendering
src/spsc_queue.hpp         bounded single-producer/single-consumer queue
compiler/                 canonical-parser compiler and local CLI; placement.ts and
                          placement-cli.ts (scene profile), session.ts (host by name)
adapters/godot/            native AudioStream / AudioStreamPlayback extension
adapters/web/              Wasm build, runtime wrapper and AudioWorklet
tests/                   PCM, compiler, sanitizer and host conformance; render_scene.cpp
                          (offline WAV and level statistics)
```

Native binaries, SDKs, generated audio and build products are not vendored or
published by this change. Existing repository licensing governs SATIE code;
godot-cpp has its own MIT license and is downloaded separately. Test audio is
synthesized locally from the checked-in generator, not taken from a third-party
recording library.

## Malformed-bundle fuzzing

With Clang/libFuzzer installed, build a separate sanitizer target:

```sh
CC=clang CXX=clang++ cmake -S packages/satie-core -B .satie/core-fuzz \
  -DCMAKE_BUILD_TYPE=Debug -DSATIE_BUILD_TESTS=OFF -DSATIE_FUZZ=ON
cmake --build .satie/core-fuzz --target satie_fuzz --parallel 4
mkdir -p .satie/core-corpus
cp examples/godot-portable/audio/scene.satp .satie/core-corpus/demo
python3 packages/satie-core/tests/run_fuzz.py .satie/core-fuzz/satie_fuzz .satie/core-corpus
```

The wrapper bounds sanitizer startup as well as mutation time. Keep generated
corpora and failure artifacts in `.satie/`; preserve a minimized regression fixture
with a test if a failure is found.

## Physics-mediated sound (ABI 7, 2026-11-18)

A trigger can carry its own level and the body it comes from (`SATIE_TRIGGER_GAIN`), a host can
report an occlusion it measured (`SATIE_OCCLUSION`), and the contact law of the web runtime
(`ContactAudio`) is in the library as `satie/contacts.h`: register bodies, report impacts,
touching pairs and footsteps, call update once per physics step, drain the decisions. Its numbers
are `src/contact_law.gen.hpp`, generated from `src/engine/integration/ContactMaterials.ts`:

    npx tsx scripts/export-contact-law.mts        # after changing the table
    npx tsx scripts/unity-plugins.mts --local     # then rebuild this machine's Unity library

`tests/contacts.test.ts` holds the C++ layer to the TypeScript one over one recorded sequence of
reports; build `satie_contacts_trace` and set `SATIE_CONTACTS_TRACE` to cross into the core. The
contract is in `docs/contract.md`, the decision in the company ADR-0013 (proposed).
