FreestyleDevelopers Open the app

Waveforms

The Freestyle Studio's timeline reads the peaks of each audio file once and then draws every zoom level, trim, split and duplicate from that one copy. Nothing is fetched because the zoom changed, so the waveform never blanks, shifts or waits. This page is the recipe for the same result in your own interface. It uses one operation, getClipWaveform, and data you already have from listClips.

What to build

  • One set of peaks per audio source, not per clip and not per zoom level. Ten clips chopped from one file share it.
  • A pyramid of levels on the client. Each level is the pairwise maximum of the level below it, so every level describes the same audio.
  • Zoom picks a level from the pixels per second. Inside one level the bars only spread apart; crossing to the next level splits each bar in two or merges pairs. A bar never moves to a different moment of the audio.
  • Edits are arithmetic. A trim, slip, split, move or duplicate changes which slice of the peaks a clip shows. It needs no request.
  • Detail arrives in the background. A coarse pass draws at once; fine tiles replace it, nearest the view first. Until a tile arrives its bars show the coarser value, so there is always something to draw.
  • Recording draws from the microphone on the client and is replaced by the saved take's peaks when the take is placed.

The operation

GET /projects/{project_id}/clips/{clip_id}/waveform (scope daw:read, viewer or above, rate class interactive). The MCP tool get_clip_waveform takes the same arguments and returns the same result.

ParameterMeaning
clip_id (path)A clip id from listClips or getProject, or backing for the backing track.
start_frame, end_frameA range of source sample frames, end exclusive. Frame 0 is the start of the source file, not of the clip's audible region. Defaults: 0 and the end of the source.
buckets1 to 8192, default 1024. Bucket b of n covers frames [start + floor(b·span/n), start + floor((b+1)·span/n)). A range with fewer frames than buckets returns one frame per bucket.
If-None-Match (header)A previous ETag. The answer is 304 with no body while the source is unchanged.
Response fieldMeaning
revisionIdentity of the source audio, also sent as the ETag. Clips cut from the same source report the same revision. It changes only when the source audio changes: a sample edit, an applied region effect, a voice-model render or a tempo change.
sample_rate, frame_count, channel_countThe source's frame rate, its whole length in frames and its channels. frame_count / sample_rate is the source's length in seconds.
start_frame, end_frame, bucket_count, frames_per_bucketThe range and bucket count actually answered, after clamping to the source.
channels[]Per channel, three arrays of bucket_count values: min, max and rms. Raw samples in [-1, 1], before clip gain and before effects.
clipThe clip's placement at the time of the read: start_ms, audio_offset_sec, audio_offset_frames, duration_sec, duration_frames, gain.
session_recoveredPresent when the clip was not loaded and the server loaded it for this read (session_load or clip_attach). Such a read takes longer than usual.

Responses are sent with Cache-Control: no-store, so the browser's HTTP cache does not keep them. Keep the peaks yourself, keyed by the clip's audioSourceId (next section).

The recipe

1. One pyramid per source

Choose a base bucket size in frames and keep it fixed. 64 frames is 1.3 ms at 48 kHz, which is fine enough for a zoom of 2400 pixels per second. Level 0 holds one peak per 64 frames, level 1 one per 128, and so on until a level has a single bucket. A peak is the largest |min| or |max| over all channels; keep min and max separately if you draw an asymmetric or per-channel waveform.

Key the pyramid by audioSourceId. Every clip from listClips and getProject carries it: an opaque id of the audio the clip plays. Clips with the same audioSourceId play the same audio, so a clip whose audioSourceId you already hold is drawn from that pyramid with no request. That covers the pieces of a split, a duplicate and a paste the moment they appear. When a clip's audio is replaced (a sample edit, an applied region effect, a voice-model render or a tempo change) its audioSourceId changes, and only that clip needs a new pyramid.

Compare audioSourceId for equality only. It is not the waveform's revision and it is not a clip id. It is null for a clip with no stored audio, and a server that predates the field leaves it out; in both cases key that clip's pyramid by the revision of its first read, which clips cut from the same source also share.

2. Read the file once: a coarse pass, then tiles

  1. Coarse pass. Find the finest level that fits in 8192 buckets and request the whole file at that level in one call. Write it into the pyramid, rebuild the coarser levels from it, and let every finer bucket show its parent's value. You can draw every zoom level now.
  2. Base tiles. Request level 0 in tiles of 8192 buckets: start_frame = tile · 8192 · 64, end_frame = start_frame + n · 64, buckets = n. Ask only for whole buckets, so each returned bucket is exactly 64 frames on your grid. A last partial bucket (under 64 frames) keeps its coarse value. Load the tiles nearest the view first.
  3. Rebuild upward after each tile: recompute only the parents of the buckets that changed, then redraw only the parts of the screen that show them.

A source needs 2 + ceil(frame_count / 524288) requests in total (the example's first request only reads the file's length): about one tile per 11 s of audio at 48 kHz, 24 requests for a four-minute track. If you never zoom that far, use a larger base (256 frames needs a quarter of the tiles), or load fine tiles only for the range on screen.

3. Pick the level from the zoom

One bucket is one bar. Use the level whose buckets are between 1.7 and 3.4 pixels wide at the current zoom:

level = ceil(log2(1.7 * sample_rate / (64 * pixels_per_second)))   // clamped to the levels you have

Draw each bar in the first half of its slot, with its left edge exactly at the bucket's start time. While the zoom stays inside one level, the same bars are drawn further apart. Do not resample peaks to the clip's pixel width: that puts every bar on a new time boundary at every zoom step, and the shape crawls.

4. Map each clip to a slice

A clip plays source seconds [audioOffsetSec, audioOffsetSec + durationSec) at timeline seconds [startMs / 1000, startMs / 1000 + durationSec) (see time units). Bucket i of a level with slot seconds per bucket starts at source second i · slot, so on the timeline it is at:

x = (startMs / 1000 + i * slot - audioOffsetSec - scroll_seconds) * pixels_per_second

Draw the buckets from floor(audioOffsetSec / slot) to ceil((audioOffsetSec + durationSec) / slot) and clip the drawing to the clip's rectangle. After clips:batch or a time-range edit, the new and changed clips have new startMs, audioOffsetSec and durationSec and the same source: redraw from the pyramid you hold. A clip inserted with source_id plays the audio of the clip it names, so its card carries that clip's audioSourceId.

5. Never blank

  • Zooming and scrolling read the pyramid synchronously. They never start a request and never wait for one.
  • A level whose own tiles have not arrived shows its parent's values. Replace them in place when the tile lands; do not clear first.
  • When a clip's audioSourceId changes, keep drawing its old pyramid until the new coarse pass has arrived, then swap.
  • Normalize once per source (divide by the file's loudest bucket, which is the top of the pyramid), so a waveform's height does not change as detail arrives.

6. Draw long clips in fixed chunks

Draw only the buckets on screen. If you draw with SVG or cache drawings, cut each level into chunks of a fixed number of bars (the Studio uses 128) anchored to file time: chunk c of a level always holds buckets [128c, 128c + 128). A chunk's drawing depends only on the level and its index, so scrolling and zooming inside a level reuse it, a tile that lands redraws only the chunks it overlaps, and a short clip cut from a long file carries only the chunks its slice touches. Use coordinates relative to the chunk and translate the chunk into place; coordinates measured from the start of a long file lose precision at deep zoom.

7. Keep the peaks

Store a finished level 0 on the device (for example in IndexedDB) under the audioSourceId, with the revision it was read at. On the next open the clip cards name the sources you hold: draw those at full detail with no request. A stored pyramid stays valid for as long as a clip reports that audioSourceId; any later read that returns a different revision means the stored copy must be rebuilt.

8. Recording: draw live, then replace

While a take records (see Recording a take), the audio exists only in the microphone stream your client is sending, so draw the growing waveform from that stream:

  • Measure the peak of each 10 ms of microphone samples and append it to a list. A finished bucket never changes.
  • Draw the bars on the same slot grid and at the same density as a finished clip at this zoom, with a fixed vertical scale. Do not re-normalize as the take gets louder; bars already drawn must not move or change height.
  • When finalizeRecording with wait_for: "placed" returns the new clip (response.track_id, start_ms, duration_sec), keep the live bars on screen, read that clip's waveform as in step 2 and swap when the coarse pass arrives.

The API has no waveform of a take that is still recording. Other people in the project see the take's waveform once its clip is placed.

9. Retries

AnswerWhat to do
429 rate_limitedStop the background fill for at least Retry-After seconds. Keep drawing what you have.
409 target_not_loaded, 502, 503, network errorsRetry with exponential backoff (0.5 s, 1 s, 2 s, …) and jitter, a few times. An editor can load a stored clip first with attachClipToSession.
400, 403, 404 waveform_unavailableDo not retry in a loop. Give the source up after three such answers and leave the other sources' fills running.

10. Stay inside the rate limit

Waveform reads are ordinary interactive requests: 600 per minute per user, shared with every other call your interface makes for that user, and for OAuth apps also 600 per minute per (app, user). See rate limits. A 304 counts as a request.

  • Give the background fill its own small budget: about 2 requests per second with at most 4 in flight. That leaves most of the minute's budget for edits, transport and mixer calls.
  • Spend it nearest the view first. On a phone, load the coarse pass for every source and fine tiles only around what is zoomed into.
  • Never request on a zoom or scroll event. Those only change which stored level and slice you draw.
  • Watch X-RateLimit-Remaining and slow the fill down before it reaches zero.

Example

A complete loader and renderer in plain JavaScript (browsers and Node 18 or later). It uses only getClipWaveform. token is a user access token with daw:read; clips are clip objects from listClips; ctx is a 2D canvas context.

const API = "https://freestyle.audio/api/v1";
const BASE = 64;     // source frames per bucket at level 0 (1.3 ms at 48 kHz)
const TILE = 8192;   // the most buckets one request returns
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// One documented call, with retry. 429 and 5xx wait for Retry-After (or back
// off 0.5 s, 1 s, 2 s ...); 409 target_not_loaded is retried the same way.
async function getClipWaveform(token, projectId, clipId, startFrame, endFrame, buckets) {
  const query = new URLSearchParams({ start_frame: startFrame, end_frame: endFrame, buckets });
  const url = `${API}/projects/${projectId}/clips/${clipId}/waveform?${query}`;
  for (let attempt = 0; ; attempt += 1) {
    const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
    if (res.ok) return res.json();
    const retryable = res.status === 429 || res.status === 409 || res.status >= 500;
    if (!retryable || attempt >= 4) throw new Error(`waveform ${res.status}`);
    const wait = Number(res.headers.get("Retry-After")) || 0.5 * 2 ** attempt;
    await sleep(wait * 1000 * (1 + Math.random() / 4));
  }
}

// Level k holds one peak (max |sample| over all channels) per BASE * 2^k
// source frames. Every level is the pairwise max of the level below it.
function createPyramid(frameCount, sampleRate, revision) {
  const counts = [Math.ceil(frameCount / BASE)];
  while (counts.at(-1) > 1) counts.push(Math.ceil(counts.at(-1) / 2));
  return {
    frameCount, sampleRate, revision,
    levels: counts.map((n) => new Float32Array(n)),
    tiles: new Uint8Array(Math.ceil(counts[0] / TILE)),  // 1 = level 0 tile is loaded
    peak: 0,                                               // loudest bucket of the file
  };
}

const absPeaks = (waveform) => {
  const out = new Float32Array(waveform.bucket_count);
  for (const channel of waveform.channels)
    for (let b = 0; b < out.length; b += 1)
      out[b] = Math.max(out[b], Math.abs(channel.min[b]), Math.abs(channel.max[b]));
  return out;
};

// Write peaks at `level` from bucket `first`, then rebuild every coarser level.
function writeLevel(pyramid, level, first, values) {
  pyramid.levels[level].set(values, first);
  let lo = first, hi = first + values.length;
  for (let k = level + 1; k < pyramid.levels.length; k += 1) {
    const child = pyramid.levels[k - 1], parent = pyramid.levels[k];
    lo >>= 1; hi = Math.min(parent.length, (hi + 1) >> 1);
    for (let i = lo; i < hi; i += 1) parent[i] = Math.max(child[2 * i], child[2 * i + 1] || 0);
  }
  pyramid.peak = pyramid.levels.at(-1)[0];
}

// Request 1: the whole file in one call, on the pyramid's own grid. Finer
// levels show their parent's value until their own tile arrives.
async function openPyramid(token, projectId, clipId) {
  const probe = await getClipWaveform(token, projectId, clipId, 0, BASE, 1);
  const pyramid = createPyramid(probe.frame_count, probe.sample_rate, probe.revision);
  const level = pyramid.levels.findIndex((data) => data.length <= TILE);
  const size = BASE * 2 ** level;
  const whole = Math.floor(pyramid.frameCount / size);
  if (whole > 0) {
    const coarse = await getClipWaveform(token, projectId, clipId, 0, whole * size, whole);
    writeLevel(pyramid, level, 0, absPeaks(coarse));
    for (let k = level - 1; k >= 0; k -= 1)
      for (let i = 0; i < pyramid.levels[k].length; i += 1)
        pyramid.levels[k][i] = pyramid.levels[k + 1][i >> 1];
    if (level === 0) pyramid.tiles.fill(1);              // a short file is complete already
  }
  return pyramid;
}

// Requests 2..n: one level 0 tile. Only whole buckets are requested, so
// bucket b of the answer is exactly frames [start + b * BASE, start + (b + 1) * BASE).
async function loadTile(token, projectId, clipId, pyramid, tile) {
  if (pyramid.tiles[tile]) return;
  const start = tile * TILE * BASE;
  const whole = Math.min(TILE, Math.floor((pyramid.frameCount - start) / BASE));
  if (whole > 0) {
    const data = await getClipWaveform(token, projectId, clipId, start, start + whole * BASE, whole);
    if (data.revision !== pyramid.revision) throw new Error("source changed: rebuild the pyramid");
    writeLevel(pyramid, 0, tile * TILE, absPeaks(data));
  }
  pyramid.tiles[tile] = 1;
}

// One pyramid per source audio. Clips with the same audioSourceId (the pieces of a
// split, a duplicate, a paste) share it, so only the first of them is read.
// A clip without an audioSourceId (older server) gets a pyramid of its own.
const pyramids = new Map();
function pyramidFor(token, projectId, clip) {
  const key = clip.audioSourceId ?? `clip:${clip.id}`;
  if (!pyramids.has(key)) {
    const opening = openPyramid(token, projectId, clip.id);
    opening.catch(() => pyramids.delete(key));             // a failed open is tried again
    pyramids.set(key, opening);
  }
  return pyramids.get(key);
}

// Fill in the background: tiles nearest the view first, a few at a time,
// about two requests per second.
async function fillPyramid(token, projectId, clipId, pyramid, viewSec = 0, onTile = () => {}) {
  const near = Math.floor((viewSec * pyramid.sampleRate) / (TILE * BASE));
  const order = [...pyramid.tiles.keys()].sort((a, b) => Math.abs(a - near) - Math.abs(b - near));
  const worker = async () => {
    for (let tile = order.shift(); tile !== undefined; tile = order.shift()) {
      await loadTile(token, projectId, clipId, pyramid, tile);
      onTile(tile);
      await sleep(1000);
    }
  };
  await Promise.all([worker(), worker()]);
}

// The level whose buckets are 1.7 to 3.4 px wide at this zoom.
function levelForZoom(pyramid, pxPerSec) {
  const level = Math.ceil(Math.log2((1.7 * pyramid.sampleRate) / (BASE * pxPerSec)));
  return Math.max(0, Math.min(pyramid.levels.length - 1, level));
}

// Draw one clip. `clip` is a Clip from listClips: startMs, audioOffsetSec and
// durationSec choose a slice of the file's peaks. Nothing is fetched here.
function drawClip(ctx, pyramid, clip, { pxPerSec, scrollSec, top, height, viewWidth }) {
  const level = levelForZoom(pyramid, pxPerSec);
  const data = pyramid.levels[level];
  const slotSec = (BASE * 2 ** level) / pyramid.sampleRate;
  const slotPx = slotSec * pxPerSec;
  const clipSec = clip.startMs / 1000;
  const from = Math.max(clip.audioOffsetSec, clip.audioOffsetSec + scrollSec - clipSec);
  const to = Math.min(clip.audioOffsetSec + clip.durationSec, from + viewWidth / pxPerSec + slotSec);
  const last = Math.min(data.length, Math.ceil(to / slotSec));
  const mid = top + height / 2, inner = Math.max(1, height - 14), scale = pyramid.peak || 1;
  for (let i = Math.max(0, Math.floor(from / slotSec)); i < last; i += 1) {
    const x = (clipSec + i * slotSec - clip.audioOffsetSec - scrollSec) * pxPerSec;
    const bar = Math.max(2, (data[i] / scale) * inner);
    ctx.fillRect(x, mid - bar / 2, slotPx / 2, bar);
  }
}

// Usage
const view = { pxPerSec: 80, scrollSec: 0, top: 0, height: 64, viewWidth: canvas.width };
const filling = new Set();
async function redraw() {
  const drawn = await Promise.all(clips.map(async (clip) => [clip, await pyramidFor(token, projectId, clip)]));
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  for (const [clip, pyramid] of drawn) {
    drawClip(ctx, pyramid, clip, view);
    if (filling.has(pyramid)) continue;                              // one fill per source
    filling.add(pyramid);
    fillPyramid(token, projectId, clip.id, pyramid, view.scrollSec, redraw)
      .catch(() => filling.delete(pyramid));                         // resumed by the next redraw
  }
}
redraw();                              // 2 requests per source, then drawn; tiles follow
// On zoom, scroll, trim or move: change `view` or the clip and call redraw(). No request.
// After a split, duplicate or paste: read the clips again and call redraw(). The new
// clips carry an audioSourceId you already hold, so they are drawn at once with no request.

Backing track and samples

  • Backing track. Use clip_id = backing and leave track_id out. Everything above applies unchanged. Its cache key is backing.audioSourceId from getProject.
  • Channel Rack samples. getPatternSampleWaveform returns up to 2048 normalized peaks for a whole sample in one call. That is enough for a sample preview; it is not a zoomable source.
  • MCP. get_backing_waveform is a loudness summary (8 to 256 buckets) for finding sections, not for drawing. An MCP-driven editor uses get_clip_waveform exactly as above.

Sample-level zoom and the pencil

Past one frame per pixel, request the visible frames directly: a range with no more frames than buckets returns one frame per bucket, so min equals max equals the sample. The revision you read is the If-Match value for editClipSamples. After an edit the clip reports a new revision and its card a new audioSourceId: build a new pyramid for it, and keep the old one for the other clips that still use the unedited source.

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