FreestyleDevelopers Open the app

Realtime: sessions & audio

REST covers reads and edits. Two things need a live channel: server push (other people's edits, the transport clock) and audio. Push goes over an interactive-session WebSocket on the Freestyle origin. Audio goes over WebRTC directly between the Mozart engine and the client. Media never passes through the REST API.

Interactive sessions (WebSocket push)

An interactive session is a WebSocket that carries commands and their acknowledgements, a gap-free stream of state patches with revisions, and the transport clock. The browser never sees your OAuth token: your backend opens the session and hands the browser a short-lived, single-use ticket.

  1. Your backend opens the session. POST /api/v1/projects/{project_id}/interactive-sessions (scope daw:read, viewer or above) with origin = the browser origin that will connect, mode = auto (default), write or read, and an optional track_id. auto gives an editor with daw:write a write session and everyone else a read-only one. The answer (201) has session_id, websocket_url, session_ticket, expires_at, revision, sample_rate and the clock and monitoring details.
  2. Hand only session_ticket to the browser. The ticket is signed, single use, valid for 120 s and bound to the user, project, session, scopes, mode and browser Origin. A ticket issued without origin refuses browser connections (server-side clients only). Allowed origins are your OAuth client's redirect-URI origins and its allowed_origins, plus origins Freestyle allowlists.
  3. The browser connects. It opens websocket_url (/api/ws/mcp-session) with no credential in the URL, and sends {"type": "auth", "ticket": "…"} as its first frame within 10 s.
  4. The server answers welcome (epoch, revision, limits, session expiry, server clocks) and then a full snapshot of the project state, unless the auth frame asked to resume from an epoch and revision.
  5. Close it when the editor closes: {"type": "close"} on the socket, or DELETE /api/v1/interactive-sessions/{session_id} from your backend. Its socket closes within seconds and its tickets stop working. Closing a closed session is not an error.
# backend
curl -X POST https://freestyle.audio/api/v1/projects/<project_id>/interactive-sessions \
  -H "Authorization: Bearer $FREESTYLE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"origin": "https://daw.example", "mode": "auto"}'

// browser
const ws = new WebSocket(session.websocket_url);
ws.onopen = () => ws.send(JSON.stringify({type: "auth", ticket: session.session_ticket}));
ws.onmessage = (event) => handle(JSON.parse(event.data));

What flows over the socket

  • Commands (write sessions): {"type": "command", "id", "action", "arguments", "base_revision"?}. A mutating command commits one revision: its state_patch arrives just before {"type": "ack", "id", "status": "applied", "revision"}. The ack of a mix command (fader, pan, mute, solo, routing, apply_mix) also carries mix_revision: Mozart's mix revision right after your write, ready to send as If-Match: "mix-<n>" / expected_mix_revision on the next REST write without re-reading the mix (a gesture's gesture_committed frame carries it too). Failures are reject frames with a code. The full ack shape: {"type": "ack", "id", "status", "revision", "action"?, "result"?, "mix_revision"?, "rebased_from"?, "coalesced"?, "gesture_id"?, "into"?, "duplicate"?}. status is applied (the command ran; revision is the channel revision it committed, result the action's bounded reply), pending (the same id is still running), coalesced (a newer command on the same control replaced it: into names it) or accepted (a gesture started; gesture_id). mix_revision is present only on mix commands. rebased_from is your base_revision when the channel had moved past it; coalesced lists earlier command ids folded into this one; duplicate: true marks a replayed answer to a repeated id. Acks never carry seq: seq numbers only the transport_clock frames (and mixer_meters on the meter channel), so match acks by id. Use the socket for high-rate gestures (fader drags, scrubbing); use REST for discrete edits that need an Idempotency-Key or an If-Match.
  • State patches for every change, including changes made by other editors, the Studio and REST calls, each with the new revision. On a gap, send resubscribe; the server replays or sends a new snapshot.
  • Transport clock frames while playing (sample frame, sample rate, playing, loop, bar/beat/tick, tempo segment, producer_latency_seconds), up to 15 Hz. Turn them off with {"type": "subscribe", "clock": false} and poll getTransportClock instead if you prefer.
  • Mix changes from anyone. Every transport_clock frame and snapshot carries Mozart's mix_revision. A mix change your socket's own commands did not cause (a Studio user's fader, mute, solo or routing move, another agent, a session reload) arrives as resync_required with source: "mix" while the clock is subscribed. This is best effort; for writes that must not overwrite a human, read getEngineMix and send its ETag as If-Match (see Mixing safely). Without a socket, long-poll waitEngineMix.
  • Renewal: before a ticket expires, {"type": "renew"} re-checks the grant and role, extends the session and returns a resume_ticket for the next reconnect. After a lost socket you can also call openInteractiveSession again with session_id.

The protocol is the same one MCP agents use. The full frame reference (command fields, reject codes, replay, clock fields, close codes and per-user and per-project session caps) is in Interactive session channel; the budgets are on Rate limits & errors.

Live audio monitoring (WebRTC)

To hear the project as it plays, with every plugin, connect a receive-only WebRTC peer to the project's live Mozart session. Audio is an Opus stream that flows engine → client directly (peer to peer when possible, or through Freestyle's TURN relay on restrictive networks such as cellular). All three calls need audio:listen.

  1. POST /api/v1/projects/{project_id}/monitor (editor) opens the live session (the server picks the engine) and returns session plus short-lived turnCredentials (urls, username, credential, expiresAt, about 10 minutes) bound to that engine.
  2. Create an RTCPeerConnection with those ICE servers and a receive-only audio transceiver, create an offer and set it as the local description.
  3. POST /api/v1/projects/{project_id}/monitor/offer with {"sdp": "…", "turn_credentials": {…}, "client_id": "…"}. Apply the returned answer ({type, sdp}) as the remote description and play the remote track in an <audio> element. The answer also carries peerGrant: "write" when the token has daw:write and the user is the project's owner or an editor, otherwise "read", and peerGrantExpiresAt (unix seconds). See Fast input on the monitoring peer.
  4. Before expiresAt, refresh relay credentials with GET /api/v1/realtime/turn-credentials?mozart_origin=<session.dawBaseUrl>.
  5. When you are done, DELETE /api/v1/projects/{project_id}/monitor?client_id=… closes your peer at once (audio and data channels). The project's live session stays loaded for the Studio and other listeners. The reply's closed is the engine's answer: true when it tore your peer down, false when it had no peer with that client_id (already gone, never opened, or the project moved to another engine since your offer), which is not an error. 502 webrtc_close_failed means the engine could not be reached and the peer may still be up: retry.

Any project the Studio can open can be monitored, including one with lanes but no recordings yet and a brand-new empty project: the engine opens an empty session and you hear whatever the project holds as it changes. Pick your own client_id and keep it: it is scoped to your user (it can never address another member's peer), a new offer with the same id replaces your old peer, and the stop and quality calls take it.

PATCH /api/v1/projects/{project_id}/monitor with {"client_id", "target_bitrate_bps": 48000–510000, "packet_loss_pct": 0–100} changes your peer's Opus bitrate live and reports your receiver's loss (in-band FEC turns on with loss), like the Studio's adaptive quality. quality_profile and low_latency are fixed per peer: send a new offer with the same client_id to change them.

Use a standard WebRTC stack (browsers, libdatachannel, Pion, aiortc). The engine answers as the DTLS server, so your side is the DTLS client and its in-band data channels normally take even stream ids; engines from 2026-11-13 also accept in-band channels on odd ids, which aiortc picks. The negotiated channels below always use the fixed ids 100 and 102.

const mon = await api("POST", `/projects/${projectId}/monitor`, {});
const t = mon.turnCredentials;
const pc = new RTCPeerConnection({iceServers: t ? [{urls: t.urls, username: t.username, credential: t.credential}] : []});
pc.addTransceiver("audio", {direction: "recvonly"});
pc.ontrack = (e) => { audioEl.srcObject = e.streams[0]; };
await pc.setLocalDescription(await pc.createOffer());
const res = await api("POST", `/projects/${projectId}/monitor/offer`, {sdp: pc.localDescription.sdp, turn_credentials: t});
await pc.setRemoteDescription({type: res.answer.type, sdp: res.answer.sdp});

Opening the monitor without a wait

By default monitor/offer does not answer at once: the engine holds its answer until it has a relay-capable ICE candidate (usually 1–2 s, at most about 4 s), so the peer also connects on networks that block direct UDP, such as cellular and strict firewalls.

Trickle ICE (recommended). Send the offer with "trickle": true. The engine then answers as soon as it has a server-reflexive candidate (typically a few hundred milliseconds) and says so with trickle: true in the reply. Its later candidates, in particular the TURN relay candidate that restrictive networks need, come from GET /api/v1/projects/{project_id}/monitor/candidates?client_id=…&after=…&wait_ms=…: it long-polls up to wait_ms (default 2000, max 3000) and returns {candidates: [{candidate, sdpMid}], next, complete}. Add each candidate with pc.addIceCandidate(), pass next back as after, and stop once complete is true or the peer is connected. A reply with trickle: false (an engine that does not support it yet) carries every candidate already: nothing to fetch.

const res = await api("POST", `/projects/${projectId}/monitor/offer`,
  {sdp: pc.localDescription.sdp, turn_credentials: t, client_id: clientId, trickle: true});
await pc.setRemoteDescription({type: res.answer.type, sdp: res.answer.sdp});
if (res.trickle) (async () => {
  let after = 0;
  while (pc.connectionState !== "connected" && pc.connectionState !== "closed") {
    const c = await api("GET", `/projects/${projectId}/monitor/candidates?client_id=${clientId}&after=${after}&wait_ms=2000`);
    for (const cand of c.candidates) await pc.addIceCandidate(cand);
    after = c.next;
    if (c.complete) break;
  }
})();

Plan for the remaining setup time instead of putting it in front of the user:

  • Start early. Call startAudioMonitor when the project opens, not when the user first presses play or a key. Its answer already carries turnCredentials; getTurnCredentials is only for refreshing them later.
  • Build the peer in parallel. While startAudioMonitor is in flight, create the RTCPeerConnection, the receive-only transceiver and the data channels. When it returns, add the ICE servers with pc.setConfiguration({iceServers: …}), create the offer and send it at once.
  • Keep one peer. Open one monitoring peer per project and reuse it across your views (editor, mixer, instrument, plug-in editor) instead of one per view. Send a new offer with the same client_id only to renew it or to change quality_profile / low_latency.
  • Do not drop the first input. Until mozart-control is open, send the first notes through REST (sendEngineMidi, play) or queue them and send them from the channel's onopen. See Instrument notes and pad samples.

The engine clock on the monitoring peer

Once mozart-control is open (create it before the offer, as in Fast input), the engine pushes {"type": "engine_clock", …} on it every 100 ms, playing or stopped, with no request from you. This is the clock the Studio runs on. It carries every getTransportClock field (position_seconds, position_samples, is_playing, sample_rate, bar/beat/tick, tempo_segment, loop_*, recording, producer_latency_seconds, mix_revision) plus project_id, a per-peer seq, server_sent_ms and rtp_sync for your audio stream. Read peers get it too. Polling getTransportClock through REST or using the socket's transport_clock (up to 15 Hz) adds a hop through Freestyle's backend, so prefer the push when you have a peer.

Drawing a playhead that matches what you hear

The engine clock is the write head: the sample the engine is producing now. What the listener hears is older. The exact way, which the Studio uses: engine_clock.rtp_sync (when ok) says which RTP timestamp carries the write head, {rtp_at_write_head, write_head_position_samples, clock_rate}. RTCRtpReceiver.getSynchronizationSources() gives the RTP timestamp your receiver is playing out now, so the heard position is write_head_position_samples − (rtp_at_write_head − playing_rtp) samples (RTP timestamps are 32-bit and wrap; take the signed difference). No latency model is needed.

Without rtp_sync (REST or socket clock only), estimate instead: the heard position is older by the engine's own buffering, producer_latency_seconds (which includes the latency of any master-bus inserts, see Master effects), plus your WebRTC jitter buffer. Read jitterBufferDelay / jitterBufferEmittedCount from RTCRtpReceiver.getStats() every 100 ms, smooth it, and draw the playhead at engine position + elapsed − producer_latency_seconds − jitter delay.

When the user scrubs, call seek only: the transport keeps playing at the new position and the audio stream stays steady. Do not stop and restart playback for a scrub.

Live mixer meters

The monitoring peer can also receive the mixer's peak meters. They are lossy telemetry over WebRTC data channels, separate from the revision stream, and the engine only sends them to a peer that subscribed. Opening a channel does not subscribe you.

  1. Before you create the offer, open two data channels on the same RTCPeerConnection: mozart-control (ordered) and mozart-meters with {ordered: false, maxRetransmits: 0}.
  2. Once mozart-meters is open, send {"type": "mixer_meters_subscribe", "persistent": true} on it. Frames then arrive on mozart-meters at 20 Hz until you send {"type": "mixer_meters_subscribe", "ttl_ms": 0} or the channel closes.
  3. For a lease that ends by itself instead, send {"type": "mixer_meters_subscribe", "ttl_ms": 4000} (at most 10000) and repeat it about every 2 s while you want meters. This is what the Studio's mixer does. You can send either form on mozart-control instead.
const meters = pc.createDataChannel("mozart-meters", {ordered: false, maxRetransmits: 0});
pc.createDataChannel("mozart-control");
// … create the offer and POST /monitor/offer as above …
meters.onopen = () => meters.send(JSON.stringify({type: "mixer_meters_subscribe", persistent: true}));
meters.onmessage = (e) => {
  const f = JSON.parse(e.data);   // {type: "mixer_meters", project_id, seq, server_sent_ms, master, buses, tracks}
  if (f.type !== "mixer_meters") return;
  for (const [engineId, laneId, peak, live] of f.tracks) { /* draw lane laneId at peak */ }
};

Each frame is {type: "mixer_meters", project_id, seq, server_sent_ms, master, buses: {busId: peak}, tracks: [[engine_id, lane_id, peak, live]]}. Peaks are linear (1.0 = full scale) and rounded to 3 decimals. live is 1 for a lane that is recording or receiving a live voice. Frames keep coming while the transport is stopped (with decaying or zero peaks). If your link falls behind, the engine drops frames rather than queueing them, so watch seq for gaps and do not treat a gap as an error. Meters need the same project access as the monitor. On a peer opened with a user's own engine credentials they also need that account's Pro access.

Live plug-in editor frames

The monitoring peer can also receive an open plug-in editor's GUI as a stream of JPEG frames, pushed by the engine with no HTTP round trip per frame. This is the low-latency alternative to polling getPluginEditorFrame. Open the editor first with openPluginEditor; send input on the mozart-editor channel of the same peer (see Fast input), or over REST (sendPluginEditorPointer and friends).

  1. Before you create the offer, add the frame channel to the same RTCPeerConnection. Both ends create it out of band, so it must be {negotiated: true, id: 102, ordered: false} with the label mozart-editor-frames.
  2. Once it is open, send {"type": "editor.subscribe", "lane_id": "<lane id>", "plugin_index": 0} on it. Optional fields: max_width (64–4096, default 1280; 640 at most with relay), fps (the most frames per second you want, 1–30, default 12; 5 at most with relay), format (jpeg, the default, or png) and relay: true when your selected ICE candidate pair goes through TURN. You can name the engine's track_id instead of lane_id.
  3. The engine answers with a text message {"type": "editor.state", "state": "subscribed", "lane_id", "track_id", "plugin_index", "max_width", "fps"}. Every editor.state message (subscribed and errors) goes to the peer's mozart-editor channel (id 100) when that channel is open, whichever channel the subscribe came in on; only a peer that opened the frames channel without mozart-editor gets it on the frames channel. Listen on both if you open both. Problems arrive as {"type": "editor.state", "state": "error", "code", "message"}, for example lane_not_loaded, invalid_target, project_access_denied, editor_not_open or capture_timeout. After an error the engine keeps retrying with back-off until the editor is open again.
  4. Frames arrive as binary messages (below). The subscription lasts until you send {"type": "editor.unsubscribe", "lane_id", "plugin_index"} (no reply) or the channel closes. A peer has one subscription; a new editor.subscribe replaces it.

Each frame is split into chunks of at most 16 KB. Every chunk starts with a 12-byte header, big-endian:

BytesTypeField
0–3uint32frame id (increases per frame sent on this peer)
4–5uint16chunk index
6–7uint16chunk count
8–11uint32revision: the first 8 hex digits of the frame's X-Editor-Revision

Chunk 0 then carries 11 bytes of metadata: bytes 12–15 engine track id (uint32), 16–17 plugin index (uint16), 18–19 width and 20–21 height in pixels (uint16), 22 format (0 = JPEG, 1 = PNG). The image bytes follow the header (and, in chunk 0, the metadata). The channel is unordered: collect chunks by frame id and, once all chunk count chunks are in, join them in chunk-index order. Drop partial frames older than the newest complete one.

const frames = pc.createDataChannel("mozart-editor-frames", {negotiated: true, id: 102, ordered: false});
frames.binaryType = "arraybuffer";
// … create the offer and POST /monitor/offer as above, then openPluginEditor …
frames.onopen = () => frames.send(JSON.stringify({type: "editor.subscribe", lane_id: laneId, plugin_index: 0, max_width: 640, fps: 30}));
const parts = new Map();
frames.onmessage = (e) => {
  if (typeof e.data === "string") { const s = JSON.parse(e.data); /* editor.state */ return; }
  const v = new DataView(e.data);
  const id = v.getUint32(0), index = v.getUint16(4), count = v.getUint16(6);
  const f = parts.get(id) || {chunks: new Array(count), got: 0};
  let offset = 12;
  if (index === 0) { f.width = v.getUint16(18); f.height = v.getUint16(20); f.type = v.getUint8(22) ? "image/png" : "image/jpeg"; offset = 23; }
  if (!f.chunks[index]) { f.chunks[index] = e.data.slice(offset); f.got++; }
  parts.set(id, f);
  if (f.got === count) { parts.delete(id); show(new Blob(f.chunks, {type: f.type}), f.width, f.height); }
};

Cadence. A frame is captured right after each input event reaches the editor, spaced by your fps and by the capture cost (a frame every 33–100 ms during a drag), and the settled frame follows within about 50 ms of the last event. Unchanged frames are not sent. Without input the engine follows the editor's own repaints at up to fps, slowing to one check per second once nothing changes. While the transport plays, frames share the link with the audio and are held to a byte budget (about 320 KB/s direct, 96 KB/s relayed), so audio packets never queue behind GUI frames. Frames need only read access to the project, so viewers may subscribe. Editor input sent over the mozart-editor channel (editor.pointer, editor.scroll, editor.type) needs edit access, like the REST input routes: the peer's peerGrant must be "write" (see Fast input). Without it the engine drops the event and answers {"type": "editor.state", "state": "error", "code": "project_write_forbidden"} (at most once per second).

Fast input on the monitoring peer

The Studio does not send drags, scrubs and plug-in clicks over HTTP. It sends them on the data channels of its WebRTC peer, so the engine applies each one within a few milliseconds and the result is in the next audio packet or editor frame. A monitoring peer opened through the API gets the same path. When your backend calls monitor/offer (or an MCP agent calls rick_webrtc_offer), Freestyle passes the engine the user the token belongs to and what the token may do. The engine then runs that peer as the user:

  • peerGrant: "write" needs audio:listen + daw:write and the owner or editor role. The peer may send every Studio fast input below.
  • peerGrant: "read" (no daw:write, or a viewer) gets audio, the clock, meters and editor frames. Every channel write, transport included, is refused (transport_ack with code: "project_control_forbidden", or editor.state with code: "project_write_forbidden").
  • The grant is bound to this project. The engine re-checks the user's role and your OAuth grant while the peer is open: removing the collaborator stops writes within seconds, and revoking your app or signing out everywhere closes the peer within about 30 seconds. A peer is closed when the engine moves to another project, and at peerGrantExpiresAt (8 hours). To renew it, send a new offer with the same client_id; the old peer is replaced.
  • peerGrant is what the engine confirmed it applied to your peer, not what was requested. If the engine cannot confirm it, the offer fails with 502 peer_delegation_unconfirmed and no peer is left open; retry shortly.
  • An engine that is still being updated answers 503 engine_update_required. Nothing was sent to it, so a peer you already have keeps running; retry shortly.
  • Your client_id is scoped to your user and always replaces your own peer. Should the engine still report it as another peer's, the offer answers 409 webrtc_client_id_in_use: nothing was replaced, send the offer again with a new client_id.
  • Your peer is yours: the engine runs it as your account and only lets you close, retune or replace it. That is why an account the engine cannot re-check (one that never completed a sign-in) gets 403 peer_identity_unavailable instead of a peer.

Create these channels on the RTCPeerConnection before you create the offer, so the offer has an m=application section:

const control = pc.createDataChannel("mozart-control");                                   // ordered
const editor  = pc.createDataChannel("mozart-editor", {negotiated: true, id: 100, ordered: true});
const frames  = pc.createDataChannel("mozart-editor-frames", {negotiated: true, id: 102, ordered: false});

Transport and mixer on mozart-control

Every message carries project_id, a key (one ordering lane, for example "transport" or "gain:<lane_id>") and a seq that increases per key. The engine drops a message whose seq is not newer than the last one it applied for that key, so a late packet never overwrites a newer drag position.

let seq = 0;
const send = (msg, key) => control.send(JSON.stringify({...msg, project_id: projectId, key, seq: ++seq, client_sent_ms: Date.now()}));
send({type: "transport_seek", seconds: 42.5}, "transport");            // scrub: the transport keeps rolling
send({type: "transport_play"}, "transport");                           // also transport_pause, transport_seek_and_play
send({type: "set_track_gain", lane_id: laneId, gain: 0.8}, `gain:${laneId}`);   // linear 0..4
send({type: "set_track_muted", lane_id: laneId, muted: true}, `mute:${laneId}`);  // set_track_soloed: {soloed}
send({type: "set_plugin_param", lane_id: laneId, plugin_index: 0, parameter_index: 3,
      value_norm: 0.62, expected_plugin_type: typeId}, `param:${laneId}:0:3`);  // typeId from listLanePlugins

A peer opened with a user's own engine credentials or through Freestyle's backend is what may write here. A peer the engine cannot tie to a user is read-only on every channel.

Transport messages are acknowledged on the same channel with {"type": "transport_ack", "ok", "applied", "key", "seq", "code"?}. If a transport message is refused (for example project_control_forbidden), it was not applied and you can safely send the REST call instead. Mixer and parameter messages change the live engine at once and have no ack. When a gesture ends, send the final value through the REST route (for example setLaneGain or setLanePluginParameter) so it is saved and recorded in history. The Studio does the same.

Instrument notes and pad samples on mozart-control

A peerGrant: "write" peer can play instruments and one-shot samples live, the way the Studio's keyboard and drum pads do. These messages carry project_id (the peer's project) but no key or seq: they are not merged, every one is played, in the order sent (the channel is ordered, so a note-off never overtakes its note-on). They have no ack. A message from a read peer, or for another project, is dropped without a reply. Field names are exact (snake_case, except sampleRange).

MessageFields
midi_notelane_id (string, an instrument lane); note (integer 0–127, default 60); velocity (number 0–1, default 0.82); channel (integer 1–16, default 1); on (boolean, default true; false is the note-off); optional ack (boolean) with event_id (string, up to 96 letters, digits, - or _, starting with a letter or digit). Values outside the ranges are clamped. If lane_id names no loaded lane and the project has exactly one instrument lane, the note plays there.
midi_all_notes_offlane_id. Releases every sounding note on that instrument. Send it when your surface loses focus or a key-up may have been lost.
sample_previewaudio_file_id (required: a pattern sample of this project, from listPatternSamples, registerPatternSample or uploadPatternSample); gain (linear 0–2, default 0.92); playback_rate (0.03125–32, default 1; repitches the sample); duration_sec (seconds of output to play, default 0 = the whole sample); bus_id (default "master"; an unknown bus plays on master); sampleRange ({"offsetSec", "durationSec"}, play part of the sample); voice_id (string up to 64 characters from A–Z a–z 0–9 _ - . :, needed only to release the voice later). Plays at once, on top of anything already sounding.
sample_preview_releasevoice_id (required, the one sent with sample_preview); optional held_sec. Ends that voice with a short fade: the pad-up of a hold-mode pad. A voice is released once; a voice that already ended is ignored.
live_holdOnly project_id. Every note and pad message keeps the engine's low-latency live-playing mode on for 15 s; live_hold does the same without playing anything. Send it every few seconds while your instrument surface is open and the player may play at any moment.

Replies. With ack: true and an event_id on a note-on, the following engine_clock frames carry midi_acks: [{"event_id", "position_samples"}]: the song position, in samples, at which that note is heard in the mix. Use it to stamp a performance at what the player heard. An ack that has not arrived after 2 s will not come. sample_preview answers only when its sample was not loaded yet (below).

A sample that is not loaded yet still plays. When audio_file_id is not loaded in the engine (the first tap after opening, or after the session was reloaded), the engine loads it and then plays it, late, and reports on the same channel: {"type": "sample_preview_result", "project_id", "audio_file_id", "ok", "healed": true, "engine_time_sec"?, "message"?}. ok: true means it played (engine_time_sec is when); with ok: false, message says why (for example sample not found, sample decode failed, or session_loading: try again shortly). Further taps of the same sample while it loads are dropped. Every later tap plays at once.

Warm the pads up. A sample_preview with gain: 0 is a supported warm-up: it is silent, and a sample that was not loaded is loaded (and answers sample_preview_result). Send one per pad when your drum surface opens, so the first real tap is not late.

const live = (msg) => control.send(JSON.stringify({...msg, project_id: projectId}));
for (const pad of pads) live({type: "sample_preview", audio_file_id: pad.audioFileId, gain: 0});   // warm-up
live({type: "midi_note", lane_id: keysLane, note: 64, velocity: 0.9, on: true, ack: true, event_id: "n1"});
live({type: "midi_note", lane_id: keysLane, note: 64, on: false});
live({type: "sample_preview", audio_file_id: kick.audioFileId, voice_id: "pad-1-7"});
live({type: "sample_preview_release", voice_id: "pad-1-7", held_sec: 0.4});
setInterval(() => live({type: "live_hold"}), 5000);   // while the surface is open
control.addEventListener("message", (e) => {
  const m = JSON.parse(e.data);
  if (m.type === "engine_clock" && m.midi_acks) for (const a of m.midi_acks) stamp(a.event_id, a.position_samples);
  if (m.type === "sample_preview_result" && !m.ok) console.warn(m.audio_file_id, m.message);
});

The REST equivalents, sendEngineMidi and engineMidiAllNotesOff, take an instrument_id from the engine state and work before the peer is open.

Launching a pattern (Session clip, pattern Play) on mozart-control

A pattern preview has to be compiled and its samples resolved before it can sound, which is too slow for the moment of the click. Do that work ahead of time and start it with one message, the way the Studio's Session clips and pattern Play buttons do. You need a peerGrant: "write" peer and a Pro account, like every pattern preview.

  1. Arm after each edit or when a clip is selected: previewPattern with the pattern, arm_only: true, the client_id of your monitoring peer and (optionally) your own armed_signature. Nothing plays. The reply carries armedSignature (yours, or a generated one) and, in response, the engine's {"ok": true, "armed": true, "armed_signature", "prepare_ms", "session_epoch"}.
  2. Start on the click: one message on that peer's mozart-control channel. key/seq work as for transport (one key for your preview lane, a seq that increases per key). preview_request_id is your own increasing number per press; repeat_count (1–64, default 1), gain (0–2, default 0.92), phase_offset_sec and lead_sec (default 0.025) shape the start like the REST call. A start pauses the song transport.
  3. Stop with pattern_preview_stop and the same or a later preview_request_id. A stop with id N also refuses any start with an id ≤ N that arrives after it.
// after an edit (REST, off the critical path)
await api(`/projects/${projectId}/patterns:preview`, {method: "POST", body: {
  pattern, length_ticks, ppq: 96, bars, arm_only: true, client_id: clientId, armed_signature: "clip-7-v12"}});
// on pointerdown
send({type: "pattern_preview_start", armed_signature: "clip-7-v12", preview_request_id: ++pressId,
      repeat_count: 64}, "pattern-preview");
// on stop
send({type: "pattern_preview_stop", preview_request_id: pressId}, "pattern-preview");

Both answer on the same channel with {"type": "pattern_preview_ack", "ok", "key", "seq", "project_id", "code"?, "message"}. A started preview's ack also carries preview_request_id, armed_signature, engine_time_sec (when it sounds), repeat_count and transport_paused_for_preview; a stop's carries preview_request_id, stopped_active_preview and stopped_through_preview_request_id. Codes:

  • not_armed: no arm with that signature for this peer (never armed, dropped as the oldest of more than 16 arms, older than 10 minutes, or the engine session reloaded). Nothing played: call previewPattern with the pattern (no arm_only) to play it now, and arm again.
  • stale_preview_request: that preview_request_id was already stopped. Nothing played.
  • project_control_forbidden: the peer may not write, or the account has no Pro. Nothing played.

An arm belongs to your peer (its client_id). A peer keeps up to 16 arms, one per armed_signature (arming the same signature again replaces that arm; beyond 16 the oldest is dropped), so every clip of a scene can stay armed. Nobody else's arm or stop (the Studio's, a collaborator's or another API client's) can replace, start or refuse yours. A single preview started this way (or over REST) replaces whatever pattern preview is sounding, theirs or yours, scene layers included; to play several together, use a scene launch (below). To start an arm over REST instead, call previewPattern with the same client_id and armed_signature, the pattern and no arm_only: it starts the arm, or compiles the pattern when the arm is gone. Pass client_id to stopPatternPreview / stopAllPatternPreviews to stop what your peer started. A preview started over REST without client_id is not tied to a peer: stop it over REST without client_id.

Scene launch: several patterns at one shared time

To start the clips of a Session scene together, in time with each other, arm each clip as above (arm_only: true, the same client_id, one armed_signature per clip), then start them all with one launch. The engine picks one start time for the whole set on its own audio clock, so the clips start on the same sample no matter how far apart your requests were. Each clip plays as a layer in its slot (slot_id, default its armed_signature) and loops repeat_count times (default 64) until you stop it.

  • REST: launchPatternPreviews with client_id and previews: [{armed_signature, slot_id?, repeat_count?, gain?}] (1–8).
  • mozart-control: {type: "pattern_preview_launch", previews, quantize?, beats_per_bar?, lead_sec?, stop_others?, preview_request_id?} with the usual key/seq; it is acknowledged with pattern_preview_ack carrying the same fields as the REST reply.
  • Quantize. quantize: "none" (default) starts after lead_sec (default 0.05 s). "beat" or "bar" starts on the next beat or bar line of the grid of the layers you already have playing (or of your single preview), so a later launch lands in time; beats_per_bar (default 4) sets the bar. With nothing playing, the launch starts at once.
  • Replacing. Launching into a slot that already plays one of your layers replaces it exactly at the launch time; your other slots keep playing. stop_others: true also ends your layers in the other slots at that moment (a full scene change). Your single preview, if one is playing, stops at the launch time too.
  • Stopping. stopPatternPreview (or pattern_preview_stop) with slot_id stops that slot only; without slot_id it stops your single preview and all of your layers. stopAllPatternPreviews stops all of yours. A stopped layer's notes that already started finish normally. Other peers' layers keep playing.
  • Limits. At most 8 layers play at once on a project's engine, from all peers together (409 too_many_previews: stop some first). Starting a single preview (pattern_preview_start, or previewPattern without arm_only) or the song transport stops every layer.
// arm every clip of the scene (REST, ahead of time)
for (const clip of scene.clips)
  await api(`/projects/${projectId}/patterns:preview`, {method: "POST", body: {
    pattern: clip.pattern, length_ticks: clip.lengthTicks, ppq: 96, bars: clip.bars, bpm,
    arm_only: true, client_id: clientId, armed_signature: clip.signature}});
// on the scene button: one launch, quantized to the next bar of what is playing
send({type: "pattern_preview_launch", quantize: "bar", preview_request_id: ++pressId,
      previews: scene.clips.map((c) => ({armed_signature: c.signature, slot_id: c.trackId}))},
     "pattern-preview");
// stop one clip slot
send({type: "pattern_preview_stop", slot_id: "track-3"}, "pattern-preview");

The reply (and the ack) carries engine_time_sec (the shared start, on the same engine audio clock as previewPattern), quantum_sec, grid_anchor_sec, previews (one entry per launched clip: slot_id, layer_id, armed_signature, engine_time_sec, cycle_duration_sec, repeat_count, replaced_slot), replaced_slots and layers (all of your layers now playing). 409 not_armed lists missing_signatures: nothing started; arm those and launch again.

Plug-in editor input on mozart-editor (id 100)

Subscribe to the editor first (on mozart-editor or on the frames channel, as above). The engine answers with editor.state "subscribed" on mozart-editor (id 100) whenever that channel is open, which gives the engine track_id. Input must name that same track_id and plugin_index. Coordinates are normalized to the editor image (0–1).

const target = {track_id: subscribed.track_id, plugin_index: 0};
editor.send(JSON.stringify({type: "editor.pointer", ...target, phase: "down", x_norm: 0.41, y_norm: 0.27,
                            button: 0, buttons: 1, gesture_id: "g1"}));        // then phase "move" ... "up"
editor.send(JSON.stringify({type: "editor.scroll", ...target, x_norm: 0.5, y_norm: 0.5, delta_x: 0, delta_y: -120, delta_mode: 0}));
editor.send(JSON.stringify({type: "editor.type", ...target, text: "a", keycode: 65}));
// all three also accept shift_key, ctrl_key, alt_key, meta_key

Pointer moves are merged on the engine side (latest wins), so send them at your pointer rate. The changed frame usually arrives on mozart-editor-frames within about 80–150 ms of the pointer-down, compared with about 300 ms or more for the REST input routes.

DAW sync sessions (Freestyle for Mac)

A DAW sync session links several people's own DAWs (FL Studio first, through Freestyle for Mac) into one live session: every mixer move, step edit, tempo change and play/stop on one machine appears on the others, with chat and WebRTC call signalling alongside. Freestyle only orders and relays small JSON frames; it does not interpret DAW contents, and audio never passes through it. Each DAW plays its own audio.

  1. Get the room. POST /api/v1/realtime/daw-sync-sessions (scope live:write, Freestyle Pro) with {"project_id": …} returns that project's one live room: the existing room (200, "created": false) while it has members or is within its grace period, otherwise a new one (201, "created": true). Everyone who opens the same project gets the same code, also when they ask at the same moment. Without project_id ({}) every call mints a new code-only room (201). The answer is {"code", "websocket_url", "expires_at", "project_id", "created"}; code is six characters without 0, O, 1 or I.
  2. Each member connects to websocket_url (/api/ws/daw-sync) with Authorization: Bearer <token> on the upgrade request (scope live:write). A missing or invalid token is a plain 401 with WWW-Authenticate; a missing scope is 403 insufficient_scope; an account without Pro is 403 pro_mode_required.
  3. The first frame is {"type": "join", "room": code, "peerId": <device id>, "daw"?, "dawConnected"?}, within 10 s. The server answers welcome. Your peer id is <user id>:<device id> and your name is your account's display name, whatever the frame says; use welcome.peerId.

Project rooms follow the share settings

Who may be in a project's room is exactly who may open the project in Freestyle: the owner, named collaborators with their roles, people who opened a link-shared project through its current link (with the link's default role), and anyone as a viewer on a public project. Anyone with at least viewer access may get the room and join it; anyone else gets 404 from the POST and project_access_denied on join.

  • Roles. welcome.role and every peers[].role are owner, editor or viewer. In a code-only room the creator is owner and everyone else editor; everyone may edit.
  • Viewers are read-only members. They receive everything (ops, reset, transport, chat, presence, signal) and may send chat, status, signal, ice and ping. Their ops, snapshot and transport frames are answered with {"type": "error", "code": "editor_required"}; the socket stays open, nothing is applied or relayed and seq does not move.
  • Share changes apply live. When the owner changes someone's role, the room sends presence with the new role and that member's write permission changes with it; when someone loses access (removed, project made private, link reset) they get authorization_revoked and the socket closes. Changes made in Freestyle's Share sheet, through the MCP sharing tools or the v1 share and collaborator operations apply within seconds; anything else is caught by the regular check every 120 s.
  • Live now. GET /api/v1/realtime/daw-sync-sessions?project_id=… (scope live:read, viewer access; 404 for a project you cannot see) answers {"project_id", "live", "code", "members", "expires_at"} without joining. For a library, ?project_ids=a,b,c (at most 50) answers {"data": [{"project_id", "live", "code", "members", "expires_at"}, …]} in the order asked; projects you cannot read, or that do not exist, are left out without an error. live is true only while someone is in the room (members > 0). An empty room inside its grace period answers live: false, members: 0 but still carries its code and expires_at (joining it keeps the session); with no room, code and expires_at are null. getProjectShare and every row of listProjects carry liveRoom: {"code", "members"} while the room exists (members: 0 during the grace period), or null.

A room lives while it has members and for 600 s after the last one leaves (so a network blip or an app restart keeps the session); expires_at slides. It holds at most 8 people. A reconnect sends join again and gets a fresh welcome with the whole picture; joining again with the same device id closes the older socket.

Frames

  • Client → server: ops (ops: [[key, value], ...], id?), snapshot (state plus seed: true, replace: true or neither), transport (kind play/stop/seek/beacon, play, pos, ppq, loop?, t), chat (text, up to 2000 characters), status (daw, dawConnected, media), signal (to, data), ping (t0) and ice.
  • Server → client: welcome (room, peerId, role, peers each with id, name, role, daw, dawConnected, state or null before the room is seeded, seq, transport, the last 50 chat messages, serverTime, iceServers, iceExpiresAt), presence, ops (seq, from, id, ops), seeded, reset (seq, from, state), transport (your fields plus from and serverTime), chat, signal, pong (t0, serverTime), ice and error (code, message). Numbers must be finite: a frame containing a value such as 1e999 is ignored like invalid JSON.
  • Ordering. Every accepted ops, seed or replace gets the next seq; every member receives ops and reset frames in that one order with no gaps, and ops come back to their sender too (the echo is the acknowledgement). The stored picture is the last value per key in that order. transport is sent to everyone except its sender.
  • Snapshots. The first seed becomes the picture (seeded to you, reset to the others); a later seed loses the race and is answered with reset carrying the existing picture. replace always becomes the picture. A snapshot with neither flag only adds keys the picture lacks, sent to everyone as an ops frame.
  • Clock. pong.serverTime is read when the pong is written; derive your clock offset from the fastest recent round trip. transport.t values are on that clock.
  • Calls. welcome.iceServers holds short-lived TURN credentials (urls, username, credential; iceExpiresAt in Unix seconds) for member-to-member WebRTC; send {"type": "ice"} for fresh ones before they expire. Offers, answers and ICE candidates travel as signal frames.

Errors arrive as an error frame before the socket closes: session_not_found (unknown or expired code), session_full, project_access_denied (project room, you have no access to the project), invalid_peer_id, join_timeout, rate_limited (over 200 frames or 262144 bytes per second, with a 3-second burst; snapshots up to 8388608 bytes have their own budget), slow_consumer (your connection fell too far behind), authorization_revoked (the app's access was revoked, or you lost Pro or your access to the project; checked every 120 s, not on token expiry), server_busy (too many sockets on the server, or more than 12 of yours) and not_available; too many joins with unknown codes also close with rate_limited. Three errors leave the socket open: editor_required (a viewer sent ops, snapshot or transport; nothing was applied), state_too_large (the frame would push the picture past 50000 keys, 8388608 bytes or 256-character keys; nothing in it was applied and seq did not move) and rate_limited for a repeated join (one per 2 s), lost seed races or ice requests beyond a small budget. Creating a room answers 429 daw_sync_session_limit when you already created 20 rooms (getting a project's existing room never counts), and 429 daw_sync_capacity when the server is full.

curl -X POST https://freestyle.audio/api/v1/realtime/daw-sync-sessions \
  -H "Authorization: Bearer $FREESTYLE_TOKEN" -H "Content-Type: application/json" \
  -d '{"project_id": "<project id>"}'
# 201 {"code": "K7QM4X", "websocket_url": "wss://…/api/ws/daw-sync", "expires_at": "…",
#      "project_id": "<project id>", "created": true}   (200 and "created": false for the next person)

→ {"type": "join", "room": "K7QM4X", "peerId": "studio-mac"}
← {"type": "welcome", "peerId": "<user id>:studio-mac", "role": "editor", "seq": 0, "state": null, …}
→ {"type": "ops", "id": "e1", "ops": [["mx/3/vol", 0.8]]}
← {"type": "ops", "seq": 1, "from": "<user id>:studio-mac", "id": "e1", "ops": [["mx/3/vol", 0.8]]}

Live microphone ingest

Recording in your interface sends the microphone to the engine over WebRTC the other way (client → engine). Scope daw:write, editor role; the engine must run at 48 kHz.

Recording a take

A take is placed on the song timeline where it was recorded: its clip starts at the song_start_sec you send in take_start and ends at song_end_sec from take_stop. Optionally, while the take records, send {type: "sync", take_id, song_sec, wall_ms} about every 100 ms with the song position the singer hears (the engine clock's position when you monitor the engine); the engine then follows the singer's clock exactly. Without syncs the clip starts at song_start_sec and is bounded by song_end_sec.

  • Record from Stop. Like Record in any DAW, a take_start with mode: "record" on a stopped transport rolls the transport from song_start_sec; take_started then carries started_transport: true. Report song_sec from the engine clock (engine_clock frames, see The engine clock) as it moves.
  • Or start playback first. Send transport_play on mozart-control (see Fast input) or call play, then call startRecording and send take_start with song_start_sec = the song position at which the take begins (the clock's position_seconds). A rolling transport is never re-seeked by take_start.
  • Or let the count-in start it. Call startRecording with count_in_beats (1–8), start_transport: true and, to start somewhere other than the current position, seek_seconds. The call answers at the recording boundary with response.count_in (recording_start_position_seconds, transport_started, …); response.audio.take_start is the take_start message to send, with song_start_sec already filled in. Add your take_id.

Count-in without an audio take (MIDI takes, count-in then play)

A MIDI take that your app stamps itself against the transport clock needs the clicks but no engine recording. Call play with count_in_beats (1–16) and, to start somewhere other than the current position, seek_seconds (0 is fine: the clicks need no timeline before the project start). The engine clicks that many beats at the tempo — also with the metronome off — and starts the stopped transport exactly one beat after the last click; nothing is armed. bpm (20–400) sets the tempo first when the tempo map is constant, like startRecording.

The call answers on the boundary (pass wait: false to get the reply at once) with response.transport_started, position_seconds, start_position_seconds (where the take starts on the timeline), count_in_bpm, count_in_beat_samples, count_in_first_click_sample and transport_start_sample; the samples are on the engine's audio-device clock (last click to transport_start_sample = one beat). A pause, play or seek during the count-in cancels it: the call then answers 409 count_in_cancelled and the transport stays stopped. 409 transport_rolling: pause first; 409 recording_in_progress: an audio take is armed, and its own count-in applies.

// MIDI take at bar 1 with a one-bar count-in
const {response} = await api(`/projects/${projectId}/transport/play`, {method: "POST",
  body: {count_in_beats: 4, seek_seconds: 0}});
// the transport is rolling from response.start_position_seconds: stamp notes from here

A take whose song clock never moved (every sync reported the same song_sec, for example because the transport was stopped again during the take) has no song placement to follow: it is saved whole, from song_start_sec, for its full captured length. It is never cut down to its last seconds.

Finalizing. Send finalizeRecording (confirm: true, take_id) right after take_stop; a finalize that reaches the engine before take_stop waits for it. Pass wait_for: "placed" so the UI can settle the take at once:

  • wait_for: "placed" (recommended). The call answers 200 as soon as the take is captured and its clip is on the lane, usually about a second after take_stop, with saved: false, state: "saving" and the clip's final track_id, lane_id, start_ms and duration_sec (in_engine: true when it already plays in the engine). The security scan and store finish in the background (about 10 s). Call finalizeRecording again with the same take_id to learn the outcome: saved: true (state: "saved"), 409 recording_take_pending (still saving, call again) or a final 422 recording_take_rejected (the clip is removed).
  • wait_for: "saved" (the default). The call answers 200 with saved: true only once the take is fully saved: security-scanned and stored as a clip of the project. Each call waits up to wait_ms (0–10000, default 8000) and then answers 409 recording_take_pending if the take is not saved yet. That 409 is the expected "still saving" signal, not an error: call again with the same take_id. The call is idempotent, so a repeat after a lost reply is safe.
  • Final answers, do not retry: 422 recording_take_silent (the take held no audio; check that the microphone track is live), 422 recording_take_rejected (refused by the scan, replaced by a newer take on its lane, access revoked, or the save failed), 404 recording_take_not_found (no take with that take_id was recorded on your uplink) and 403 recording_take_owner_mismatch. After a 422, record again with a new take_id; a take_id is single-use.
async function finalize(takeId) {
  showClip(takeId, {state: "saving"});
  let waitFor = "placed";
  for (;;) {
    const res = await fetch(`${API}/projects/${projectId}/recording:finalize`, {method: "POST", headers,
      body: JSON.stringify({confirm: true, take_id: takeId, wait_for: waitFor, wait_ms: 10000})});
    const body = await res.json();
    if (res.ok && body.response.saved) return showClip(takeId, {state: "saved", clip: body.response});
    if (res.ok) { showClip(takeId, {state: "saving", clip: body.response}); waitFor = "saved"; continue; }  // on the lane, still saving
    if (res.status === 409 && body.error?.code === "recording_take_pending") continue;
    return showClip(takeId, {state: "failed", code: body.error?.code});   // final
  }
}

Mixer meters are lossy telemetry on the monitoring peer's data channels, not part of the revision stream. See Live mixer meters.

Freestyle developer documentation. Base URL https://freestyle.audio. Generated from the server's own registry and configuration.