# Host Maru modules in a web DAW

> Put Maru instruments and effects on the tracks of a browser DAW: choose an integration path, host modules in your own AudioContext, schedule notes and automation, save projects and bounce offline.

Canonical: https://maru.audio/docs/host-modules-in-a-web-daw
Documentation index: https://maru.audio/llms.txt

A web DAW can host Maru instruments and effects on its own tracks. Each module
runs as an AudioWorklet node in your `AudioContext`, plays the notes and
automation your timeline schedules on the audio clock, and returns its state
for your project file. This guide is for the engineer who builds that
integration: which path to choose, who owns what, a walkthrough you can follow
step by step, and what to check before your users rely on it.

> **In the Help Center:** [DAWs and audio software makers](https://maru.audio/help/daw-and-audio-software-makers.md) for choosing an integration and starting a pilot.

## Choose an integration path

| Path | What your users get | Where the module's audio runs | Processes your tracks |
| --- | --- | --- | --- |
| Embed a published module's player | The module's own player page in an iframe, with its face, presets and playback controls | Inside the frame, on Maru's site | No |
| Host modules with the module player | Instruments on MIDI tracks and effects as inserts, inside your mixer | Your `AudioContext` | Yes |

**Embed a player** to let people browse and audition modules. Copy the iframe
from a module page's **Embed this module** option, as described in
[Embed instruments, effects and racks](https://maru.audio/help/embed-audio-on-your-website.md).
The frame plays with its own audio and its own controls. Audio cannot cross
from your page into the frame, so an embedded player cannot process a track,
join your mixer or take part in an export.

**Host with the module player** to put modules on tracks. `createModulePlayer`
from `maruaudio/module-player/react` verifies a module's published Release,
runs its Program in your `AudioContext` and gives you a controller for
notes, parameters, state and disposal. The rest of this guide covers that path.
[Host a module in React](https://maru.audio/docs/module-player-react.md) is the API reference.

Maru also has deeper routes that are not generally available: a headless SDK
host for a DAW that wires several modules into one device or connects their
individual audio buses, and adapters to standard web plug-in formats such as
WAM 2 and WebCLAP. If your DAW can only load one of those formats, or renders
every processor inside its own engine callback rather than as Web Audio nodes,
say so when you contact us. The module player connects as nodes in your
graph; it has no buffer-level call for running a module inside your own
render loop.

For VST3, Audio Unit and CLAP plug-ins, see
[Native plug-ins and web DAWs](https://maru.audio/docs/native-plugins-and-web-daws.md).

## Who owns what

| Your DAW owns | Maru owns |
| --- | --- |
| The `AudioContext`, its sample rate and its lifetime | Verifying the Release and each file it loads |
| Tracks, clip sources, faders, the master bus and routing | Selecting and running the module's Program in an AudioWorklet on your context |
| The clock, tempo, transport and lookahead scheduling | Applying notes and parameter writes at their scheduled frame |
| Automation lanes, normalized-to-engine conversion and gesture recording | The parameter schema: ranges, units, steps, tapers and stable paths |
| The project file, pinning each Release by digest, and storing module state | Factory presets and the module's state format |
| Delay compensation from the latency the module reports | Reporting latency, and shutting each instance down cleanly |

The module player feeds the module's first declared main audio input and
monitors its first declared main output. Sidechain and auxiliary buses are not
connected through it.

## Before you start

Build each module with `maru module build` and serve its web Release
directory (`release.json`, `module.json`, the Programs and resources) from
your own origin, next to your app. Keep the directory intact: the player
verifies each file it loads against the Release. A build made with
`--development` carries no qualification evidence, so it runs only when you
pass an explicit `prequalification` policy, and the host then reports itself as
unqualified.
[Check, build and export](https://maru.audio/docs/export.md) describes the build.

The SDK and framework are source available with all rights reserved, and are
not published under a general open-source license. Shipping them in your
product, including an evaluation build, needs written terms; see
[Licensing](https://maru.audio/docs/licensing.md).

## Walk through an integration

The steps below follow a small reference DAW: one instrument track and two
audio tracks that carry the same effect, played live, saved, reopened and
bounced offline. The snippets are shortened from it. Maru can share the
complete reference integration with teams starting a pilot.

### 1. Inspect a Release before running it

A plug-in browser can show what a module needs before anything runs. Fetch
`release.json`, record the SHA-256 of its exact bytes, validate it, and read
the declaration in `module.json` beside it:

```ts
import { validateRelease } from "maruaudio/contracts"
import type { ModulePlayerDefinition } from "maruaudio/module-player/react"

async function sha256Hex(bytes: ArrayBuffer) {
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))
  return [...digest].map((byte) => byte.toString(16).padStart(2, "0")).join("")
}

export async function inspectModule(releaseUrl: string) {
  const url = new URL(releaseUrl, location.href)
  const bytes = await (await fetch(url)).arrayBuffer()
  const checked = validateRelease(JSON.parse(new TextDecoder().decode(bytes)))
  if (!checked.ok || !checked.release)
    throw new Error(checked.issues.map((issue) => issue.message).join("; "))
  const release = checked.release
  const definition: ModulePlayerDefinition = await (await fetch(new URL("module.json", url))).json()
  if (definition.id !== release.module.id) throw new Error("module.json describes another module")
  return { url: url.href, releaseSha256: await sha256Hex(bytes), release, definition }
}
```

The Release gives the module's identity and version, its runtime line
(`release.requires.runtime`), engine ABI, required host capabilities, the
Programs it can run and its qualification evidence. The declaration gives its
ports, parameters with ranges and units, and factory presets. Nothing is
activated. Refuse an instrument with no MIDI input port, or an insert with no
audio input port, before you create a track for it.

### 2. Host an insert and an instrument in your AudioContext

Create one player per instance. Pass your own context, your track's channel
strip as the destination, and the digest you recorded:

```ts
import { createModulePlayer } from "maruaudio/module-player/react"

type InspectedModule = Awaited<ReturnType<typeof inspectModule>>

async function hostModule(context: BaseAudioContext, module: InspectedModule, strip: AudioNode) {
  const player = createModulePlayer(
    { definition: module.definition, releaseUrl: module.url, sha256: module.releaseSha256 },
    {
      context,            // yours: the player never closes or suspends it
      destination: strip, // the track's channel strip, not the speakers
      monitorLevel: 1,    // the player's output gain defaults to 0.8
      onError: (error) => reportTrackError(module, error),
    },
  )
  await player.start()
  return player
}

const synth = await hostModule(context, instrument, synthStrip)
const guitar = await hostModule(context, effect, guitarStrip)

const clip = context.createBufferSource()
clip.buffer = guitarRecording
const disconnectClip = guitar.connectInput(clip)
clip.start(startTime)
```

Pass `monitorLevel: 1` for an insert: without it the player's own output gain
of 0.8 sits between the module and your fader. On a realtime context, call
`start()` from a user gesture; it resumes the context. `connectInput` returns
a function that removes only that connection, and every node you connect must
belong to the same context. `onError` reports a failure after activation; the
player stops that instance, and the rest of your project keeps playing.

### 3. Schedule notes and automation

Schedule from your timeline a short window ahead of the audio clock, the usual
Web Audio lookahead pattern. Notes go through the player's session with a time
and a duration, so the note-off is scheduled on the audio clock too.
Velocity runs from 0 to 1. Automation goes through `setParam` with `{ when }`:

```ts
const LOOKAHEAD = 0.15 // seconds of timeline handed to the engine at a time

function dispatchUntil(horizon: number) {
  for (const event of timeline.eventsBefore(horizon)) {
    // `timeline` stands for your DAW's own arrangement.
    if (event.kind === "note")
      synth.session.triggerNote(event.note, {
        velocity: event.velocity, when: event.time, duration: event.length, source: "host",
      })
    else guitar.setParam(event.path, event.value, { when: event.time })
  }
}

setInterval(() => dispatchUntil(context.currentTime + LOOKAHEAD), 25)
```

The engine applies each timed write at its frame. The player's value mirror
(`getParam`, snapshots, the face and `saveState()`) takes the value once the
render clock reaches it. Stop, panic and `dispose()` discard pending writes
along with the engine's queue; selecting a preset or restoring state leaves
them scheduled. A timed write needs a started player.

Each Program's queue of scheduled events is bounded by the event capacity it
declares, and notes and parameter writes share it. Feed a window at a time, as
above, rather than a whole arrangement at once. The reference DAW samples an
automation lane every 256 frames and sends each point as a timed write.

Parameter values are engine units from the schema: hertz, decibels, an enum's
option index, 0 or 1 for a switch. Key lanes by the parameter's `path`, which
is its stable automation identity. If your lanes store positions from 0 to 1,
`normalize` and `denormalize` from `maruaudio/contracts` apply the range, step
and taper of a numeric parameter; for an enum or a switch, send the option
index or 0/1. To record automation from a face, use the `onParamEdit` option,
which reports when a gesture begins and ends.

### 4. Save and reopen a project

Store the Release address, its digest and the module's state with each track:

```ts
const saved = {
  releaseUrl: module.url,
  releaseSha256: module.releaseSha256,
  moduleState: await player.saveState(),
}

// Reopening, in a fresh page:
const module = await inspectModule(saved.releaseUrl)
if (module.releaseSha256 !== saved.releaseSha256)
  throw new Error("This track's module changed since the project was saved")
const player = await hostModule(context, module, strip)
await player.restoreState(saved.moduleState)
```

A pinned load also refuses a Release whose bytes do not match the digest.
`saveState()` returns the module ID and its saved parameter values.
`saveState({ includeProcessor: true })` adds the Program's opaque state as a
`Uint8Array` when the Program supports it; encode those bytes for your project
file, and expect `restoreState` to refuse them for a different Program. For a
module with live-only (transient) controls, `includeProcessor` is refused, so
save its parameter values alone.

### 5. Run two instances

Two players created from the same Release are independent: separate nodes,
event queues, settings and state. The reference DAW runs the same effect on two
tracks, automating one and leaving the other fixed:

```ts
const lead = await hostModule(context, effect, leadStrip)
const double = await hostModule(context, effect, doubleStrip)
double.setParam("drive", 0.4)
```

To duplicate a track, host the same Release again and restore the saved state
into the new player.

### 6. Dispose

Call `dispose()` for every instance you remove, and for all of them when the
project closes:

```ts
await Promise.all(players.map((player) => player.dispose()))
```

Disposal releases the module's nodes and connections and is safe to call more
than once. A disposed player refuses to start again. Your context, faders and
master bus remain yours to disconnect or close. Closing or hiding a module's
editor is not disposal: audio, notes and tails keep running without the face.

### 7. Bounce offline

Host the same Releases with the same state on an `OfflineAudioContext`. The
player does not resume an offline context; it renders when you call
`startRendering()`. Schedule the first window before rendering, and the rest at
render-time `suspend()` points instead of on a timer, because the bounded queue
cannot hold a whole arrangement:

```ts
const offline = new OfflineAudioContext({ numberOfChannels: 2, length: seconds * sampleRate, sampleRate })
// Build the same tracks on `offline`, restore their state and start their clips, then:
const quantum = 128 / sampleRate
for (let t = 0.1; t < seconds; t += 0.1)
  void offline.suspend(Math.floor(t / quantum) * quantum).then(() => {
    dispatchUntil(offline.currentTime + LOOKAHEAD)
    return offline.resume()
  })
dispatchUntil(offline.currentTime + LOOKAHEAD)
await new Promise((resolve) => setTimeout(resolve, 0)) // connectInput attaches clips asynchronously
const rendered = await offline.startRendering()
```

After the render, each player's values show the final automation. Level
meters read analysers on the animation frame, so they mean nothing during an
offline render. A Graph module whose input changes when `connectInput`
attaches a source needs a running render clock for that change, so it refuses
the connection on an offline or suspended context. Compare a bounce with live
playback of the same session before you offer export to your users.

## Inspect the running engine

After `start()`, `player.getSnapshot().audio.host` is the engine host the
player activated. Read it for display and diagnostics: `backend` (`js` or
`wasm`), `artifactId` and `artifactSha256` for the exact Program,
`qualificationStatus` and `activationPurpose`, and `latencyFrames`. Send notes
and parameters through the player, never to that host directly, so the
player's state and the face stay in step. Latency is fixed at activation; a
DAW with delay compensation reads `latencyFrames` and delays its other tracks.

## Serve modules to the browser

- **Secure context.** AudioWorklet needs HTTPS or `localhost`. Pages opened
  from `file://` do not work.
- **CORS.** The player fetches the Release and its files with `fetch`. If they
  come from another origin, every file needs CORS headers.
- **Content Security Policy.** Programs load into the AudioWorklet from `blob:`
  URLs, and WebAssembly Programs compile in the page. Allow
  `script-src blob: 'wasm-unsafe-eval'`, and `connect-src` for the origin that
  serves the Releases. Maru's own module host pages use
  `script-src 'self' blob: 'wasm-unsafe-eval'` and `worker-src 'self' blob:`.
- **Content types.** Serve `release.json` as `application/json`. A Program's
  media type comes from its record in the Release, so your server's
  `Content-Type` does not decide how it runs.
- **Cross-origin isolation.** Not needed: the player uses no
  `SharedArrayBuffer`. If your page is cross-origin isolated for its own
  reasons, every module file served from another origin needs CORS, and
  `Cross-Origin-Resource-Policy: cross-origin` where your policy requires it.

## Trust the code you host

With the module player, module code runs inside your page. Its Program runs in
your context's `AudioWorkletGlobalScope`, which every module and worklet in that
context shares, and a face rendered with `ModulePlayerFace` runs as part of
your document with your origin's authority. A digest proves which bytes you
loaded, not that they are safe.

Host only Releases you have reviewed and trust, pin each by its digest, and
store that digest in the project rather than a bare URL or module name. An
embedded player page runs on Maru's site inside its own frame, which keeps
modules you have not reviewed out of your page.

## Test before you ship

Measure rendered audio from the real engine in your DAW; reading code or
seeing a module load does not establish that it sounds right. Report listening
separately from measurements. At minimum, check:

- **State round trip.** Save, close the page, reopen in a fresh page, and
  compare restored values and rendered level. A changed or missing Release
  must fail visibly, never load a substitute.
- **Automation.** A scheduled change lands at its time in the rendered audio,
  and the final value reaches the player's state.
- **Two instances.** The same module on two tracks with different settings
  renders differently on the same input, and changing one leaves the other
  unchanged.
- **Editor closed.** Notes, tails and automation continue while the face is
  unmounted.
- **Offline against live.** A bounce of a session matches its live playback:
  note onsets at their frames, the same levels, finite and unclipped output.
- **Disposal.** Repeated create and dispose cycles leave no connected nodes,
  and your context stays open.
- **Sample rates.** Run the checks at 44.1 and 48 kHz.

## Start a pilot

[Contact Maru](https://maru.audio/contact) with your DAW, the browsers you support, whether
plug-ins run as Web Audio nodes in your context or inside your own engine, how
you export, where you store project state and assets, and the instrument or
effect you would start with. We will say which parts are available for your
host, what has been tested and what a guided integration would cover.
