# Mastering

> Master through the API or an embedded bench, with an optional partner payment hold.

Upload a lossless stereo master (WAV or FLAC, 16- or 24-bit, up to 500 MB), measure its loudness, true peak, clipping, silence, and spectrum, and render corrected versions — either through the REST API or inside `<wavbee-mastering>` on your own site.

Requires the `mastering` feature on your account.

## REST API flow

### 1. Upload a master (create a session)

Send a small file (≤ 32 MiB) as multipart `file`, point at an `audio_url`, or use direct-to-storage upload (`POST /v1/builder/uploads/direct` → `PUT` → `POST /v1/builder/uploads`, then pass `upload_id`) for masters over 32 MiB.

```bash
curl -X POST "$ACTIVQC_BASE_URL/v1/mastering/sessions" \
  -H "Authorization: Bearer $WQC_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"audio_url": "https://cdn.example.com/masters/song.wav"}'
```

Returns `202 Accepted` with a `mastering.session` in `status: "analyzing"`. Files expire automatically after 7 days.

### 2. Poll the session and inspect its measurement

```bash
curl "$ACTIVQC_BASE_URL/v1/mastering/sessions/41" \
  -H "Authorization: Bearer $WQC_API_KEY"
```

When `status` reaches `"ready"`, `assessment` contains measured integrated loudness (LUFS), true peak (dBTP), LRA, PLR, leading/trailing silence, and audio QC notes. Fetch waveform, spectrum, and clipping map once via `GET /v1/mastering/sessions/:id/visual`.

### 3. Render with a loudness target, genre profile, or reference track

Queue one or more renders on the same measured session:

```bash
curl -X POST "$ACTIVQC_BASE_URL/v1/mastering/sessions/41/renders" \
  -H "Authorization: Bearer $WQC_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "settings": {
      "loudness_mode": "match",
      "target_lufs": -14.0,
      "ceiling_dbtp": -1.0,
      "trim_silence": true,
      "keep_silence_s": 3.0
    }
  }'
```

To shape tone toward a reference track, upload the reference as a second mastering session and pass `reference_session_id`, or pass `tone: { "mode": "genre", "genre": "Pop", "strength": 0.7 }` (or `"mode": "closest"`) to match your reference library profiles (`GET /v1/mastering/profiles`).

### 4. A/B listen and download

Poll `GET /v1/mastering/renders/:id` (or the parent session). Every finished render (`status: "succeeded"`) is measured on the actual rendered file, never predicted, and carries:

- `assessment` — post-render LUFS, true peak, silence, and QC findings;
- `output_url` — short-lived signed WAV download URL (15-minute TTL) for A/B listening and delivery;
- `GET /v1/mastering/renders/:id/visual` — post-render waveform and spectrum.

### Status updates (polling and live updates)

- **Server-to-server:** poll `GET /v1/mastering/sessions/:id` or `GET /v1/mastering/renders/:id` every 2 seconds until `status` is `"ready"` / `"succeeded"` or `"failed"`. Dedicated mastering webhook events are planned; until then, polling is the authoritative server channel.
- **Browser embeds:** the embed polls its session automatically while analysis, rendering, or payment release is in progress. Live WebSocket push replaces polling in an upcoming update with no change to your embed integration.

## Embeddable mastering (`<wavbee-mastering>`)

Mount the full mastering bench inside your own portal without putting an API key in the browser.

### 1. Allow your origin

In your tenant console under **Developers → Embed**, add the exact origin(s) that will host the iframe (for example `https://studio.yourlabel.com`). Every embed response sends `Content-Security-Policy: frame-ancestors` restricted to that list.

### 2. Mint an embed session on your server

Call `POST /v1/embed/sessions` with your **secret API key** (`wqc_live_…` or `wqc_test_…`). Pass `product: "mastering"`. Set `require_payment: true` if you want to charge the artist before releasing full-quality downloads.

```bash
curl -X POST "$ACTIVQC_BASE_URL/v1/embed/sessions" \
  -H "Authorization: Bearer $WQC_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "product": "mastering",
    "end_user_ref": "artist-8842",
    "require_payment": true,
    "theme": { "mode": "light" }
  }'
```

The single-use `client_token` (`wqc_es_…`) expires in 30 minutes and is strictly scoped: the embed session can see only the mastering sessions and renders it created.

### 3. Mount the element and handle partner payment

Load `/embed/v1/embed.js` (or use `Mastering` from `@wavbee/release-builder-react`):

```html
<script type="module" src="https://YOUR-ACTIVQC-HOST/embed/v1/embed.js"></script>

<wavbee-mastering client-token="wqc_es_..." theme="light"></wavbee-mastering>

<script type="module">
  const el = document.querySelector('wavbee-mastering')

  el.addEventListener('wavbee:render.completed', (e) => {
    console.log('Render ready', e.detail) // { render_id, lufs, true_peak }
  })

  el.addEventListener('wavbee:download.requested', async (e) => {
    const { render_id } = e.detail
    // 1. Run your checkout flow for the artist.
    // 2. From your server, call POST /v1/mastering/renders/:id/release with your secret API key.
    await fetch(`/api/mastering/checkout/${render_id}`, { method: 'POST' })
    // Optional: nudge the iframe to refresh immediately instead of waiting for the next 2 s poll.
    el.notifyDownloadReleased()
  })

  el.addEventListener('wavbee:download.ready', (e) => {
    console.log('Full-quality download unlocked', e.detail.render_id)
  })
</script>
```

When `require_payment: true`:
1. The artist previews and A/B compares every render normally inside the embed.
2. Clicking **Download** posts `download.requested` (`{ render_id }`) to the parent window instead of downloading; full attachment URLs are withheld by the server.
3. Once your backend collects payment, call `POST /v1/mastering/renders/:id/release` with your secret API key.
4. The embed unlocks the Download link and posts `download.ready` (`{ render_id }`).

Without `require_payment`, downloads work immediately.

### Events (`wavbee.mastering.v1`)

All messages use `{ protocol: "wavbee.mastering.v1", version: 1, type, nonce, data }` posted strictly to your `allowed_origin`, and are re-emitted on `<wavbee-mastering>` as `wavbee:<type>` `CustomEvent`s:

| Event | `detail` payload | When |
|---|---|---|
| `ready` | `{ session_id }` | Embed mounted and session active |
| `resize` | `{ height }` | Content height changed (handled automatically by the loader) |
| `upload.completed` | `{ mastering_session_id, filename }` | Master uploaded and analysis queued |
| `render.completed` | `{ render_id, lufs, true_peak }` | A render finished and was measured |
| `download.requested` | `{ render_id }` | Artist clicked Download on a payment-held render |
| `download.ready` | `{ render_id }` | Partner released the render and Download is now active |
| `session.expired` | `{}` | 30-minute embed session expired or was revoked |
| `error` | `{ code }` | An API or upload call failed |

## Metering

Each live mastering session that produces at least one succeeded render records one `mastering_session` `UsageEvent` (keyed idempotently by session id). Multiple renders on the same master, failed renders, and sandbox sessions cost 0.
