# ClipMux documentation
ClipMux is self-hosted video infrastructure, an open-source alternative to Mux and Cloudflare Stream.
Source: https://clipmux.com/docs
ClipMux lets any app upload a video, get a playback ID, and stream it to every
device as encrypted HLS: from your own storage, encoded on your own GPU or one
you rent by the minute, behind playback tokens your backend signs.
It's one Go binary and Postgres. Storage, encoding and delivery each sit behind
an adapter. You can move from a disk to R2, or from your server to a cloud GPU,
and the API your apps call stays the same.
## Choose a path [#choose-a-path]
Uploads, webhooks and private playback with the Node SDK, or the REST API
from any language.
Install ClipMux on a Linux machine with Docker, then connect storage,
encoding and delivery.
Point your agent at `clipmux.com/agents.md`. Every page here is also plain
Markdown.
## Start here [#start-here]
Add uploads and playback to a Next.js app in four steps.
One command on a Linux server with Docker.
Videos, playback IDs, tokens and tracks.
Every route of the integration API, with an example.
## What ClipMux does [#what-clipmux-does]
- **Uploads that resume.** Browsers send parts straight to storage, and a
dropped connection picks up where it left off.
- **Encoding up to 4K,** on the server's GPU or CPU, a PC you own, or a cloud
GPU on Modal or RunPod under a monthly spend limit.
- **Encrypted HLS,** with keys derived when a signed viewer asks, never stored.
- **Subtitles and chapters,** from whisper.cpp on your own machines, or a
speech API and an LLM you choose.
- **Apps, keys and webhooks,** so each app has its own credentials.
- **Share links and analytics:** views, watch time and unique viewers.
And what it doesn't: it isn't DRM, it runs as a single replica, and it doesn't
do live streaming. [Limitations](/docs/self-host/limitations) has the full
list.
## Licence [#licence]
The server is AGPL-3.0. The packages your app embeds, `@clipmux/node`,
`@clipmux/player` and `@clipmux/uploader`, are MIT.
---
# Build with ClipMux
Add uploads, webhooks and private playback to your app, with the Node SDK or the REST API.
Source: https://clipmux.com/docs/build
Your app talks to a ClipMux server the way it would talk to Mux: it creates
uploads, hears about them through webhooks, and plays them with tokens it
signs. The browser talks only to your app. It never sees an API key or a
signing key.
With the Node SDK, the whole integration is one command, one route file, two
elements and three callbacks.
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
From any other language, call the REST API and sign playback tokens as
standard ES256 JWTs.
## Get started [#get-started]
Add video to a Next.js app in four steps.
Upload, wait for it, and play it, with nothing but HTTP.
Videos, playback IDs, tokens and tracks, and how they fit.
Give a coding agent everything it needs to integrate ClipMux.
## Guides [#guides]
From the browser, a URL, the command line, or your own UI.
The player, signed tokens, public videos, posters and share links.
Subtitles, transcripts and chapters, made on the server.
Keep your records in step with each video.
Views, watch time and unique viewers.
Next.js, Express, Hono, other Fetch runtimes, and any language.
## Before you ship [#before-you-ship]
- [Production checklist](/docs/build/going-live/production-checklist)
- [Troubleshooting](/docs/build/going-live/troubleshooting): each error and
what to do
- [API reference](/docs/reference/api)
---
# Quickstart
Add uploads, webhooks and private playback to a Next.js app in four steps.
Source: https://clipmux.com/docs/build/quickstart
By the end of this page, a signed-in user of your app uploads a video from the
browser, your database hears when it's ready, and a viewer your app allows
watches it, encrypted. The browser never sees a ClipMux key.
It takes one command, one route file, two elements and three callbacks. The
same handler runs in [Express](/docs/build/frameworks/express),
[Hono](/docs/build/frameworks/hono) and
[other Fetch runtimes](/docs/build/frameworks/fetch-runtimes).
## Before you start [#before-you-start]
- A ClipMux server, for example `https://video.example.com`, and an owner
account on it to approve your app. To run one, see
[Install with one line](/docs/self-host/install).
- A Next.js app with the App Router, on Node 20.19 or later.
## Add ClipMux [#add-clipmux]
### Connect the app [#connect-the-app]
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
`init` opens an approval page on your ClipMux server. Approve the app there,
as the owner, and `init` writes its credentials to `.env.local`:
`CLIPMUX_URL`, `CLIPMUX_API_KEY`, `CLIPMUX_SIGNING_KID`,
`CLIPMUX_SIGNING_KEY` and `CLIPMUX_WEBHOOK_SECRET`. It never prints them.
Keep `.env.local` out of git.
### Add one route file [#add-one-route-file]
```ts title="app/api/clipmux/[action]/route.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
export const POST = clipmuxHandler({
// Someone wants to upload: say what the upload is, or return null to refuse.
async upload(req, { file }) {
await requireInstructor(req)
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name, generate: { subtitles: true } }
},
// Someone wants to watch: say who they are, or return null to refuse.
async playback(req, { playbackId }) {
const user = await getUser(req)
return (await canWatch(user, playbackId)) ? { viewerId: user.id } : null
},
// A verified webhook, with the video re-fetched so it's current.
async asset(asset) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
})
```
The file answers POST requests on three of your app's routes: `/api/clipmux/upload`, `/playback` and
`/webhook`. `requireInstructor`, `getUser`, `canWatch` and `db` stand for
your own code. Every route refuses by default: a callback you leave out is a
404, and one that returns `null` is a 403.
`passthrough` is your own ID for the video. It comes back on every webhook,
so you can find the record it belongs to. See
[Link videos to your records](/docs/build/upload/passthrough).
### Add two elements [#add-two-elements]
```tsx title="app/lessons/[id]/video.tsx"
'use client'
import type {} from '@clipmux/player/react' // JSX types only
import type {} from '@clipmux/uploader/react'
import { useEffect } from 'react'
export function LessonVideo({ lessonId, playbackId }: { lessonId: string; playbackId?: string }) {
// The elements need the DOM, so load them in the browser only.
useEffect(() => {
import('@clipmux/uploader/element')
import('@clipmux/player/element')
}, [])
return (
<>
{playbackId && }
>
)
}
```
The uploader sends the file in parts straight to storage, and resumes if the
connection drops. The player asks your `playback` callback for a token before
it plays, and again when the token runs out. Outside React, the same two
elements work in plain HTML:
```html
```
### Check it [#check-it]
```bash
npx @clipmux/node doctor
```
`doctor` checks every credential and ends with `✓ Ready.` It also prints the
origins your Content-Security-Policy must allow.
While you develop, your laptop can't receive webhooks from the server, so
forward them:
```bash
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
## Check it works [#check-it-works]
1. Open a lesson page, choose a short video in the uploader and wait for it
to finish.
2. Watch the `listen` terminal: `video.asset.ready` arrives when encoding is
done, and your `asset` callback stores the status and the playback ID.
3. Reload the page. The video plays.
To test without the browser, upload a file from the terminal:
```bash
npx @clipmux/node upload sample.mp4 --passthrough lesson_42 --wait
```
If a step fails, [Troubleshooting](/docs/build/going-live/troubleshooting)
lists each error and what to do.
## Next [#next]
- [`examples/nextjs-lms`](https://github.com/visheshgubrani/clipmux/tree/main/examples/nextjs-lms):
these four steps in a whole course site
- [Receive webhooks](/docs/build/webhooks): every event, and keeping your
records in step
- [Add the player](/docs/build/play/player): events, React, subtitles and
chapters
- [Production checklist](/docs/build/going-live/production-checklist)
---
# Your first video with curl
Upload a file, wait for it to encode and play it, using nothing but curl and jq against the API.
Source: https://clipmux.com/docs/build/first-video
This page walks one video through the API by hand: you create an upload with
your API key, send the file in parts straight to storage, tell ClipMux the
upload is complete, wait until the video is ready, and play its
`master.m3u8`. It's the same sequence the SDK and `` run
for you, so it's worth doing once to see what they do.
Every request and response here is in the
[API reference](/docs/reference/api/uploads).
## Before you start [#before-you-start]
- A ClipMux server, for example `https://video.example.com`. To run one, see
[Install with one line](/docs/self-host/install).
- An API key for an app, `cmx_…`, with the default scopes (`uploads:write`,
`assets:read`, `assets:write`). `npx @clipmux/node init` writes one to
`.env.local`; you can also create one under **Apps & API** in the
dashboard, or with `clipmux admin create-key --app NAME` on the server.
- `curl`, `jq` and a short video file, here `lesson-42.mp4`.
```bash
export CLIPMUX_URL=https://video.example.com
export CLIPMUX_API_KEY=cmx_…
FILE=lesson-42.mp4
```
The API key is a secret. Use it from a terminal or your backend, never in
browser code. The browser side of an upload uses the upload token, which
reaches only that one upload.
## Upload and play [#upload-and-play]
### Create the upload [#create-the-upload]
Send the file's size in bytes. `passthrough` is your own ID for the video
and `title` is a name for people; both are optional.
```bash
SIZE=$(wc -c < "$FILE" | tr -d ' ')
curl -s "$CLIPMUX_URL/v1/uploads" \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-d "{\"size\": $SIZE, \"passthrough\": \"lesson_42\", \"title\": \"Lesson 42\"}" \
| tee upload.json
```
```json
{
"upload_id": "upl_…",
"asset_id": "ast_…",
"part_size": 33554432,
"part_count": 22,
"upload_token": "M4XQ7R2VK6WT5ZJYBNC3D4F7GH",
"playback_ids": [{ "id": "pid_…", "policy": "signed", "playable": false, "status": "active" }]
}
```
The video exists at once, as `ast_…` in `waiting_upload`, with a private
(`signed`) playback ID you can store before the file arrives. Every part is
`part_size` bytes (32 MiB) except the last.
```bash
UPLOAD_ID=$(jq -r .upload_id upload.json)
ASSET_ID=$(jq -r .asset_id upload.json)
UPLOAD_TOKEN=$(jq -r .upload_token upload.json)
PART_SIZE=$(jq -r .part_size upload.json)
PART_COUNT=$(jq -r .part_count upload.json)
```
### Send the parts [#send-the-parts]
For each part, ask ClipMux for a signed URL with the upload token, `PUT` the
part's bytes to it, and keep the `ETag` header storage answers with. You can
sign up to 100 part numbers in one call, and each URL lasts an hour; this
loop signs one part at a time to keep it short.
```bash
echo '[]' > parts.json
for n in $(seq 1 "$PART_COUNT"); do
URL=$(curl -s "$CLIPMUX_URL/v1/uploads/$UPLOAD_ID/parts" \
-H "Authorization: Bearer $UPLOAD_TOKEN" \
-H 'Content-Type: application/json' \
-d "{\"part_numbers\": [$n]}" | jq -r '.parts[0].url')
dd if="$FILE" of=part.bin bs="$PART_SIZE" skip=$((n - 1)) count=1 2>/dev/null
ETAG=$(curl -s -T part.bin -D - -o /dev/null "$URL" \
| grep -i '^etag:' | cut -d' ' -f2 | tr -d '\r')
jq --argjson n "$n" --arg etag "$ETAG" \
'. + [{part_number: $n, etag: $etag}]' parts.json > parts.tmp && mv parts.tmp parts.json
done
rm part.bin
```
The parts go straight to storage, not through your backend. If the loop
stops halfway, `GET /v1/uploads/{id}/parts` with the upload token lists the
parts storage already holds, so you send only the rest. An upload left idle
for 24 hours expires.
### Complete the upload [#complete-the-upload]
Send every part's number and `ETag`:
```bash
jq '{parts: .}' parts.json | curl -s "$CLIPMUX_URL/v1/uploads/$UPLOAD_ID/complete" \
-H "Authorization: Bearer $UPLOAD_TOKEN" \
-H 'Content-Type: application/json' \
-d @- | jq '{id, status}'
```
The answer is the video, now `processing`. Encoding has started.
### Wait until it's ready [#wait-until-its-ready]
Ask for the video until its status moves on from `processing`:
```bash
while :; do
STATUS=$(curl -s "$CLIPMUX_URL/v1/assets/$ASSET_ID" \
-H "Authorization: Bearer $CLIPMUX_API_KEY" | jq -r .status)
echo "$STATUS"
[ "$STATUS" = processing ] || break
sleep 10
done
```
It ends `ready`, or `errored` with an `error_code` saying why. In an app,
don't poll: ClipMux sends `video.asset.ready` to your webhook endpoint. See
[Receive webhooks](/docs/build/webhooks).
### Play it [#play-it]
Get the playback ID and the media origin, `base_url`, from the video:
```bash
curl -s "$CLIPMUX_URL/v1/assets/$ASSET_ID" \
-H "Authorization: Bearer $CLIPMUX_API_KEY" > asset.json
PLAYBACK_ID=$(jq -r '.playback_ids[0].id' asset.json)
BASE_URL=$(jq -r .base_url asset.json)
```
The video is private, so it plays only with a token: a short JWT your
backend signs with your app's signing key. Sign one as
[Sign playback tokens](/docs/build/play/sign-tokens) shows, in Node, Python,
Go or PHP, and put it in `TOKEN`. Then:
```bash
echo "$BASE_URL/v/$TOKEN/$PLAYBACK_ID/master.m3u8"
```
Safari plays that URL directly, and so does
[``](/docs/build/play/player).
To skip the token for a throwaway test, create the upload with
`"playback_policy": "public"`. Anyone with the URL can then watch it at
`$BASE_URL/p/$PLAYBACK_ID/master.m3u8`. See
[Public videos](/docs/build/play/public-videos).
## Check it works [#check-it-works]
```bash
curl -s -o /dev/null -w '%{http_code}\n' "$BASE_URL/v/$TOKEN/$PLAYBACK_ID/master.m3u8"
```
`200` means the video plays. If a step failed, the error's `code` says why:
- `401 unauthorized` on create: the API key is wrong or revoked.
- `403 insufficient_scope`: the key lacks `uploads:write` (create) or
`assets:read` (the status loop).
- `413 too_large`: the file is over this server's upload limit. See
[Limits and defaults](/docs/reference/limits).
- `400 invalid_parts` on complete: an `ETag` is missing or wrong, usually
because a `PUT` failed. Check `parts.json` for an empty `etag`, send that
part again and complete again.
- `409 upload_expired`: the upload sat idle for 24 hours. Create a new one.
- The status ends `errored`: `error_code` says why, for example
`unsupported_source` for a file that isn't a video ClipMux can read.
- `401 token_expired` or `403 denied` when playing: the token is expired or
wrong. See [Sign playback tokens](/docs/build/play/sign-tokens).
Every code is in [Errors](/docs/reference/errors).
## Next [#next]
- [Quickstart](/docs/build/quickstart): the same flow in an app, with the
uploader and the player
- [Choose an upload method](/docs/build/upload)
- [A video's lifecycle](/docs/build/concepts/lifecycle)
---
# AI and agents
Point a coding agent at the files that teach it ClipMux, from a one-line prompt or the agent skills to every page as Markdown.
Source: https://clipmux.com/docs/build/ai-and-agents
A coding agent can add ClipMux to your app if it reads the right file first.
These docs publish one written for that job, plus every page as Markdown and
the API as an OpenAPI spec, so the agent works from the same facts you do
instead of guessing.
## Start with one prompt [#start-with-one-prompt]
Paste this into Claude Code, Cursor, Codex or any agent that can fetch a URL,
from your app's project:
```txt
Read https://clipmux.com/agents.md, then add ClipMux uploads, webhooks and signed playback to this app.
```
`https://clipmux.com/agents.md` is the onboarding guide for agents. It
gives the rules (no secret in browser code, no hand-rolled HMAC or JWT code,
access decided in your own callbacks), the steps from
`npx @clipmux/node init` to `doctor`, and a table of error codes with their
fixes. It also links to the docs index, the Build docs in full,
Troubleshooting and the OpenAPI spec.
The guide's body is the `AGENTS.md` that ships inside the `@clipmux/node`
package, so an agent that has already installed the SDK finds the same text
at `node_modules/@clipmux/node/AGENTS.md`, matching the installed version.
`init` asks the ClipMux server's owner to approve the app in the
dashboard, so the agent will ask you to open an approval link. It writes
the credentials to `.env.local` without printing them, and the guide tells
the agent never to print or log them either.
## Install the skills [#install-the-skills]
ClipMux publishes two agent skills, in the `SKILL.md` format that Claude
Code, Cursor, Codex and other agents load when a task needs them. Install
them from your app's project:
```bash
npx skills add visheshgubrani/clipmux
```
| Skill | What it covers |
| --- | --- |
| `clipmux-integrate` | Your backend: `init`, the route file with `clipmuxHandler` (Next.js, Express, the Fetch runtimes), the webhook, signed playback, `passthrough`, subtitles and chapters, `doctor`, and every error code with what to do |
| `clipmux-player` | Your pages: `` and `` with `session-url`, in React and Next.js or plain HTML |
They are short on purpose and link to these docs for detail, so they stay
current. The skills and their evals are in
[`skills/`](https://github.com/visheshgubrani/clipmux/tree/main/skills).
Then ask the agent to add ClipMux uploads, webhooks and signed playback.
## The docs as Markdown [#the-docs-as-markdown]
| URL | What it holds |
| --- | --- |
| `https://clipmux.com/llms.txt` | The index, in the llms.txt format: every page's title, its one-line description and a link to its Markdown. |
| `https://clipmux.com/llms-full.txt` | Every page in one file. |
| `https://clipmux.com/docs/build/llms-full.txt` | The Build tab in one file: integrating an app. |
| `https://clipmux.com/docs/self-host/llms-full.txt` | The Self-host tab in one file: installing and running a server. |
| `https://clipmux.com/docs/reference/llms-full.txt` | The Reference tab: the API, webhooks, errors, limits, settings and CLI. |
| `https://clipmux.com/docs/resources/llms-full.txt` | The Resources tab: migrating, the architecture, the FAQ. |
Every page is also served as Markdown at its own URL plus `.md`. This page,
for example, is at `https://clipmux.com/docs/build/ai-and-agents.md`, and the
introduction at `https://clipmux.com/docs.md`.
For an agent with a small context, point it at the tab it needs rather than
`llms-full.txt`: an app integration needs only the Build tab.
## Page actions [#page-actions]
Each page has two buttons under its title and description:
- **Copy page** copies the page's Markdown, to paste into any chat.
- **Open in** opens the page's Markdown (**View as Markdown**), starts a chat
in **Claude**, **ChatGPT** or **Cursor** that is told to read the page and
help you with ClipMux, or opens the page's source on GitHub
(**Edit on GitHub**).
Open in Claude, ChatGPT or Cursor sends that service a prompt naming the
page's public URL, and nothing else. What you then type into the chat goes
to that service under its own terms.
## The OpenAPI spec [#the-openapi-spec]
The integration API, the delivery URLs and the webhooks are described as
OpenAPI 3.1 at `https://clipmux.com/openapi.json`. Every ClipMux server
also serves its own copy at `GET /openapi.json`, with no credential, so an
agent can read the spec of the exact version you run:
```bash
curl -s https://video.example.com/openapi.json | jq '.info.version, (.paths | keys)'
```
Use it to generate a client in another language, or to let an agent check
a request before it sends one. The routes the dashboard uses with the
owner's session are not in it; see the
[Management API](/docs/reference/management-api).
## Check it works [#check-it-works]
Ask the agent to run, once it has finished:
```bash
npx @clipmux/node doctor
```
It must end with `✓ Ready.` If it doesn't, each line names the credential or
setting that failed. Then upload a test file:
```bash
npx @clipmux/node upload sample.mp4 --passthrough lesson_42 --wait
```
## Next [#next]
- [Quickstart](/docs/build/quickstart): the steps the agent follows, for a
person
- [Troubleshooting](/docs/build/going-live/troubleshooting)
- [API reference](/docs/reference/api)
---
# How ClipMux works
The handful of objects an app works with, from the app and its keys to the video, its outputs, playback IDs and tracks.
Source: https://clipmux.com/docs/build/concepts/how-it-works
An app talks to ClipMux about a few objects. Once you know what each one is
and which ones change, the API reads plainly: a video holds one playable
output at a time, playback IDs are the handles viewers use, and an upload is
how a file arrives.
## Video and asset [#video-and-asset]
These docs say **video**. The API says **asset**: the routes are
`/v1/assets`, the IDs are `ast_…`, and webhook events start with
`video.asset.`. They are the same thing. The rest of these docs use "asset"
only where the API does.
## The objects [#the-objects]
| Object | ID | What it is |
| --- | --- | --- |
| App | `app_…` | One integration, such as a course site or a marketing site. It owns its API keys (`cmx_…`), its signing keys, its webhook endpoints and the videos it creates. |
| Video (asset) | `ast_…` | The video as the API sees it: its `status`, its `version`, your `passthrough`, its `title`, and the source file it was made from. |
| Output | | One encoded, encrypted set of HLS files for a video: the renditions, the audio, the playlists and the poster. An output never changes once written. You never address one directly. |
| Playback ID | `pid_…` | The handle in a playback URL. Private (`signed`) or public, several per video, each revocable on its own. |
| Track | `trk_…` | A subtitles or chapters track, made from the video after it is ready. |
| Upload | `upl_…` | One file on its way into storage, in 32 MiB parts. It fills one video's source, and expires after 24 hours idle. |
The ClipMux server's owner manages apps, keys and webhook endpoints in the
dashboard. The dashboard's own uploads go to a built-in Dashboard app unless
the owner picks another, and the dashboard sees every app's videos.
## How they relate [#how-they-relate]
1. Your backend creates an **upload** with its app's API key. The **video**
exists at once, in `waiting_upload`, with one **playback ID**.
2. The browser sends the file's parts straight to storage with the upload
token, and completes the upload. The file becomes the video's source.
3. A worker encodes the source into a new **output**. When the output is
written, the video points at it and becomes `ready`.
4. A viewer plays a **playback ID**. Delivery follows the playback ID to its
video, and the video to its current output.
5. **Tracks** are made from the ready video if you asked for them. Subtitles
play inside the same playlist; each track is also a WebVTT file.
A video points at one current output. A re-encode writes a new output beside
the old one, and the pointer moves only once the new one is complete, so
viewers never see a half-written video. That pointer is the only thing that
moves: playback IDs never point at files, so adding or revoking one moves no
files, and a cached segment never goes stale.
Each output has its own encryption key, so a re-encode brings a new key too.
See [What encryption does and doesn't do](/docs/build/concepts/encryption).
## Where the work happens [#where-the-work-happens]
- **The server**, `clipmux serve`, holds the objects in Postgres and answers
the API. It is one Go binary.
- **Workers** encode. They run on the server itself, on a PC you own, or on
Modal or RunPod. A worker gets URLs signed for one job, never storage
credentials.
- **Storage** holds sources and outputs: the server's own disk, or an
S3-compatible bucket such as R2.
- **Delivery** serves playlists, segments and keys to viewers: the server's
built-in handler, or a Cloudflare Worker at the edge.
Running these is the server owner's job; see
[Self-host ClipMux](/docs/self-host). An app sees only the API, the media
origin (`base_url`) and its webhooks.
## Next [#next]
- [A video's lifecycle](/docs/build/concepts/lifecycle)
- [Playback IDs and tokens](/docs/build/concepts/playback-ids-and-tokens)
- [Architecture overview](/docs/resources/architecture)
---
# A video's lifecycle
The five states a video moves through, what moves it, and what a re-encode does to a video that is already playing.
Source: https://clipmux.com/docs/build/concepts/lifecycle
A video has one of five statuses, in the asset's `status` field. The status
says whether it can play; the work of encoding (probing, transcoding,
packaging) is tracked on jobs, so a video that is ready stays ready while it
is encoded again.
## The states [#the-states]
| Status | What it means | Plays? |
| --- | --- | --- |
| `waiting_upload` | The video exists and its playback IDs are made, but the file hasn't arrived. | No |
| `processing` | The file has arrived and is being encoded. | No |
| `ready` | An output is published. | Yes |
| `errored` | The upload, the import or the first encode failed. `error_code` says why. | No |
| `deleted` | The video was deleted. Its playback stopped at once. | No |
## What moves it [#what-moves-it]
| From | To | When | Webhook |
| --- | --- | --- | --- |
| (new) | `waiting_upload` | Your backend creates an upload with `POST /v1/uploads`. | |
| (new) | `processing` | Your backend imports a URL with `POST /v1/assets`. | |
| `waiting_upload` | `processing` | The upload is completed. | |
| `waiting_upload` | `errored` | The upload is cancelled (`upload_cancelled`) or sits idle for 24 hours (`upload_expired`). | `video.asset.errored` |
| `processing` | `ready` | The first output is written and published. | `video.asset.ready` |
| `processing` | `errored` | The import or the encode fails for good, for example `import_failed` or `unsupported_source`. | `video.asset.errored` |
| `errored` | `processing` | You re-encode it with `POST /v1/assets/{id}/reencode`, if its source was kept. | |
| `ready` | `ready` | A re-encode finishes, the title changes, a playback ID is published, or the files move storage. | `video.asset.updated` |
| any | `deleted` | You delete it with `DELETE /v1/assets/{id}`. | `video.asset.deleted` |
The asset's `version` rises on every change. Webhooks are delivered at least
once and in no fixed order, so keep the highest `version` you have stored
and ignore an older snapshot. See [Receive webhooks](/docs/build/webhooks).
## Re-encoding a ready video [#re-encoding-a-ready-video]
`POST /v1/assets/{id}/reencode` encodes the source again, for example with
other [renditions](/docs/build/upload/renditions). The new encode writes a
new output beside the current one:
- The video stays `ready`, and viewers keep watching the current output.
- When the new output is complete, the video switches to it in one step and
you get `video.asset.updated`. Players that start after that get the new
output.
- If the re-encode fails, the current output keeps playing and you get
`video.asset.reencode_failed`, with `job.error_code` saying why.
Only one job that changes a video runs at a time. A second re-encode while
one runs is `409 job_active`, with the running job's `job_id`; send
`"supersede": true` to cancel the running job and start yours. A delete
always wins: it cancels whatever is running.
A re-encode needs the source file. A video still `waiting_upload` has none
(`409 asset_not_ready`), and one whose source was not kept can't be encoded
again (`409 source_missing`).
## Tracks [#tracks]
Subtitles and chapters have their own status, on each track: `preparing`,
`ready` or `errored`. They are made after the video is ready and never hold
it up, so expect `video.asset.ready` first, then
`video.asset.track.ready` or `video.asset.track.errored`. See
[Subtitles and transcripts](/docs/build/captions/subtitles).
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Webhook events](/docs/reference/webhooks)
- [Errors](/docs/reference/errors): every `error_code`
---
# Playback IDs and tokens
How a viewer reaches a video through a playback ID, why a private one needs a token your backend signs, and what revoking either does.
Source: https://clipmux.com/docs/build/concepts/playback-ids-and-tokens
A viewer never sees a video's `ast_…` ID. They play a **playback ID**, and
for a private video they also need a **token**: proof, signed by your
backend, that your app let this viewer watch this video for a while.
## Playback IDs [#playback-ids]
A playback ID, `pid_…`, is the handle in a playback URL:
```txt
https://media.example.com/v/{token}/{playback_id}/master.m3u8 private
https://media.example.com/p/{playback_id}/master.m3u8 public
```
- **Private or public.** Its `policy` is `signed` (plays only with a token)
or `public` (plays for anyone with the URL). A new video gets one
playback ID with the `playback_policy` you asked for, `signed` by default.
- **Several per video.** Add one with `POST /v1/assets/{id}/playback-ids`,
up to 1000 per video. A video can have private and public IDs at once,
for example a public one for a trailer page and a private one for paying
viewers. Share links each make their own private ID.
- **Revocable one at a time.** `DELETE /v1/assets/{id}/playback-ids/{pid}`
stops that ID; the video's other IDs keep playing.
- **Cheap.** A playback ID points at the video, not at files, so adding or
revoking one copies or moves nothing.
Each playback ID in the asset has a `status` (`active`, `revoking`,
`revoked`) and `playable`, which is `false` until the video has an output
and again once the ID is revoked.
### What revoking does, and how fast [#what-revoking-does-and-how-fast]
The revoke call answers `200` with `revoked` once the ID is unpublished, or
`202` with `revoking` while ClipMux is still unpublishing it. After that,
every request for the ID answers `404`, including from players that are
already watching, and existing tokens for it stop working.
With built-in delivery, a revoked ID stops at once. With
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare), the edge
caches route records for up to 60 seconds, so a revoked ID stops within a
minute.
To stop everything for a video, delete it: its playback stops at once.
## Tokens [#tokens]
A token is an ES256 JWT that your backend signs with your app's signing key.
It goes in the URL path, so every playlist, segment and key URL the player
follows carries it without any player hooks.
| Claim | Meaning |
| --- | --- |
| `sub` | The playback ID it is for. A token for one ID can't play another. |
| `aud` | `v` plays the video: playlists, segments, tracks, the poster and the decryption key. `t` fetches only the poster, so a catalogue can show posters for videos a viewer can't play yet. |
| `iat`, `exp` | Issued and expiry times, in whole seconds. |
| `vid` | Optional. A stable ID for the viewer, used to count unique viewers. ClipMux stores only a keyed hash of it. |
The header's `kid` names the signing key. A token signed by another app's
key is refused, even for a valid playback ID.
### Lifetime [#lifetime]
`exp - iat` may be at most `max_token_lifetime_seconds`, from `GET /v1/app`:
7 days unless the server's owner changed it. A token issued more than 60
seconds in the future is refused too.
Keep tokens short and let the player renew them: `` asks
your backend for a new token when the old one expires, and resumes where it
was. Players ClipMux doesn't control, such as iOS before 17.1 and
AirPlay, can't renew mid-video, so sign their tokens for longer. See
[Sign playback tokens](/docs/build/play/sign-tokens).
When a token is refused, delivery says why:
- `401 token_expired`: `exp` has passed. Get a new token.
- `403 denied`: the signature, key, playback ID, audience or lifetime is
wrong. A new token signed the same way won't help.
- `404`: the playback ID doesn't exist, is revoked, or its video has no
output yet.
### Why signing is local [#why-signing-is-local]
ClipMux keeps only your signing key's public half. Your backend signs with
the private half, on its own, after your own code has decided the viewer may
watch, and delivery checks the signature when the player asks. So there is
no call to ClipMux per play, ClipMux never needs to know who your users
are, and playback keeps working if your backend can't reach the API.
### Revoking and rotating signing keys [#revoking-and-rotating-signing-keys]
- **Revoking** a signing key ends every token it signed: built-in delivery
refuses them at once, the Cloudflare edge within a minute. Do this if the
private key leaks.
- **Rotating** adds a new key and retires the old ones once the longest
token they may have signed has expired, so no viewer is cut off. Use
`clipmux admin rotate-signing-key --app NAME` on the server.
`GET /v1/app` lists the keys that still verify tokens, newest first, in
`signing_keys`. See [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets).
## Next [#next]
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Public videos](/docs/build/play/public-videos)
- [Share links](/docs/build/play/share-links)
---
# What encryption does and doesn't do
Every video is stored and streamed as AES-128 encrypted HLS, which protects your storage but is not DRM.
Source: https://clipmux.com/docs/build/concepts/encryption
Every output ClipMux writes is encrypted. That keeps your stored videos
useless to anyone who gets at the bucket or the disk, and makes a leaked
segment URL worthless on its own. It does not stop a viewer who may watch a
video from saving it. This page says plainly where the line is.
## What it does [#what-it-does]
- **Every segment is encrypted with AES-128**, the standard HLS encryption
that every HLS player supports. You turn nothing on.
- **Storage holds only ciphertext.** Segments, and subtitles and chapters
files, are encrypted at rest. A leaked bucket, stolen storage credentials
or a copied disk exposes no playable output.
- **The key is handed out behind the token.** Each media playlist names its
key by a URL that carries the same token as the segments. Delivery answers
only a request that passes the same checks: a `v` token for that playback
ID, or a public playback ID. A `t` (poster-only) token can't fetch it, and
the answer is never cached.
- **Keys are derived, not stored.** Each output's key is derived on request
from the server's content key secret, the video's ID and the output's ID.
There is no table of keys to leak, and a token for one video can't fetch
another video's key.
- **Each output has its own key.** A re-encode brings a new key, so a leaked
key exposes one version of one video.
- **The secret is sealed.** The content key secret is stored in Postgres,
encrypted with a key held outside it. A worker that encodes a video
receives only the key for the output it writes.
## What it doesn't do [#what-it-doesnt-do]
- **It is not DRM.** Anyone with a valid token can fetch the key, and common
download tools do that automatically. A viewer you let watch a video can
save it, and anyone can record their screen. ClipMux has no Widevine,
FairPlay or PlayReady, and no licence server.
- **It doesn't replace tokens.** Encryption is a layer behind access
control. Who may watch is decided by your backend when it signs a token,
and by revoking playback IDs. A public playback ID serves its key to
anyone, by design.
- **It doesn't encrypt the source.** The file you upload is kept as
uploaded, in the same storage, so it can be encoded again. Protect the
bucket or disk as you would any copy of your videos. See
[Where videos are stored](/docs/self-host/storage).
To limit what a leaked token can do, keep tokens short and pass a `vid`
claim, so analytics can show who watched. See
[Playback IDs and tokens](/docs/build/concepts/playback-ids-and-tokens).
## If the secret leaks [#if-the-secret-leaks]
The server's owner rotates the content key secret, and re-encodes the
videos that matter. New outputs use the new secret; old outputs keep playing
with the version they were made with until they are encoded again. Losing
the secret, or the key that seals it, makes every output unplayable, so it
belongs in backups. See [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)
and [Back up and restore](/docs/self-host/operate/backups).
## Next [#next]
- [Security model](/docs/self-host/security-model)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Limitations](/docs/self-host/limitations)
---
# Choose an upload method
Compare the ways a video gets into ClipMux, from a drop zone in your app to a URL import or a terminal, and pick the one that fits.
Source: https://clipmux.com/docs/build/upload
Every method below ends in the same place: a video that encodes, sends your
webhook `video.asset.ready`, and plays through its playback ID. They differ
in where the file starts and who sends it. Whichever you pick, the file goes
straight to storage, and an API key never reaches a browser.
| Method | The file starts | Use it when |
| --- | --- | --- |
| [The browser element](/docs/build/upload/browser) | On a user's device | Your users upload from your app, and a ready-made drop zone with progress, Cancel and Retry is enough. |
| [Headless](/docs/build/upload/headless-and-uppy) | On a user's device | You want your own upload interface, or a client other than a web page. |
| [Import from a URL](/docs/build/upload/from-url) | On a public URL | The file is already online, for example in another bucket or on the video host you are leaving. |
| [The command line](/docs/build/upload/command-line) | On your machine | You're testing an integration, or loading a folder of existing videos. |
| [The dashboard](/docs/self-host/dashboard) | On the owner's machine | The server's owner adds a video by hand, without any app code. |
Uploads and imports through the API take the same options: `passthrough`
(your own ID), `title`, `playback_policy`, `generate` (subtitles and
chapters) and `renditions`. The command lines take a subset of them, as
flags.
A drop zone that resumes after a reload.
The upload class and routes, for your own interface.
The server fetches a public URL itself.
Push files and folders from a terminal.
Tag each video with your own ID.
Pick the resolutions to encode, up to 2160p.
## Limits [#limits]
An upload may be up to 312.5 GiB (10,000 parts of 32 MiB), or less if the
server's owner set a lower limit. An upload left idle for 24 hours expires.
See [Limits and defaults](/docs/reference/limits).
## Next [#next]
- [Your first video with curl](/docs/build/first-video): the upload routes by
hand
- [A video's lifecycle](/docs/build/concepts/lifecycle)
- [Receive webhooks](/docs/build/webhooks)
---
# Upload from the browser
Add a drop zone that sends a file straight to storage in resumable parts, with your backend deciding who may upload.
Source: https://clipmux.com/docs/build/upload/browser
`` is a drop zone with a file button, a progress bar,
Cancel and Retry. It asks your backend to create the upload, sends the file
in parts straight to storage (not through your server), resumes after a
dropped connection or a reload, and tells you when the upload is complete.
The browser never holds an API key.
It comes from `@clipmux/uploader`, which has no dependencies.
## Before you start [#before-you-start]
- A backend route that creates uploads. With `@clipmux/node`, that is the
`upload` callback of `clipmuxHandler` from the
[quickstart](/docs/build/quickstart); to write your own, see
[Your backend route](#your-backend-route) below.
- The package:
```bash
npm i @clipmux/uploader
```
```bash
pnpm add @clipmux/uploader
```
## Add the element [#add-the-element]
```html
```
```ts
const uploader = document.querySelector('clipmux-uploader')!
uploader.addEventListener('clipmux-uploaded', (e) => {
console.log(e.detail.asset.id) // processing: your webhook hears when it's ready
})
```
When someone chooses or drops a file, the element POSTs
`{"size", "name", "type"}` as JSON to `create-url`, with the page's cookies,
so your backend can check who is asking. Put your own IDs in the URL, as
`?lesson=42` does here.
### Attributes [#attributes]
| Attribute | What it does |
| --- | --- |
| `create-url` | Your backend's route that creates the upload. Required. |
| `accept` | The files it takes, as on ` `, for example `video/*,.mkv`. Dropped files are checked too. |
| `max-size` | The largest file, in bytes. A larger one fails with `file_too_large` before anything is sent. |
| `state` | Set by the element, for styling: `idle`, `uploading`, `done` or `error`. |
The element also has a few properties and methods:
- `options` takes further upload options: `concurrency` (parts in flight,
default 4), `maxAttempts` (tries per request, default 6), and `store`
(where an unfinished upload is remembered, `localStorage` by default;
`null` turns that off).
- `upload(file)` uploads a file as choosing it does; `retry()` tries the
last failed upload again; `cancel()` stops it for good and tells ClipMux.
- `state`, `file` and `asset` read the current state, the file and, once
complete, the video.
### Events [#events]
Each event bubbles and is typed.
| Event | `detail` |
| --- | --- |
| `clipmux-progress` | `{ bytesUploaded, bytesTotal, partsDone, partsTotal }` |
| `clipmux-uploaded` | `{ asset }`: the video, now `processing`. |
| `clipmux-error` | `{ code, message, status, error }` |
`clipmux-error`'s `code` is one of:
- `file_type_rejected`: the file doesn't match `accept`.
- `file_too_large`: the file is over `max-size`.
- `create_denied`: `create-url` answered `401` or `403`, for example because
your `upload` callback returned `null`.
- An error code from ClipMux or storage, such as `too_large` (the file is
over the server's upload limit), or `network` when the connection kept
failing.
## Resume and retry [#resume-and-retry]
- The file goes in parts of the upload's `part_size` (32 MiB), up to four at
a time.
- Requests retry by themselves with backoff, honour `Retry-After`, and wait
while the browser is offline. A `4xx` such as `413 too_large` fails at
once.
- After a failure, Retry continues from what storage already holds.
- The upload is remembered in `localStorage`, keyed by the file's name,
size and modification time, until it completes. Choosing the same file
after a reload, or in a new tab, resumes it. If the remembered upload has
expired or been cancelled, the element creates a new one.
- An unfinished upload stays resumable for 24 hours. Cancel ends it for
good: the video becomes `errored` with `upload_cancelled`.
## Style it [#style-it]
- **Parts:** `dropzone`, `label`, `button`, `progress`, `bar`, `status`,
`cancel` and `retry`.
- **Custom properties:** `--clipmux-uploader-accent`, `--clipmux-uploader-border`,
`--clipmux-uploader-radius`, `--clipmux-uploader-background`,
`--clipmux-uploader-color` and `--clipmux-uploader-font`.
- **Slot:** the default slot replaces the drop zone's text, "Drop a video
here, or".
```css
clipmux-uploader {
--clipmux-uploader-accent: #0f766e;
--clipmux-uploader-radius: 4px;
}
clipmux-uploader::part(bar) {
transition: none;
}
clipmux-uploader[state='error']::part(status) {
color: #b91c1c;
}
```
```html
Drop your lesson video, or
```
## React [#react]
Import the JSX types once, and load the element in the browser only:
```tsx title="app/lessons/[id]/uploader.tsx"
'use client'
import type {} from '@clipmux/uploader/react' // JSX types only
import { useEffect } from 'react'
export function LessonUploader({ lessonId }: { lessonId: string }) {
useEffect(() => {
import('@clipmux/uploader/element')
}, [])
return (
console.log(e.detail.asset.id)}
/>
)
}
```
The types cover the attributes, `options` and the three `onclipmux-…`
events; React itself is not a dependency. React 19 passes the
`onclipmux-…` props to the element as event listeners when it creates the
element in the browser, but not when it hydrates server-rendered HTML (a
Next.js page's first load). There, and on React 18, add the listeners with a
ref and `addEventListener`.
## Your backend route [#your-backend-route]
The element needs `create-url` to answer with the created upload plus
`endpoint`, your ClipMux server's URL. With `clipmuxHandler`, the `upload`
callback returns how to create it, or `null` to refuse:
```ts
async upload(req, { file }) {
await requireInstructor(req) // your own check
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name }
}
```
It may also return `playback_policy`, `generate` and `renditions`.
To write the route yourself, check access, call `POST /v1/uploads` with your
API key, and answer with the body. `clipmux.uploads.create` returns it with
`endpoint` already added:
```ts
const upload = await clipmux.uploads.create({ size, passthrough: 'lesson_42' })
return Response.json(upload)
```
Without the SDK, add `endpoint` yourself:
```ts
const res = await fetch(`${process.env.CLIPMUX_URL}/v1/uploads`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.CLIPMUX_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ size, passthrough: 'lesson_42' }),
})
return Response.json({ ...(await res.json()), endpoint: process.env.CLIPMUX_URL })
```
`size` comes from the element's request body. The upload token in the answer
reaches only that one upload.
## Content-Security-Policy [#content-security-policy]
A page with the uploader must allow, besides its own origin:
- `connect-src`: your ClipMux server's URL, and the storage origins the
parts go to (`upload_origins` from `GET /v1/app`; the server's own URL
when it stores files on its own disk);
- `style-src 'unsafe-inline'`, for the element's styles.
`npx @clipmux/node doctor` prints the exact origins. Storage must also
expose the `ETag` header to the page; ClipMux sets that up on its own disk
and on the buckets it connects.
## Check it works [#check-it-works]
Choose a short video. The bar fills, the status reads "Uploaded" and the
`clipmux-uploaded` event fires with a video in `processing`. Then your
webhook receives `video.asset.ready`.
- `create_denied`: your route refused, or the browser sent no session
cookie. Check `create-url` is on your own origin.
- `create_invalid`: your route answered without an upload. It must return
the body of `POST /v1/uploads`, with `endpoint`.
- `etag_not_exposed`: storage doesn't expose `ETag` to the page; fix the
bucket's CORS rules.
- A request blocked in the console: the Content-Security-Policy is missing an
origin. Run `doctor`.
## Next [#next]
- [Headless uploads and Uppy](/docs/build/upload/headless-and-uppy): your own
upload UI
- [Link videos to your records](/docs/build/upload/passthrough)
- [@clipmux/uploader reference](/docs/reference/sdks/uploader)
---
# Headless uploads and Uppy
Drive uploads from your own interface with the ClipMuxUpload class, or from any client through the upload routes.
Source: https://clipmux.com/docs/build/upload/headless-and-uppy
When you want your own upload interface, use the class inside
`` directly: `ClipMuxUpload` from `@clipmux/uploader`. It
sends a file in parts straight to storage, resumes from what storage holds,
retries, and reports progress, and leaves every pixel to you. For anything
else, such as a native app or another upload library, the upload routes are
a small API of their own.
## Before you start [#before-you-start]
- A backend route that creates uploads: the `upload` callback of
`clipmuxHandler`, or your own route calling `POST /v1/uploads`. See
[Your backend route](/docs/build/upload/browser#your-backend-route).
- `npm i @clipmux/uploader`.
## Upload with ClipMuxUpload [#upload-with-clipmuxupload]
Give it the file and your `createUrl`, the same route the element uses:
```ts
import { ClipMuxUpload, ClipMuxUploadError } from '@clipmux/uploader'
const upload = new ClipMuxUpload(file, {
createUrl: '/api/clipmux/upload?lesson=42',
onProgress: (p) => setProgress(p.bytesUploaded / p.bytesTotal),
})
try {
const asset = await upload.start() // the video, processing
console.log(asset.id)
} catch (err) {
if (err instanceof ClipMuxUploadError) console.log(err.code, err.status, err.retryable)
}
```
`start()` POSTs `{size, name, type}` to `createUrl` with the page's cookies,
remembers the upload in `localStorage` so a reload resumes it, sends the
parts and completes the upload. Calling `start()` again after a rejection
continues from what storage holds.
| Method | What it does |
| --- | --- |
| `start()` | Uploads what storage doesn't hold yet and completes the upload. Resolves with the video. |
| `pause()` | Stops sending. Parts already stored stay. |
| `resume()` | Continues after `pause()`. |
| `cancel()` | Stops for good and tells ClipMux. The video becomes `errored` with `upload_cancelled`; resolves with it, or `null` when there was no upload yet. |
| `upload` | The upload in use, once there is one. |
| Option | Default | What it does |
| --- | --- | --- |
| `createUrl` | | Your backend route that creates the upload. Give this, `create` or `upload`. |
| `create` | | A function that creates the upload your own way and resolves with the body of `POST /v1/uploads`. Remembered like a `createUrl` upload. |
| `upload` | | An upload your backend already created: the body of `POST /v1/uploads`. Not remembered across a reload. |
| `endpoint` | the upload's `endpoint` | Your ClipMux server's URL, if the upload doesn't carry it. |
| `store` | `localStorage` | Where a `createUrl` or `create` upload is remembered until it completes; `null` forgets it on reload. |
| `concurrency` | `4` | Parts in flight at once. |
| `maxAttempts` | `6` | Tries per request before giving up. |
| `onProgress` | | Called with `{ bytesUploaded, bytesTotal, partsDone, partsTotal }`. |
| `signal` | | An `AbortSignal` that stops the upload. |
A failure rejects with a `ClipMuxUploadError` with `code`, `status` and
`retryable`, and leaves the upload resumable for 24 hours. Codes include
`create_denied` (your route answered `401` or `403`), `network`,
`etag_not_exposed`, and the API's own codes such as `too_large`.
## With an upload your backend created [#with-an-upload-your-backend-created]
If your backend creates the upload some other way, for example as part of
saving a form, give `create` a function that does it and the server URL
with `endpoint`:
```ts
import { ClipMuxUpload } from '@clipmux/uploader'
const asset = await new ClipMuxUpload(file, {
create: () => createUploadOnMyBackend(file.size),
endpoint: 'https://video.example.com',
}).start()
```
The upload is remembered in `localStorage` until it completes, so choosing
the same file after a reload resumes it, and one that ClipMux has ended
(expired, cancelled, its video deleted) is replaced by a new one. Only the
upload's ID, token and part layout are stored; ClipMux itself knows which
parts it holds. An upload you already hold goes in as `upload`, without the
memory. `clipmux.uploads.create` in `@clipmux/node` returns
the body with `endpoint` added, so the browser needs no other setting.
## The upload routes, for any client [#the-upload-routes-for-any-client]
`ClipMuxUpload` is a thin client of four routes. Any client that can make
HTTP requests can do the same, as
[Your first video with curl](/docs/build/first-video) does by hand.
| Step | Route | Credential |
| --- | --- | --- |
| Create the upload; get `upload_id`, `part_size`, `part_count` and `upload_token`. | `POST /v1/uploads` | Your API key, from your backend |
| Sign up to 100 part URLs, each good for an hour. | `POST /v1/uploads/{id}/parts` | The upload token |
| `PUT` each part's bytes to its URL; keep the `ETag` header. | The signed URL | None |
| On resume, list the parts storage holds. | `GET /v1/uploads/{id}/parts` | The upload token |
| Complete with every part's number and `ETag`. | `POST /v1/uploads/{id}/complete` | The upload token |
| Or cancel. | `POST /v1/uploads/{id}/cancel` | The upload token, or your API key |
Every part is exactly `part_size` bytes (32 MiB) except the last, and the
parts must number `part_count`. Upload-token requests are limited to 10 a
second per upload. Storage must expose `ETag` to a browser page.
## Uppy [#uppy]
There is no Uppy plugin for ClipMux. ClipMux's upload routes are its own,
not S3's API, and ClipMux never hands a browser S3 credentials or signs
arbitrary S3 requests, so Uppy's S3 plugin can't talk to them as it is. To
keep Uppy's interface, wire its upload step to `ClipMuxUpload`, or to the
routes above, yourself. Either way, test it against your server: ClipMux
doesn't test any Uppy release.
## Check it works [#check-it-works]
Upload a short file and watch `onProgress` reach `bytesTotal`. `start()`
resolves with a video whose `status` is `processing`. Reload halfway
through and start again with the same file: progress jumps to the parts
already stored.
- `create_invalid`: your `createUrl` route answered without an upload.
- `file_mismatch`: the file isn't the one the upload was created for (its
size gives a different number of parts).
- `part_url_rejected`: storage refused a part URL twice; check the server's
public URL and storage settings.
## Next [#next]
- [Upload from the browser](/docs/build/upload/browser)
- [Uploads in the API reference](/docs/reference/api/uploads)
- [@clipmux/uploader reference](/docs/reference/sdks/uploader)
---
# Import from a URL
Have your ClipMux server fetch a video from a public URL and encode it, with no upload from your side.
Source: https://clipmux.com/docs/build/upload/from-url
When the file is already online, for example in another bucket or on your
old video host, your backend can hand ClipMux its URL. The server fetches
the file itself, stores it as the video's source and encodes it exactly as
it would an upload. Nothing passes through your backend or a browser.
## Before you start [#before-you-start]
- An API key with `assets:write`, from your backend.
- A URL that anyone on the internet can fetch with a plain `GET`: `http` or
`https`, answering `200` with the file. A short-lived signed URL from your
own storage works, as long as it lasts while the import runs.
## Import a video [#import-a-video]
```ts
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux() // reads the CLIPMUX_* settings
const asset = await clipmux.assets.importUrl(
{
url: 'https://files.example.com/lesson-42.mp4',
passthrough: 'lesson_42',
title: 'Lesson 42: Sorting',
},
{ idempotencyKey: 'import-lesson_42' },
)
console.log(asset.id, asset.status) // ast_… processing
```
```python
import os, requests
res = requests.post(
f"{os.environ['CLIPMUX_URL']}/v1/assets",
headers={
"Authorization": f"Bearer {os.environ['CLIPMUX_API_KEY']}",
"Idempotency-Key": "import-lesson_42",
},
json={
"url": "https://files.example.com/lesson-42.mp4",
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
},
)
res.raise_for_status()
asset = res.json() # status: processing
```
```go
body := strings.NewReader(`{"url": "https://files.example.com/lesson-42.mp4",
"passthrough": "lesson_42", "title": "Lesson 42: Sorting"}`)
req, _ := http.NewRequest("POST", os.Getenv("CLIPMUX_URL")+"/v1/assets", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLIPMUX_API_KEY"))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "import-lesson_42")
res, err := http.DefaultClient.Do(req) // 201: the asset, processing
```
```php
$ch = curl_init(getenv('CLIPMUX_URL') . '/v1/assets');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('CLIPMUX_API_KEY'),
'Content-Type: application/json',
'Idempotency-Key: import-lesson_42',
],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://files.example.com/lesson-42.mp4',
'passthrough' => 'lesson_42',
'title' => 'Lesson 42: Sorting',
]),
]);
$asset = json_decode(curl_exec($ch), true); // status: processing
```
`POST /v1/assets` answers `201` with the video, already `processing`, and
its playback ID. With an `Idempotency-Key`, a retry of the same request
returns the same video instead of importing twice.
| Field | Default | What it does |
| --- | --- | --- |
| `url` | | The public `http` or `https` URL to fetch. Required. |
| `playback_policy` | `signed` | `signed` for a private video, `public` for one anyone with the URL can watch. |
| `passthrough` | | Your own ID for the video, up to 255 bytes. See [Link videos to your records](/docs/build/upload/passthrough). |
| `title` | | A name for people, one line, up to 200 characters. |
| `generate` | | `{ "subtitles": true, "chapters": true }` makes subtitles and chapters once the video is ready. Chapters imply subtitles. |
| `renditions` | every rung up to the source | The rungs to encode, for example `["1080p", "480p"]`. See [Choose renditions](/docs/build/upload/renditions). |
When the video is ready, your webhook receives `video.asset.ready`, as for
an upload.
## What is refused [#what-is-refused]
ClipMux fetches only public addresses, so an import can't be used to reach
the server's own machine or your private network. It refuses:
- a URL that isn't `http` or `https`, has no host, or is over 2048
characters;
- a URL with credentials in it, such as `https://user:pass@…`;
- a host that is, or resolves to, a loopback, private, link-local or other
non-public address, including cloud metadata addresses.
The address is checked on every connection, after DNS, and on each of up to
5 redirects, so a redirect or a DNS change can't lead around it. A URL that
is refused when you send it is `400 import_url_refused`, and nothing is
created. One that leads to a refused address later ends the video as
`errored` with `import_url_refused`.
## Sizes and failures [#sizes-and-failures]
The file may be up to 312.5 GiB (10,000 parts of 32 MiB), and one fetch may
take up to 6 hours. A fetch that fails for a passing reason (a network error,
or a `5xx`, `408` or `429` answer) is tried 3 times in all, with a growing
wait between tries.
An import that fails for good ends the video `errored`, sends
`video.asset.errored`, and sets `error_code`:
| `error_code` | What happened |
| --- | --- |
| `import_url_refused` | The URL, or an address it redirected to, is not public. |
| `import_failed` | The fetch kept failing, or the server answered something other than `200`, or an empty body. |
| `import_too_large` | The file is larger than the import limit. |
A file that arrives but isn't a video ClipMux can read fails later, at
encoding, like an upload would.
## Check it works [#check-it-works]
Get the video until it's ready:
```bash
curl -s https://video.example.com/v1/assets/ast_… \
-H "Authorization: Bearer $CLIPMUX_API_KEY" | jq '{status, error_code}'
```
`processing` turns into `ready`. If it ends `errored`, `error_code` is one of
those above. For `import_failed`, fetch the URL yourself with
`curl -I` from somewhere outside your network: it must answer `200`.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Migrate from Mux](/docs/resources/migrate-from-mux)
- [Videos in the API reference](/docs/reference/api/videos)
---
# Upload from the command line
Push files and whole folders from a terminal, with the server's clipmux binary or with npx @clipmux/node from your app's project.
Source: https://clipmux.com/docs/build/upload/command-line
Two commands upload from a terminal. `npx @clipmux/node upload` runs in your
app's project and uses the credentials `init` wrote, which makes it the
quick way to test an integration. `clipmux push` is the server's own binary:
it walks folders, resumes an interrupted push, and with `--local` encodes on
a PC you own without uploading the file.
Both send the file in 32 MiB parts straight to storage, through the same
upload API a browser uses.
## Before you start [#before-you-start]
- For `npx @clipmux/node upload`: Node 20.19 or later, and an env file
from `npx @clipmux/node init` with `CLIPMUX_URL` and `CLIPMUX_API_KEY`.
- For `clipmux push`: the `clipmux` binary, your server's URL, and an API
key with `uploads:write` (and `assets:read` for `--wait`). For `--local`,
a PC connected as a worker; see
[Encode on a PC you own](/docs/self-host/encoding/your-pc).
## npx @clipmux/node upload [#npx-clipmuxnode-upload]
```bash
npx @clipmux/node upload lesson-42.mp4 --passthrough lesson_42 --wait
```
```txt
0%
10%
…
✓ uploaded lesson-42.mp4: asset ast_… (processing)
Waiting until it is ready…
✓ ready: 1830.4 s, playback ID pid_…
```
| Flag | What it does |
| --- | --- |
| `--passthrough REF` | Your own ID for the video. |
| `--title TITLE` | The video's title. Default: the file's name. |
| `--renditions LIST` | The rungs to encode, comma separated, for example `1080p,480p`. Default: every rung up to the source. |
| `--public` | Make a public playback ID instead of a private (`signed`) one. |
| `--wait` | Wait until the video is ready, and print its duration and playback ID. |
| `--env-file FILE` | Where to read the credentials. Default: `.env.local`, or `.env` if it exists. |
It uploads one file per run.
## clipmux push [#clipmux-push]
The API key comes from `CLIPMUX_API_KEY`, never from a flag, so it doesn't
show in a process listing. The server URL comes from `--server` or
`CLIPMUX_SERVER`.
```bash
export CLIPMUX_API_KEY=cmx_…
clipmux push --server https://video.example.com --passthrough lesson_42 lesson-42.mp4
```
| Flag | Default | What it does |
| --- | --- | --- |
| `--server URL` | `CLIPMUX_SERVER` | Your server's public URL. |
| `--policy POLICY` | `signed` | `signed` for a private video, `public` for a public one. |
| `--passthrough REF` | | Your own ID for the video. One file only. |
| `--renditions LIST` | every rung up to the source | The rungs to encode, comma separated, for example `1080p,480p`. |
| `--wait` | `false` | Wait until each video is ready. Needs an API key. |
| `--quiet` | `false` | Don't print the progress lines. |
| `--local` | `false` | Keep the files on this PC: its worker encodes them and uploads only the outputs. |
| `--upload-source` | `false` | With `--local`: once a video is encoded, also upload its file, so any worker can encode it again. |
### Folders [#folders]
Give it folders as well as files. It walks each folder, skips folders whose
names start with a dot, and picks up files with these extensions: `.mp4`,
`.m4v`, `.mov`, `.mkv`, `.webm`, `.avi`, `.mxf`, `.ts`, `.mts`, `.m2ts`,
`.flv`, `.wmv`, `.mpg`, `.mpeg`, `.ogv` and `.3gp`.
```bash
clipmux push --server https://video.example.com ./course/
```
`--passthrough` names one video, so push files one at a time to set it.
### Resuming [#resuming]
If a push is interrupted, run the same command again: it resumes where it
stopped. Pushing a file that has already finished creates nothing new.
`clipmux push` keeps what it needs for this in your user cache folder, or in
`CLIPMUX_PUSH_STATE_DIR`.
### Output [#output]
Progress goes to standard error, one line per file. Standard output gets one
tab-separated line per video: its asset ID, its playback ID, its status and
the file's path, so you can pipe it into other tools.
```txt
ast_… pid_… processing course/lesson-42.mp4
```
The exit code is `0` when every file went through, `1` if any failed or
ended `errored`, and `2` for a usage mistake.
### --local [#--local]
With `--local`, the file never leaves the PC. The PC's connected worker
encodes it in place and uploads only the encrypted outputs. With an API key
the key's app owns the video; without one, it becomes the server owner's
own upload, as from the dashboard, and `--server` isn't needed.
Such a video can be encoded again only on that PC, because its source is
there. Add `--upload-source` to upload the file once it is encoded, so any
worker can re-encode it later.
## Check it works [#check-it-works]
The last line of `npx @clipmux/node upload --wait` names the playback ID,
and `clipmux push --wait` prints `ready` as the status. Without `--wait`,
your webhook receives `video.asset.ready` when encoding is done.
- `unauthorized`: the API key is wrong or revoked.
- `insufficient_scope`: the key lacks `uploads:write`, or `assets:read` for
`--wait`.
- `too_large`: the file is over the server's upload limit.
- `clipmux push: needs --server and CLIPMUX_API_KEY (or --local), and at least one file`:
set both, or use `--local`.
- `no video files found`: the folder has no file with one of the extensions
above.
## Next [#next]
- [Command line reference](/docs/reference/cli)
- [Link videos to your records](/docs/build/upload/passthrough)
- [Choose renditions](/docs/build/upload/renditions)
---
# Choose renditions
Pick which resolutions ClipMux encodes a video at, from 360p up to 2160p, and what the larger ones cost.
Source: https://clipmux.com/docs/build/upload/renditions
ClipMux encodes each video into a ladder of renditions, so the player can
switch between them as the viewer's connection changes. By default a video
gets every rung up to its own resolution: a 1080p source gets 1080p, 720p,
480p and 360p, and a 4K source adds 1440p and 2160p. You can ask for fewer,
to save encoding time and storage.
## Before you start [#before-you-start]
- An API key with `uploads:write` to choose on an upload, or `assets:write`
to choose on an import or a re-encode.
## The ladder [#the-ladder]
A rung is named by the video's short side, so a vertical video's 1080p is
1080 pixels wide. Video is H.264 in 6-second segments; audio is one shared
rendition.
| Rung | Target bitrate | Peak bitrate |
| --- | --- | --- |
| `2160p` | 14 Mbit/s | 16.8 Mbit/s |
| `1440p` | 8 Mbit/s | 9.6 Mbit/s |
| `1080p` | 5 Mbit/s | 6 Mbit/s |
| `720p` | 3 Mbit/s | 3.5 Mbit/s |
| `480p` | 1.5 Mbit/s | 1.8 Mbit/s |
| `360p` | 800 kbit/s | 1 Mbit/s |
Which rungs a video can get depends on the source:
- **Never above the source.** Only rungs up to the source's short side are
encoded. ClipMux doesn't upscale.
- **At most 4096 pixels on the long side.** A rung whose frame would be
wider than that is skipped, so a 21:9 4K source tops out at 1440p.
- **Small sources.** A source smaller than 360p gets one rendition at its
own size.
## Choose renditions [#choose-renditions]
Send `renditions` on `POST /v1/uploads`, on an import with `POST /v1/assets`,
or on `POST /v1/assets/{id}/reencode`:
```json
{ "size": 734003200, "passthrough": "lesson_42", "renditions": ["1080p", "480p"] }
```
- Use the names above, each once, at least one. Anything else is
`400 invalid_request`.
- Rungs above the source are skipped. If none of the ones you chose fits,
the largest rung that does is encoded instead, so a video always gets a
rendition.
- Leave `renditions` out for every rung up to the source.
The asset shows `renditions` only when there is a choice, largest first.
The same choice is in each client:
- `@clipmux/node`: `renditions` on `uploads.create`, `assets.importUrl` and
`assets.reencode`, or returned from the handler's `upload` callback.
- `npx @clipmux/node upload --renditions 1080p,480p` and
`clipmux push --renditions 1080p,480p`.
- The dashboard's upload dialog, under **Resolutions**: every rung is on by
default, and rungs above the chosen file's resolution show as skipped.
## Change them later [#change-them-later]
Re-encode with a new list. The video keeps playing its current renditions
until the new output is ready, then switches:
```bash
curl -s -X POST https://video.example.com/v1/assets/ast_…/reencode \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"renditions": ["2160p", "1080p", "480p"]}'
```
The new list replaces the video's choice for this output and the ones after
it; leave `renditions` out to keep the current one. See
[A video's lifecycle](/docs/build/concepts/lifecycle) for what a re-encode
does.
## What 4K costs [#what-4k-costs]
Adding 2160p and 1440p to a 4K source is the largest choice you make about
cost:
- **Encoding:** the full ladder for a 4K source is about 4.3 times the
pixels of a 1080p source's ladder, so it takes several times longer on the
same worker. On a CPU-only worker, a 4K ladder is slow.
- **Storage and delivery:** the full ladder's target bitrates add up to
32.3 Mbit/s with 2160p and 1440p, against 10.3 Mbit/s up to 1080p, so a 4K
video stores about 3 times the bytes. Viewers who watch at 2160p also pull
about 14 Mbit/s each.
If your viewers watch on laptops and phones, `["1080p", "720p", "480p",
"360p"]` keeps 4K uploads at the cost of a 1080p one. See
[Encoding performance](/docs/self-host/encoding/performance) for timings.
## Check it works [#check-it-works]
Once the video is ready, get it and read `renditions`, or open its
`master.m3u8` and count the variants:
```bash
curl -s "https://media.example.com/v/$TOKEN/pid_…/master.m3u8" | grep -A1 EXT-X-STREAM-INF
```
Each `EXT-X-STREAM-INF` entry is one rendition. A rung you asked for that is missing was above
the source.
## Next [#next]
- [Encoding performance](/docs/self-host/encoding/performance)
- [Where videos are stored](/docs/self-host/storage)
- [Upload from the browser](/docs/build/upload/browser)
---
# Link videos to your records
Tag each video with your own ID through passthrough, so every webhook and lookup leads straight back to your record.
Source: https://clipmux.com/docs/build/upload/passthrough
`passthrough` is your own ID for a video, such as `lesson_42`. You set it
when you create the upload or import, ClipMux stores it on the video, and it
comes back on the video and in every webhook. Your webhook handler finds the
record a video belongs to without keeping a map of ClipMux IDs, and without
trusting anything else in the body.
## Before you start [#before-you-start]
- A record in your own database for each video, created before you call
ClipMux, with an ID you can send.
## Set it [#set-it]
Make the record first, then send its ID as `passthrough` when you create
the upload (`POST /v1/uploads`) or the import (`POST /v1/assets`).
```ts
// With clipmuxHandler, return it from the upload callback:
async upload(req, { file }) {
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name }
}
// Or with the client:
const upload = await clipmux.uploads.create({ size, passthrough: 'lesson_42' })
```
```python
res = requests.post(
f"{os.environ['CLIPMUX_URL']}/v1/uploads",
headers={"Authorization": f"Bearer {os.environ['CLIPMUX_API_KEY']}"},
json={"size": size, "passthrough": "lesson_42"},
)
```
```go
body := strings.NewReader(fmt.Sprintf(`{"size": %d, "passthrough": "lesson_42"}`, size))
req, _ := http.NewRequest("POST", os.Getenv("CLIPMUX_URL")+"/v1/uploads", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLIPMUX_API_KEY"))
req.Header.Set("Content-Type", "application/json")
```
```php
$ch = curl_init(getenv('CLIPMUX_URL') . '/v1/uploads');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('CLIPMUX_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode(['size' => $size, 'passthrough' => 'lesson_42']),
]);
```
The command lines take it as `--passthrough lesson_42`.
- It is a string of up to 255 bytes; a longer one is `400 invalid_request`.
- It is set once, when the video is made. The API has no route to change
it later.
- It isn't unique: ClipMux doesn't stop two videos sharing one, for example
when a lesson's video is replaced. Your record decides which video is
current.
- It isn't secret, and it isn't checked. Use an ID, not personal data.
## Use it in webhooks [#use-it-in-webhooks]
Every webhook body carries the video, and the video carries `passthrough`:
```json
{ "id": "evt_…", "type": "video.asset.ready", "created_at": "…",
"data": { "id": "ast_…", "status": "ready", "version": 4, "passthrough": "lesson_42", "…": "…" } }
```
In your handler, after verifying the signature:
1. Find the record by `data.passthrough`. If it isn't one of yours (the
dashboard's test event has none), answer `200` and ignore it.
2. Re-fetch the video with `GET /v1/assets/{id}`, since the body says that
something changed, not what it is now.
3. Store its `status`, its playback ID and its `version`, if the `version`
is at least the one you have.
`clipmuxHandler`'s `asset` callback does the verifying and re-fetching, so
you upsert by `asset.passthrough`. See [Receive webhooks](/docs/build/webhooks).
Store the video's ID on your record as soon as the upload is created, from
`asset_id` in the answer: you have it before the file arrives.
## Find videos by it [#find-videos-by-it]
`GET /v1/assets?passthrough=lesson_42` returns your app's videos with that
passthrough, newest first, leaving out deleted ones:
```ts
const videos = await clipmux.assets.findByPassthrough('lesson_42')
const latest = videos[0]
```
```python
res = requests.get(
f"{os.environ['CLIPMUX_URL']}/v1/assets",
params={"passthrough": "lesson_42"},
headers={"Authorization": f"Bearer {os.environ['CLIPMUX_API_KEY']}"},
)
videos = res.json()["data"]
```
```go
u := os.Getenv("CLIPMUX_URL") + "/v1/assets?passthrough=" + url.QueryEscape("lesson_42")
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLIPMUX_API_KEY"))
// the response's "data" is the list, newest first
```
```php
$ch = curl_init(getenv('CLIPMUX_URL') . '/v1/assets?passthrough=' . urlencode('lesson_42'));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('CLIPMUX_API_KEY')],
]);
$videos = json_decode(curl_exec($ch), true)['data'];
```
This needs `assets:read`. Use it to repair a record that missed its
webhooks, or to check before creating a second upload for the same record.
## Check it works [#check-it-works]
Upload a test file with a passthrough, then look it up:
```bash
npx @clipmux/node upload sample.mp4 --passthrough lesson_42
curl -s "https://video.example.com/v1/assets?passthrough=lesson_42" \
-H "Authorization: Bearer $CLIPMUX_API_KEY" | jq '.data[] | {id, status, passthrough}'
```
The new video is first in the list. An empty list means the passthrough was
spelled differently, or the key belongs to another app: each app sees only
its own videos.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Choose an upload method](/docs/build/upload)
- [Webhook events](/docs/reference/webhooks)
---
# Add the player
Play private and public videos in your pages with the clipmux-player element, which renews tokens while it plays.
Source: https://clipmux.com/docs/build/play/player
`` is a web component from `@clipmux/player`: Video.js 10's
skin around hls.js. It plays a video by its playback ID, shows the poster,
subtitles and chapters, and asks your backend for a new token whenever the
old one runs out, without losing the viewer's place. It works in plain HTML
and in any framework.
## Before you start [#before-you-start]
- A video with a playback ID, `pid_…`, from your `asset` callback or
`GET /v1/assets/{id}`.
- For a private video, a route on your backend that decides who may watch.
The [quickstart](/docs/build/quickstart)'s `clipmuxHandler` gives you one
at `/api/clipmux/playback`.
- The package:
```bash
npm i @clipmux/player
```
```bash
pnpm add @clipmux/player
```
## Play with a session URL [#play-with-a-session-url]
The shortest way is `session-url`. The page needs only the playback ID:
```html
```
The element POSTs `{"playback_id": "pid_…", "native": false}` to that URL.
Your backend checks the viewer, from its own session, and answers with a
playback session:
```json
{
"playback_id": "pid_…",
"base_url": "https://media.example.com",
"token": "eyJ…",
"expires_at": "2026-11-18T10:15:00.000Z",
"poster_url": "https://media.example.com/v/eyJ…/pid_…/poster.jpg",
"title": "Lesson 42",
"duration_seconds": 612.4,
"tracks": [{ "id": "trk_…", "kind": "chapters", "source": "generated", "status": "ready" }]
}
```
The `/playback` route of `clipmuxHandler` answers exactly this, from your
`playback` callback. It includes `tracks`, `title` and `duration_seconds`
only when the callback returns the video as well, `{ viewerId, asset }`;
with only the playback ID, the session has no tracks, so the player finds
no chapters. To build it yourself in Node, return
`clipmux.playback.session(asset, { viewerId, native })`. The player:
- plays from `base_url` with `token`;
- shows `poster_url`, unless you set `poster`;
- marks the chapters of the first ready chapters track, unless you set
`chapters-track`;
- POSTs to the same URL again whenever the token expires.
A `401` or `403` from your route fires `clipmux-denied` and stops playback.
Any other failure fires `clipmux-error` with its `status`. The answer in use
is on `player.session`.
## Play with getToken [#play-with-gettoken]
If your page already knows the media origin, or you have your own token
route, set `getToken` instead. The element calls it for the first token and
for every renewal:
```ts
import '@clipmux/player/element'
const player = document.querySelector('clipmux-player')!
player.getToken = async ({ playbackId, native }) => {
const res = await fetch(`/api/playback-token?playback_id=${playbackId}&native=${native}`)
return res.ok ? res.text() : null // null denies
}
```
```html
```
Return the token as a string, or `null` to refuse; `null` fires
`clipmux-denied`. Your route signs the token after its own access check; see
[Sign playback tokens](/docs/build/play/sign-tokens). If you set
`getToken` as well as `session-url`, `getToken` is used for renewals.
A public playback ID needs no token: set `base-url` and `playback-id` and
leave `getToken` unset. See [Public videos](/docs/build/play/public-videos).
## How renewal works [#how-renewal-works]
The token rides in the URL path. When it expires, delivery answers `401
token_expired`. The player asks for a new token once, puts it into that
request and every later one, and retries, so the viewer sees nothing.
Where the browser plays HLS itself, with no Media Source (iOS before 17.1,
AirPlay), the player can't swap the token mid-video. The element tells your
backend: `native: true` in the session request, or in `getToken`'s
argument. Pass it through when you sign, and the token is signed to outlive
the session. If you drop it, Safari before 17.1 stops when the first token
expires. iOS 17.1 and later play through hls.js and renew like any other
browser.
## Attributes and properties [#attributes-and-properties]
Properties, set from script:
Promise","description":"Called for the first token and every renewal. null refuses."},"token":{"type":"string","description":"A token to start with. Without getToken it can't be renewed."},"hls":{"type":"Record","description":"Extra hls.js options. Set it before the first load."},"session":{"type":"PlaybackSession | null","description":"Read only. The session-url answer in use."},"chapters":{"type":"PlayerChapter[]","description":"Read only. The chapters, in seconds, once clipmux-chapters has fired."},"media":{"type":"HTMLVideoElement | null","description":"Read only. The inner element."}}} />
Set `getToken` rather than `token` when you can, so the first token can be
a native one when the browser needs it.
`player.media` is the `` element. Read `currentTime`,
`paused`, `ended`, `duration` and `readyState` from it, and listen for its
media events (`timeupdate`, `ended` and so on), to resume where a viewer
left off or to report progress.
## Events [#events]
They bubble, and they are typed on `HTMLElementEventMap`, so
`player.addEventListener('clipmux-chapters', (e) => e.detail.chapters)`
needs no cast.
| Event | `detail` | When |
| --- | --- | --- |
| `clipmux-token` | `{ token }` | A new token is in use. |
| `clipmux-denied` | `{}` | Your backend said no (`null` from `getToken`, or `401` or `403` from `session-url`), or delivery answered `403`. Playback stops. |
| `clipmux-error` | `{ status, track? }` | Something failed. `status` is the HTTP status, or `0` for a network or media error. `track` is set when a track's file failed to load. |
| `clipmux-chapters` | `{ chapters }` | The chapters track loaded. Times are in seconds. |
`clipmux-denied` means the viewer may not watch: show your own sign-in or
enrol state, not an error. A `clipmux-error` with `status: 404` means the
playback ID was revoked or never existed, so show that the video was
removed.
## React and Next.js [#react-and-nextjs]
The element needs the DOM and Media Source, so a server render must not load
it. Import it in an effect, and import the JSX types once:
```tsx title="app/lessons/[id]/player.tsx"
'use client'
import type { ClipMuxPlayerElement } from '@clipmux/player/element' // types only
import type {} from '@clipmux/player/react' // JSX types only, no React dependency
import { useEffect, useRef } from 'react'
export function Player({ playbackId }: { playbackId: string }) {
const player = useRef(null)
useEffect(() => {
import('@clipmux/player/element')
const el = player.current
const onDenied = () => location.assign('/enrol')
el?.addEventListener('clipmux-denied', onDenied)
return () => el?.removeEventListener('clipmux-denied', onDenied)
}, [])
return
}
```
`@clipmux/player/react` types the attributes, the `token`, `getToken` and
`hls` properties and the `onclipmux-*` handlers, for React 18 and 19. The
listener goes on a ref because React 19 attaches an `onclipmux-denied` prop
only to an element it creates in the browser, not to one it hydrates from
server-rendered HTML, which is what a Next.js page's first load does (React
18 never attaches them).
[`examples/nextjs-lms`](https://github.com/visheshgubrani/clipmux/blob/main/examples/nextjs-lms/app/lessons/%5Bid%5D/lesson-video.tsx)
does the same for both elements. In Next.js, `router.refresh()` from a `clipmux-denied` handler re-renders the
page's locked state.
To set `getToken` from React, wait until the element is defined, then set it
on a ref:
```tsx title="player.tsx"
'use client'
import type {} from '@clipmux/player/react'
import type { ClipMuxPlayerElement } from '@clipmux/player/element'
import { useEffect, useRef, useState } from 'react'
export function Player({ baseUrl, playbackId }: { baseUrl: string; playbackId: string }) {
const ref = useRef(null)
const [defined, setDefined] = useState(false)
useEffect(() => {
import('@clipmux/player/element').then(() => setDefined(true))
}, [])
useEffect(() => {
const el = ref.current
if (!defined || !el) return
el.getToken = async ({ native }) => {
const res = await fetch(`/api/playback-token?playback_id=${playbackId}&native=${native}`)
return res.ok ? res.text() : null
}
}, [defined, playbackId])
return
}
```
Video.js 10.2's own declaration files don't all type-check, so keep
`"skipLibCheck": true` in `tsconfig.json`. Most templates have it already.
## Subtitles and chapters [#subtitles-and-chapters]
Subtitles need no attribute. A ready subtitles track is listed in the HLS
master playlist, so it appears in the player's captions menu, and its files
load with the same token as the video.
Chapters are never in the master playlist. With `session-url`, the player
marks the first ready chapters track by itself. Otherwise, name the track:
```html
```
The player fetches the track's WebVTT with the playback token, marks the
chapters on the time slider, fires `clipmux-chapters` and fills
`player.chapters`. Times there are in seconds; the API's `chapters` on a
track are in milliseconds. See
[Subtitles and transcripts](/docs/build/captions/subtitles) and
[Chapters](/docs/build/captions/chapters).
## Theming [#theming]
Set `--media-accent-color` on the player or an ancestor to colour the
controls:
```css
clipmux-player {
--media-accent-color: #e11d48;
}
```
The player is 16:9 and fills its container's width.
## Content-Security-Policy [#content-security-policy]
A page with the player must allow, besides its own origin:
| Directive | Sources | Why |
| --- | --- | --- |
| `connect-src` | the media origin | playlists, segments, keys and subtitles |
| `media-src` | `blob:` and the media origin | Media Source playback, and native HLS |
| `img-src` | the media origin | the poster |
| `style-src` | `'unsafe-inline'` | Video.js injects its skin's styles |
`npx @clipmux/node doctor` prints the exact origins. hls.js runs on the main
thread, so no `worker-src` is needed.
## Check it works [#check-it-works]
Open the page with the player and watch the browser's network panel:
- `master.m3u8`, then playlists, `key/…` and `.m4s` segments answer `200`.
The video plays.
- Your session route answers `403`, and `clipmux-denied` fires: your
`playback` callback returned `null`.
- Delivery answers `403 denied`: the token was signed with the wrong key or
for another playback ID. Run `npx @clipmux/node doctor`.
- Requests are blocked in the console with a CSP message: add the origins
above.
## Next [#next]
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Other players and native apps](/docs/build/play/other-players)
- [@clipmux/player reference](/docs/reference/sdks/player)
---
# Sign playback tokens
Let your backend decide who watches a private video, with a token it signs itself.
Source: https://clipmux.com/docs/build/play/sign-tokens
A private video plays only with a token: a short JWT that your backend signs
with your app's signing key after it has decided the viewer may watch. Signing
is local. Your backend makes no call to ClipMux per play, and ClipMux checks
the signature when the player asks for the video.
If you use `clipmuxHandler` and `` from the
[quickstart](/docs/build/quickstart), this already happens: your `playback`
callback decides, and the handler signs. Read on to sign tokens yourself, for
your own route, another player or another language.
## Before you start [#before-you-start]
- A video with a **signed** playback ID. Uploads are signed unless you ask
for `playback_policy: "public"`.
- Your app's signing key, as `CLIPMUX_SIGNING_KID` (the key's ID) and
`CLIPMUX_SIGNING_KEY` (a P-256 private key in PEM).
`npx @clipmux/node init` writes both. You can also create one under
**Apps & API** in the dashboard, or with `clipmux admin create-signing-key`
on the server.
- The media origin, `base_url`, from `GET /v1/app`, for example
`https://media.example.com`.
The signing key is a secret. Keep it on your server, never in browser code,
and never in a log.
## What a token holds [#what-a-token-holds]
A token is an ES256 JWT. Its header names the key, and its claims name the
video, what the token may fetch, and for how long.
| Part | Field | Value |
| --- | --- | --- |
| Header | `alg` | `ES256` |
| Header | `kid` | Your `CLIPMUX_SIGNING_KID` |
| Claims | `sub` | The playback ID, `pid_…` |
| Claims | `aud` | `v` to play the video, its tracks and its poster; `t` for the poster only |
| Claims | `iat`, `exp` | Issued and expiry times, in whole Unix seconds |
| Claims | `vid` | Optional. A stable ID for the viewer, which counts unique viewers. ClipMux stores only a keyed hash of it |
`exp - iat` may be at most `max_token_lifetime_seconds` from `GET /v1/app`,
which is 7 days by default. Keep tokens short, 15 minutes for a player that
renews them, and let the player ask again.
## Sign a token [#sign-a-token]
### Check access [#check-access]
Decide in your own code, from your own session, whether this person may watch
this video. ClipMux has no idea who your users are. If the answer is no,
don't sign anything.
### Sign [#sign]
```ts title="playback.ts"
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux() // reads the CLIPMUX_* settings
const token = await clipmux.playback.token('pid_…', {
viewerId: user.id, // optional
expiresIn: '15m', // the default
})
```
`{ audience: 'poster' }` signs a poster-only token.
```python title="playback_token.py"
import time
import jwt # pip install "pyjwt[crypto]"
def playback_token(
playback_id: str,
signing_key_pem: str,
kid: str,
viewer_id: str | None = None,
audience: str = "v",
ttl: int = 900,
) -> str:
"""A token for a signed playback ID, signed with your app's signing key.
signing_key_pem is CLIPMUX_SIGNING_KEY and kid is CLIPMUX_SIGNING_KID.
audience is "v" to play, or "t" for the poster. viewer_id, when given,
counts unique viewers; ClipMux keeps only a keyed hash of it.
"""
now = int(time.time())
claims = {"sub": playback_id, "aud": audience, "iat": now, "exp": now + ttl}
if viewer_id:
claims["vid"] = viewer_id
return jwt.encode(claims, signing_key_pem, algorithm="ES256", headers={"kid": kid})
```
```go title="playback_token.go"
package clipmux
import (
"crypto/ecdsa"
"time"
"github.com/golang-jwt/jwt/v5"
)
// PlaybackToken signs a token for a signed playback ID with your app's
// signing key: CLIPMUX_SIGNING_KEY, read once with
// jwt.ParseECPrivateKeyFromPEM, and CLIPMUX_SIGNING_KID. audience is "v" to
// play, or "t" for the poster. viewerID may be empty; when set it counts
// unique viewers, and ClipMux keeps only a keyed hash of it.
func PlaybackToken(key *ecdsa.PrivateKey, kid, playbackID, viewerID, audience string, ttl time.Duration) (string, error) {
now := time.Now()
claims := jwt.MapClaims{"sub": playbackID, "aud": audience, "iat": now.Unix(), "exp": now.Add(ttl).Unix()}
if viewerID != "" {
claims["vid"] = viewerID
}
t := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
t.Header["kid"] = kid
return t.SignedString(key)
}
```
```php title="playback_token.php"
$playbackId, 'aud' => $audience, 'iat' => $now, 'exp' => $now + $ttl];
if ($viewerId !== null && $viewerId !== '') {
$claims['vid'] = $viewerId;
}
return JWT::encode($claims, $signingKeyPem, 'ES256', $kid);
}
```
Any ES256 JWT library works in other languages: put `kid` in the header and
the claims above in the body.
### Play [#play]
Give the player the token, or build the URL yourself:
```txt
https://media.example.com/v/{token}/{playback_id}/master.m3u8
https://media.example.com/v/{token}/{playback_id}/poster.jpg
```
With ``, set `getToken` so the player asks your backend each
time it needs a fresh token. See [Add the player](/docs/build/play/player).
## Check it works [#check-it-works]
```bash
curl -s -o /dev/null -w '%{http_code}\n' \
"https://media.example.com/v/$TOKEN/pid_…/master.m3u8"
```
- `200`: the token is good.
- `401` with `token_expired`: the token's `exp` has passed. Sign a new one;
the player does this by itself.
- `403` with `denied`: the signature, the key, the playback ID or the
audience is wrong, or the key was revoked. Stop, and check the `kid`
matches the key you signed with.
- `404`: the playback ID was revoked, or doesn't exist.
## Safari and AirPlay [#safari-and-airplay]
iOS before 17.1 and AirPlay play HLS themselves and can't renew a token
mid-video. `` tells your backend when it plays natively:
`native: true` in the session request, or in `getToken`'s argument. Sign
those tokens for longer. The Node SDK does it for you with
`playback.token(id, { native: true, durationSeconds })`: the larger of twice
the video's duration and 4 hours, or 12 hours without a duration, within the
maximum.
## Next [#next]
- [Add the player](/docs/build/play/player)
- [Posters and thumbnails](/docs/build/play/posters-and-thumbnails)
- [Playback IDs and tokens](/docs/build/concepts/playback-ids-and-tokens),
the concepts behind them
---
# Public videos
Give a video a public playback ID so anyone with its URL can watch it, with no token.
Source: https://clipmux.com/docs/build/play/public-videos
A video plays through its playback IDs. A **signed** ID, the default, plays
only with a token your backend signs. A **public** ID plays for anyone who
has its URL: a marketing video, a trailer, a page with no sign-in. The video
is still encrypted on disk and in transit, but a public ID hands out its key
to every request.
A video can have both: a signed ID for your members and a public one for
everyone else. Revoking one ID leaves the others playing.
## Before you start [#before-you-start]
- An API key with `assets:write` (the default scopes include it), or the
`@clipmux/node` client.
- A video, or a file to upload.
## Make a video public [#make-a-video-public]
### At upload [#at-upload]
Ask for a public ID when you create the upload:
```ts
// In clipmuxHandler's upload callback
return { passthrough: 'lesson_42', playback_policy: 'public' }
// Or with the client
const upload = await clipmux.uploads.create({ size, passthrough: 'lesson_42', playback_policy: 'public' })
```
```bash
curl -s https://video.example.com/v1/uploads \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"size": 10485760, "passthrough": "lesson_42", "playback_policy": "public"}'
```
`playback_policy` is also accepted by `POST /v1/assets` when you import a
URL. From the command line:
```bash
npx @clipmux/node upload trailer.mp4 --public
CLIPMUX_API_KEY=cmx_… clipmux push --server https://video.example.com --policy public trailer.mp4
```
### On an existing video [#on-an-existing-video]
Add a public ID to a video that has a signed one, with
`POST /v1/assets/{id}/playback-ids`:
```ts
const pid = await clipmux.playbackIds.create('ast_…', { policy: 'public' })
// { id: 'pid_…', policy: 'public', playable: true, status: 'active' }
```
```bash
curl -s https://video.example.com/v1/assets/ast_…/playback-ids \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"policy": "public"}'
```
`playable` is `false` until the video has finished encoding. A video can
have up to 1000 playback IDs (`409 too_many_playback_ids`).
## Play it [#play-it]
A public ID's URLs start with `/p/` and carry no token:
```txt
https://media.example.com/p/{playback_id}/master.m3u8
https://media.example.com/p/{playback_id}/poster.jpg
https://media.example.com/p/{playback_id}/tracks/{track_id}.vtt
```
The media origin is `base_url` on the video, or from `GET /v1/app`. In your
pages, give `` the media origin and the ID, and no token:
```html
```
Any HLS player plays the `master.m3u8` URL as it is; see
[Other players and native apps](/docs/build/play/other-players). ClipMux has
no embed page or iframe: you put the player in your own page.
## Caching [#caching]
Public bytes may sit in shared caches, such as a CDN in front of your media
origin:
| URL | `Cache-Control` |
| --- | --- |
| `master.m3u8` | `no-store`. It's generated on each request. |
| Segments, rendition playlists and init files | `public, max-age=31536000, immutable`. Their paths change when the video is re-encoded. |
| `poster.jpg` | `public, max-age=300` |
| `tracks/{track_id}.vtt` | `public, max-age=31536000, immutable` |
| `key/…` (the content key) | `no-store` |
Signed IDs send `private` instead of `public`, so their bytes stay out of
shared caches.
## Stop a public video [#stop-a-public-video]
Revoke the public ID, and its URLs stop working. The video's other IDs keep
playing:
```ts
await clipmux.playbackIds.delete('ast_…', 'pid_…')
```
`DELETE /v1/assets/{id}/playback-ids/{pid}` answers `202 revoking` while the
ID is unpublished and `200 revoked` once it is gone. The master playlist is
never cached, so a revoked ID can't start playing again.
## Free previews: a signed ID with an open token [#free-previews-a-signed-id-with-an-open-token]
To let anyone watch for a while, such as a free lesson, you don't need a
public ID. Keep the signed ID, and have your backend sign a token for every
visitor without an access check. You can stop it at any time in your own
code, and a URL someone copies dies with its token. A public ID's URL
works until you revoke the ID.
## Check it works [#check-it-works]
```bash
curl -s -o /dev/null -w '%{http_code}\n' https://media.example.com/p/pid_…/master.m3u8
```
- `200`: the ID is public and the video is ready.
- `403 denied`: the ID is signed. Use a `/v/{token}/…` URL, or add a public
ID.
- `404`: the ID was revoked or doesn't exist, or the video isn't ready yet.
## Next [#next]
- [Posters and thumbnails](/docs/build/play/posters-and-thumbnails)
- [Share links](/docs/build/play/share-links): one private link per
recipient, which you can revoke
- [Playback IDs and tokens](/docs/build/concepts/playback-ids-and-tokens)
---
# Posters and thumbnails
Show a still of each video in your pages, lists and link previews, with a token that can fetch only the poster.
Source: https://clipmux.com/docs/build/play/posters-and-thumbnails
Every encoded video has one poster: a JPEG of a frame near the start. Use it
as the player's poster, as a thumbnail in a list of videos, or as the image
of a link preview. For a private video, the poster can have its own token
that fetches the poster and nothing else, so a poster URL that leaks can't
play the video.
## Before you start [#before-you-start]
- A video that has finished encoding (`status: "ready"`). The poster is made
with the first encode.
- For a private video, your app's signing key; see
[Sign playback tokens](/docs/build/play/sign-tokens).
## What the poster is [#what-the-poster-is]
- One frame, taken 1 second in, or halfway through a video shorter than
2 seconds.
- A JPEG, scaled to at most 720 pixels on its short side, keeping the
video's shape.
- One per video. There are no parameters for its size or its time, and no
animated or storyboard thumbnails. To show a smaller image, scale it in
your page or in your own image service.
A re-encode makes a new poster with the new output.
## Get the poster URL [#get-the-poster-url]
```txt
Private: https://media.example.com/v/{token}/{playback_id}/poster.jpg
Public: https://media.example.com/p/{playback_id}/poster.jpg
```
A private poster takes either a playback token (`aud: v`) or a poster-only
token (`aud: t`). A poster-only token is refused for anything else: the
playlists, segments, keys and subtitles answer `403 denied`.
### From a playback session [#from-a-playback-session]
A playback session already carries a poster URL. `poster_url` from
`clipmux.playback.session()`, and from `clipmuxHandler`'s `/playback` route,
is signed with its own poster-only token that expires with the playback
token. `` shows it unless you set `poster`.
### For a poster alone [#for-a-poster-alone]
On a list page you need the poster without a playback session. Sign a
poster-only token and build the URL:
```ts title="posters.ts"
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux()
const { base_url } = await clipmux.app.get()
const token = await clipmux.playback.token('pid_…', { audience: 'poster', expiresIn: '1h' })
const { poster } = clipmux.playback.urls({ baseUrl: base_url, playbackId: 'pid_…', policy: 'signed' }, token)
// https://media.example.com/v/eyJ…/pid_…/poster.jpg
```
With `playback_token` from [Sign playback tokens](/docs/build/play/sign-tokens):
```python
token = playback_token("pid_…", signing_key_pem, kid, audience="t", ttl=3600)
poster = f"{base_url}/v/{token}/pid_…/poster.jpg"
```
With `PlaybackToken` from [Sign playback tokens](/docs/build/play/sign-tokens):
```go
token, err := PlaybackToken(key, kid, "pid_…", "", "t", time.Hour)
poster := baseURL + "/v/" + token + "/pid_…/poster.jpg"
```
With `clipmux_playback_token` from [Sign playback tokens](/docs/build/play/sign-tokens):
```php
$token = clipmux_playback_token('pid_…', $signingKeyPem, $kid, null, 't', 3600);
$poster = "{$baseUrl}/v/{$token}/pid_…/poster.jpg";
```
Signing is local: a page of fifty thumbnails costs fifty signatures and no
calls to ClipMux. `app.get()` is cached, so the media origin is read once.
## Link previews [#link-previews]
A poster-only token is safe in an `og:image` tag or a chat message: whoever
reads the page source gets a still, not the video.
```html
```
Link preview crawlers may fetch the image long after you render the page,
so sign that token for longer, up to `max_token_lifetime_seconds` from
`GET /v1/app` (7 days by default). A public video's poster URL has no token
and never expires.
## Caching [#caching]
The poster answers with `Cache-Control: max-age=300`, `private` for a signed
ID and `public` for a public one. Each token makes a different URL, so a
new token means a fresh fetch. If you show the same thumbnails on a busy
page, reuse a token for its lifetime rather than signing one per request.
## Check it works [#check-it-works]
```bash
curl -s -o poster.jpg -w '%{http_code} %{content_type}\n' \
"https://media.example.com/v/$POSTER_TOKEN/pid_…/poster.jpg"
```
- `200 image/jpeg`: the poster is in `poster.jpg`.
- `401 token_expired`: sign a new token.
- `403 denied`: the token is for another playback ID, or signed with the
wrong key. A poster-only token used for `master.m3u8` also gets this.
- `404`: the video isn't encoded yet, or the playback ID was revoked.
## Next [#next]
- [Add the player](/docs/build/play/player)
- [Public videos](/docs/build/play/public-videos)
- [Sign playback tokens](/docs/build/play/sign-tokens)
---
# Other players and native apps
Play ClipMux videos in hls.js, Safari, ExoPlayer and any other HLS player, with the token in the URL path.
Source: https://clipmux.com/docs/build/play/other-players
`` is the easy path in a web page, but nothing about ClipMux
needs it. A video is standard HLS: a master playlist, fMP4 (CMAF) segments,
a separate audio rendition and AES-128 encryption with the key served
beside the segments. Any player that plays that plays ClipMux. This page
covers the URL, how the token travels, and how to keep a long session
playing.
## Before you start [#before-you-start]
- A playback ID, and for a private video a token your backend signed; see
[Sign playback tokens](/docs/build/play/sign-tokens).
- The media origin, `base_url`, from the video or from `GET /v1/app`. This
page uses `https://media.example.com`.
## The URL [#the-url]
```txt
Private: https://media.example.com/v/{token}/{playback_id}/master.m3u8
Public: https://media.example.com/p/{playback_id}/master.m3u8
```
The token is part of the path, not a query string or a header. Every
playlist, segment and key URL inside the master is relative, so the token
rides along to each of them without the player knowing. There are no
cookies and no custom headers to set, and delivery allows requests from any
origin (`Access-Control-Allow-Origin: *`), so a web player on your own
domain needs no CORS setup.
What delivery answers, and what a player should do:
| Status | Meaning | Do |
| --- | --- | --- |
| `401 token_expired` | The token's `exp` has passed. | Get a new token and retry. |
| `403 denied` | The token is wrong for this video, or the app was disabled. | Stop. |
| `404` | The playback ID was revoked or doesn't exist, or the video isn't ready. | Stop, and show that the video is gone. |
## Keep long sessions playing [#keep-long-sessions-playing]
A token expires, and a player keeps fetching segments for as long as the
viewer watches. There are two ways to handle it:
1. **Renew the token.** A player that lets you change request URLs can swap
a new token into the path when it sees a `401`. `@clipmux/player`
exports helpers for this, shown for hls.js below.
2. **Sign for the whole session.** A player you can't hook into, including
every native HLS player, gets a token that outlives the session. Sign it
for the larger of twice the video's duration and 4 hours, within
`max_token_lifetime_seconds` from `GET /v1/app` (7 days by default):
```ts
const token = await clipmux.playback.token('pid_…', {
native: true,
durationSeconds: asset.duration_seconds, // 12 hours if you leave it out
})
```
In another language, set `exp` to `iat` plus that many seconds.
A longer token is a longer-lived URL: anyone who copies it can play the
video until it expires. Prefer renewal where the player allows it.
## hls.js [#hlsjs]
ClipMux's own tests play videos with plain hls.js. Load the master URL:
```ts
import Hls from 'hls.js'
const hls = new Hls()
hls.loadSource(`https://media.example.com/v/${token}/${playbackId}/master.m3u8`)
hls.attachMedia(video)
```
To renew tokens, wrap hls.js's loader with `createRefreshLoader` from
`@clipmux/player`. On a `401` it asks your callback for a new token once,
however many requests failed together, puts it into that request and every
later one, and retries. hls.js loads playlists, segments and keys through
the same loader, so this covers them all:
```ts title="player.ts"
import Hls from 'hls.js'
import { createRefreshLoader, type LoaderClass, playbackUrl, TokenSession } from '@clipmux/player'
const baseUrl = 'https://media.example.com'
const session = new TokenSession(firstToken, () => fetchTokenFromYourBackend(playbackId), {
onDenied: () => video.pause(), // your callback returned null, or delivery said 403
})
const Base = Hls.DefaultConfig.loader as unknown as LoaderClass<{ url: string }>
const loader = createRefreshLoader(Base, session, baseUrl, playbackId)
const hls = new Hls({ loader: loader as unknown as typeof Hls.DefaultConfig.loader })
hls.loadSource(playbackUrl({ baseUrl, playbackId, token: session.current }))
hls.attachMedia(video)
```
Your callback returns a new token, or `null` to stop. A callback that throws
is retried after 1, 2 and 4 seconds. For a player with another loader or
request hook, `rewriteTokenUrl(url, mediaOrigin, playbackId, token)` puts a
token into a ClipMux URL and leaves any other URL alone.
## Safari and iOS [#safari-and-ios]
Safari plays HLS itself. ClipMux's tests play a private video in Safari with
a plain `` element, including its separate audio track:
```html
```
Safari's own player can't renew a token mid-video, so sign for the whole
session. On iOS 17.1 and later, hls.js runs on Managed Media Source, so
hls.js with the refresh loader, or ``, can renew instead.
## Android with ExoPlayer [#android-with-exoplayer]
ClipMux's tests play a private video with Media3 ExoPlayer 1.5.1, including
its encryption and separate audio rendition. Add the HLS module:
```kotlin title="build.gradle.kts"
implementation("androidx.media3:media3-exoplayer:1.5.1")
implementation("androidx.media3:media3-exoplayer-hls:1.5.1")
```
and play the master URL:
```kotlin
val player = ExoPlayer.Builder(context).build()
player.setMediaItem(MediaItem.fromUri("https://media.example.com/v/$token/$playbackId/master.m3u8"))
player.prepare()
player.play()
```
Fetch the token from your own backend, which checks the viewer first, and
sign it for the whole session.
## Other players [#other-players]
Video.js, Shaka Player, AVPlayer on iOS and tvOS, and players on smart TVs
aren't covered by ClipMux's tests. They should play the same URL, since it
is standard HLS with AES-128, but check them yourself. Unless you can hook
the player's requests, sign tokens for the whole session.
AirPlay and Chromecast hand the URL to the receiving device, which fetches
the video itself, so nothing on the sending side can renew the token. Sign
those tokens for the whole session too. `` reports native
playback to your backend with `native: true`, but it can't tell whether the
viewer will cast, so a long session that starts in the browser and moves to
a TV may stop when its token expires.
## Subtitles and chapters [#subtitles-and-chapters]
Ready subtitles are listed in the master playlist as an HLS subtitles
rendition, so players that show HLS subtitles find them with no extra
work. A player that wants a WebVTT file instead can fetch the sidecar URL:
```txt
https://media.example.com/v/{token}/{playback_id}/tracks/{track_id}.vtt
```
Chapters are never in the master playlist. Fetch the chapters track's VTT
from the same URL form, and `parseChapters` from `@clipmux/player` reads it
into `{ startTime, endTime, title }` in seconds. See
[Chapters](/docs/build/captions/chapters).
## Check it works [#check-it-works]
```bash
curl -s "https://media.example.com/v/$TOKEN/pid_…/master.m3u8" | head
```
A `200` with `#EXTM3U` and `#EXT-X-STREAM-INF` lines means the URL is right.
If the player still fails, open its network log: a `401` partway through a
session means the token expired and nothing renewed it.
## Next [#next]
- [Add the player](/docs/build/play/player)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Delivery API reference](/docs/reference/api/delivery)
---
# Share links
Send someone a link that plays one private video on a page ClipMux hosts, and revoke it when you're done.
Source: https://clipmux.com/docs/build/play/share-links
A share link is a URL like `https://video.example.com/s/…` that plays one
video for anyone who has it, with no sign-in and no app of yours in the
way. Use it to send a draft to a client, or a lesson to someone outside
your platform. Each link can expire, you can revoke it at any time, and you
can see how many views it had.
Each link owns its own signed playback ID, made with it. Revoking the link
revokes that ID and nothing else: your app's playback ID and other links
keep playing.
## Before you start [#before-you-start]
- A video. It can still be processing; the page waits for it.
- An API key with `assets:write` to create and revoke links, and
`assets:read` to list them. The default scopes have both.
## Create a link [#create-a-link]
```ts
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux()
const share = await clipmux.shares.create('ast_…', {
name: 'For the client', // optional, one line, up to 100 characters
expires_at: '2026-12-31T23:59:59Z', // optional; leave it out for a link that never expires
})
console.log(share.url) // https://video.example.com/s/…
```
```bash
curl -s https://video.example.com/v1/assets/ast_…/shares \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"name": "For the client", "expires_at": "2026-12-31T23:59:59Z"}'
```
`POST /v1/assets/{id}/shares` answers `201`:
```json
{
"id": "shr_…",
"asset_id": "ast_…",
"name": "For the client",
"url": "https://video.example.com/s/…",
"playback_id": "pid_…",
"status": "active",
"expires_at": "2026-12-31T23:59:59Z",
"created_at": "2026-11-18T09:00:00Z"
}
```
`url` is what you send. `expires_at` must be in the future, and it can't be
changed later: to extend a link, make a new one. The link's playback ID
shows in the video's `playback_ids` with `share: {id, name}`.
You can also make links in the dashboard: open the video under **Videos**,
then **Share links** and **New share link**.
## What the recipient sees [#what-the-recipient-sees]
The link opens a page on your ClipMux server. It shows the video's title,
`` with the video's subtitles and chapters, and a small
"Shared with ClipMux" credit, and nothing else.
- While the video is processing, the page says so and checks again every
15 seconds.
- Once the link expires or is revoked, or the video is deleted, the page
says the link doesn't work and asks them to get a new one from whoever
shared it. A viewer who is watching when that happens is stopped.
- The page renews its own tokens, so a long video plays to the end.
- The page can't be put in an iframe, asks search engines not to index it,
and sends no referrer.
The page keeps a random viewer ID in the browser's storage, so your
analytics count unique viewers. A private window sends none.
## List links and their views [#list-links-and-their-views]
```ts
const links = await clipmux.shares.list('ast_…')
// [{ id, name, url, status, expires_at, views_30d, … }], newest first
```
`GET /v1/assets/{id}/shares` lists every link of the video, with
`views_30d`, its views over the last 30 UTC days. A link's views also count
in the video's [analytics](/docs/build/analytics), though ClipMux signs its
tokens.
`status` is one of:
| Status | Meaning |
| --- | --- |
| `active` | The link plays. |
| `revoked` | You revoked it, or the video was deleted. |
| `expired` | Its `expires_at` has passed. |
## Revoke a link [#revoke-a-link]
```ts
await clipmux.shares.delete('shr_…')
```
`DELETE /v1/shares/{id}` revokes the link's playback ID. It answers `200`
once the ID is unpublished and `202` while it is being revoked. Revoking a
link twice changes nothing.
An expired link stops at its expiry by itself; within a minute ClipMux also
revokes its playback ID.
## Play a link in another player [#play-a-link-in-another-player]
The share page is for people with a browser. For a player that can't open
a page, such as a TV app or a media player, get a signed `master.m3u8` URL
for the link:
```ts
const { url, expires_at } = await clipmux.shares.streamUrl('shr_…')
```
`POST /v1/shares/{id}/stream-url` answers `{url, expires_at}`. The URL
can't renew itself: it lasts until the link's expiry or the server's
longest token lifetime, whichever comes first, and stops when the link is
revoked. It answers `409 share_expired`, `409 share_revoked`, or `409
asset_not_ready` while the video is processing.
## Check it works [#check-it-works]
Open `share.url` in a private window. The video plays with no sign-in.
```bash
curl -s -o /dev/null -w '%{http_code}\n' -X POST \
-H 'Content-Type: application/json' -d '{}' \
"https://video.example.com/s/$SECRET/playback"
```
`$SECRET` is the last part of the link's URL. This is what the page asks
for each token:
- `200`: the link plays.
- `409 asset_not_ready`: the video is still processing.
- `404 share_not_found`: the link was revoked, its video deleted or its app
disabled.
- `410 share_expired`: the link has expired.
## Next [#next]
- [Public videos](/docs/build/play/public-videos), for a video anyone can
find and play
- [Views, watch time and unique viewers](/docs/build/analytics)
- [Share links API reference](/docs/reference/api/share-links)
---
# Subtitles and transcripts
Have ClipMux transcribe a video's speech into subtitles the player shows, and read the transcript as text with timings.
Source: https://clipmux.com/docs/build/captions/subtitles
ClipMux can transcribe a video's speech into a subtitles track. The player
shows it in its captions menu with no extra code, any HLS player finds it in
the playlist, and your backend can read the same transcript as text, with
segment and word timings, for search, notes or an AI feature of your own.
Transcription runs where the server's owner set it up: on the server's own
workers with [whisper.cpp](/docs/self-host/captions-and-ai/whisper), or with
a [speech API](/docs/self-host/captions-and-ai/speech-apis) they connected.
Your app asks for subtitles the same way in both cases.
If the owner connected a speech API, the video's audio is sent to that
provider to be transcribed. With whisper.cpp, nothing leaves the
owner's machines.
## Before you start [#before-you-start]
- An API key with `assets:write` to ask for subtitles, and `assets:read` to
read tracks and transcripts. The default scopes have both.
- A video with speech in it. ClipMux detects the language.
## Ask for subtitles [#ask-for-subtitles]
### At upload [#at-upload]
Add `generate` when you create the upload:
```ts title="app/api/clipmux/[action]/route.ts"
async upload(req, { file }) {
return { passthrough: 'lesson_42', title: file.name, generate: { subtitles: true } }
},
```
`generate` works the same on `POST /v1/uploads`, on an import with
`POST /v1/assets`, and with the client's `uploads.create`.
`generate: { chapters: true }` asks for subtitles too, since chapters are
made from them.
Subtitles are made after the video is ready, and never hold it up:
`video.asset.ready` comes first, then the track's own event.
### For a video you already have [#for-a-video-you-already-have]
```ts
const { track, job } = await clipmux.tracks.create('ast_…', { kind: 'subtitles' })
// track: { id: 'trk_…', kind: 'subtitles', source: 'generated', status: 'preparing' }
```
`POST /v1/assets/{id}/tracks` with `{"kind": "subtitles"}` answers `202`.
If the video already has subtitles, a new track is made and the old one
keeps playing until the new one is ready. It refuses with `409` and:
| Code | Meaning |
| --- | --- |
| `asset_not_ready` | The video is still processing. Wait for `video.asset.ready`. |
| `no_audio` | The video has no audio track. |
| `job_active` | Another job is changing this video. Wait, or send `"supersede": true` to cancel a transcription that's running. |
| `asset_deleted` | The video is deleted. |
## Know when it's ready [#know-when-its-ready]
A track's `status` is `preparing`, `ready` or `errored`. It's on the video,
in `tracks`, and ClipMux sends a webhook when it changes:
| Event | When |
| --- | --- |
| `video.asset.track.ready` | The track is ready to play and read. |
| `video.asset.track.errored` | Transcription failed. `track.error_code` says why. |
| `video.asset.track.deleted` | The track was deleted. |
Track events carry `track: {id, kind, error_code?}` beside the video. With
`clipmuxHandler`, your `asset` callback gets the video with its current
`tracks`, and the event as its second argument:
```ts
async asset(asset, event) {
const subtitles = asset.tracks?.find((t) => t.kind === 'subtitles' && t.status === 'ready')
await db.lesson.update({ where: { ref: asset.passthrough }, data: { subtitlesTrackId: subtitles?.id } })
},
```
See [Receive webhooks](/docs/build/webhooks).
## Show them [#show-them]
`` needs nothing more: a ready subtitles track is listed in
the video's HLS playlist, so it appears in the player's captions menu,
labelled with its language. Other HLS players find it in the same place.
For a player that wants a WebVTT file, the track is also at:
```txt
https://media.example.com/v/{token}/{playback_id}/tracks/{track_id}.vtt
```
or under `/p/{playback_id}/…` for a public playback ID.
## Read the transcript [#read-the-transcript]
```ts
const t = await clipmux.tracks.transcript('ast_…', 'trk_…')
```
`GET /v1/assets/{id}/tracks/{track_id}/transcript` returns, the moment the
track reads `ready`:
```json
{
"track_id": "trk_…",
"language": "en",
"duration_ms": 612400,
"text": "Welcome to the course. Today we…",
"segments": [{ "id": "s0", "start_ms": 0, "end_ms": 4200, "text": "Welcome to the course." }]
}
```
Times are in milliseconds. `language` is the detected language code, for
example `en` or `hi`. Add `words: true` (`?words=true`) for each segment's
word timings. Before the track is ready, the route answers
`409 track_not_ready`.
If you store the text in Postgres, strip any `\u0000` characters first:
Postgres `text` columns refuse them.
## Remove subtitles [#remove-subtitles]
```ts
await clipmux.tracks.delete('ast_…', 'trk_…')
```
`DELETE /v1/assets/{id}/tracks/{track_id}` removes the track. Its file and
transcript go at once; it answers `202` while the track is taken out of the
playlist and `200` once nothing lists it.
## When transcription fails [#when-transcription-fails]
An `errored` track's `error_code` is one of:
| Code | Meaning |
| --- | --- |
| `no_audio` | The video has no audio. |
| `transcribe_failed` | Speech recognition failed. |
| `transcribe_unavailable` | No worker or speech API can transcribe right now. |
| `transcript_invalid` | The transcript that came back was not valid. |
| `speech_api_rejected` | The speech API refused the request. The server's owner should check its key and model. |
| `speech_api_unavailable` | The speech API kept failing. |
To try again, ask for subtitles with `POST /v1/assets/{id}/tracks`.
## What it doesn't do [#what-it-doesnt-do]
- One language per video, detected from the speech. There is no language
hint, and no translation.
- No uploading your own caption files.
- No editing a transcript.
## Check it works [#check-it-works]
Upload a short clip with speech and `generate: { subtitles: true }`, or run
`tracks.create` on a ready video. Your webhook receives
`video.asset.track.ready` once it's transcribed. Then:
```bash
curl -s https://video.example.com/v1/assets/ast_…/tracks/trk_…/transcript \
-H "Authorization: Bearer $CLIPMUX_API_KEY" | head -c 300
```
prints the transcript, and the player's captions button lists the language.
## Next [#next]
- [Chapters](/docs/build/captions/chapters), made from the transcript
- [Add the player](/docs/build/play/player)
- [Subtitles and chapters API reference](/docs/reference/api/subtitles-and-chapters)
---
# Chapters
Split a video into named chapters, written by an LLM from its transcript, and mark them on the player's time slider.
Source: https://clipmux.com/docs/build/captions/chapters
Chapters split a video into named parts, such as "Setting up" and
"Deploying", that the player marks on its time slider. ClipMux writes them
from the video's transcript with an LLM that the server's owner connected.
The model only picks where each chapter starts and names it; ClipMux works
out every time from the transcript itself.
Each time chapters are made, the video's transcript text is sent to the
LLM provider the server's owner connected, such as OpenAI or Anthropic.
No audio or video is sent. With a model on the owner's own network, such
as Ollama, nothing leaves their machines.
## Before you start [#before-you-start]
- An LLM connected on the ClipMux server, under **Captions & AI** in the
dashboard. See [Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm).
- An API key with `assets:write`, which the default scopes include.
- A video with speech. Chapters are made from its subtitles, so a video
with no audio can't have them.
## Ask for chapters [#ask-for-chapters]
### At upload [#at-upload]
```ts title="app/api/clipmux/[action]/route.ts"
async upload(req, { file }) {
return { passthrough: 'lesson_42', title: file.name, generate: { chapters: true } }
},
```
`generate: { chapters: true }` asks for subtitles too. Once the video is
ready, ClipMux transcribes it, then makes chapters from the transcript. If
no LLM is connected by then, the chapters track ends `errored` with
`llm_not_connected`; the video and its subtitles are unaffected.
### For a video you already have [#for-a-video-you-already-have]
```ts
const { track } = await clipmux.tracks.create('ast_…', { kind: 'chapters' })
```
`POST /v1/assets/{id}/tracks` with `{"kind": "chapters"}` answers `202`. A
video that has chapters keeps them until the new ones are ready. It
refuses with `409` and:
| Code | Meaning |
| --- | --- |
| `subtitles_not_ready` | Chapters need ready subtitles. Ask for subtitles first, or wait for them. |
| `chapters_not_connected` | No LLM is connected for chapters on the server. |
| `asset_not_ready` | The video is still processing. |
| `job_active` | Another job is changing this video. Wait, or send `"supersede": true` to cancel a chapters job that's running. |
## What you get [#what-you-get]
A chapters track has `kind: "chapters"` and the same statuses and webhooks
as subtitles: `preparing`, then `ready` with `video.asset.track.ready`, or
`errored` with `video.asset.track.errored`.
- Between 1 and 10 chapters, as few as the content needs.
- Titles of up to 100 characters, on one line, in the transcript's
language.
- The first chapter starts at 0, each one ends where the next starts, and
the last ends at the end of the video.
Read them as JSON, in milliseconds, from the track:
```ts
const track = await clipmux.tracks.get('ast_…', 'trk_…')
// track.chapters: [{ start_ms: 0, end_ms: 95400, title: 'Setting up' }, …]
```
`GET /v1/assets/{id}/tracks/{track_id}` includes `chapters` once the track is
ready.
The same chapters are a WebVTT file, one numbered cue per chapter with its title
as the cue text, at the track's sidecar URL:
```txt
https://media.example.com/v/{token}/{playback_id}/tracks/{track_id}.vtt
```
```txt title="trk_….vtt"
WEBVTT
X-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000
1
00:00:00.000 --> 00:01:35.400
Setting up
2
00:01:35.400 --> 00:04:12.000
Deploying
```
## Show them in the player [#show-them-in-the-player]
With `session-url`, `` finds the first ready chapters track
in the session and marks it on the time slider by itself. Otherwise, name
the track:
```html
```
Chapters are never listed in the HLS playlist, so the player fetches the
VTT itself, with the playback token. When it has them, it fires
`clipmux-chapters` and sets `player.chapters`, in seconds:
```ts
player.addEventListener('clipmux-chapters', (e) => {
for (const c of e.detail.chapters) console.log(c.startTime, c.endTime, c.title)
})
```
To list chapters in your own page or another player, fetch the VTT and read
it with `parseChapters` from `@clipmux/player`:
```ts
import { parseChapters } from '@clipmux/player'
const chapters = parseChapters(await (await fetch(vttUrl)).text())
// [{ startTime: 0, endTime: 95.4, title: 'Setting up' }, …]
```
## When chapters fail [#when-chapters-fail]
An `errored` chapters track's `error_code` is one of:
| Code | Meaning |
| --- | --- |
| `llm_not_connected` | No LLM is connected for chapters. Show nothing rather than an error; once the owner connects one, ask again with `POST /v1/assets/{id}/tracks`. |
| `subtitles_failed` | The subtitles chapters are made from failed. |
| `llm_unavailable` | The model kept failing, through three tries. |
| `model_rejected` | The provider refused the request. The owner should check the key and model. |
| `model_refused` | The model declined to write chapters for this transcript. |
| `invalid_model_output` | The model's chapters were still invalid after one corrective re-prompt. |
| `transcript_too_large` | The transcript makes a prompt over 512 KB. It is never cut short. |
Videos made before an LLM was connected don't get chapters by themselves:
ask for them again.
## Check it works [#check-it-works]
```bash
curl -s https://video.example.com/v1/assets/ast_…/tracks/trk_… \
-H "Authorization: Bearer $CLIPMUX_API_KEY"
```
A `ready` track with a `chapters` list means it worked, and the player's
time slider shows the chapter marks. An `errored` track names its reason in
`error_code`, above.
## Next [#next]
- [Subtitles and transcripts](/docs/build/captions/subtitles)
- [Add the player](/docs/build/play/player)
- [Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm)
---
# Receive webhooks
Keep your own records in step with each video's state, from signed webhook events and a catch-up job for any you miss.
Source: https://clipmux.com/docs/build/webhooks
ClipMux tells your backend when something happens to a video: it's ready,
it failed, its subtitles are done, it was deleted. Each event is an HTTP
POST to a URL of yours, signed with your webhook secret. Your handler finds
the record the video belongs to, by your own `passthrough`, and stores what
changed.
## Before you start [#before-you-start]
- A webhook endpoint registered for your app, and its secret as
`CLIPMUX_WEBHOOK_SECRET`. `npx @clipmux/node init` makes both when the
owner gives a webhook URL on the approval page. Otherwise add one under
**Apps & API**, your app, **Webhooks** in the dashboard, or with
`clipmux admin create-webhook --app NAME --url URL` on the server.
- Uploads made with a `passthrough`, your own ID for the record; see
[Link videos to your records](/docs/build/upload/passthrough).
- While you develop on a laptop the server can't reach, forward events with
[listen](/docs/build/webhooks/listen).
## The events [#the-events]
| Event | When |
| --- | --- |
| `video.asset.ready` | The video is encoded and plays. |
| `video.asset.updated` | Its title changed. |
| `video.asset.errored` | It failed; `error_code` on the video says why. |
| `video.asset.reencode_failed` | A re-encode failed. The video still plays its previous encode. |
| `video.asset.deleted` | It was deleted. |
| `video.asset.track.ready` | A subtitles or chapters track is ready. |
| `video.asset.track.errored` | A track failed; `track.error_code` says why. |
| `video.asset.track.deleted` | A track was deleted. |
Each body has the event's `id` (`evt_…`), `type`, `created_at` and `data`,
the video as `GET /v1/assets/{id}` returned it when the event was made.
Track events add `track: {id, kind, error_code?}`, and re-encode events add
`job`. Every field is in [Webhook events](/docs/reference/webhooks).
## Handle them with clipmuxHandler [#handle-them-with-clipmuxhandler]
`clipmuxHandler` from `@clipmux/node/handlers` verifies each request, then
re-fetches the video, so your code sees its current state rather than the
state when the event was made:
```ts title="app/api/clipmux/[action]/route.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
export const POST = clipmuxHandler({
// Every verified event, before asset(). Optional.
async event(event) {
console.log(event.type, event.id)
},
// The video, re-fetched so it's current, and the event that triggered it.
async asset(asset, event) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
// Errors the handler turned into a 4xx or 5xx. Default: console.error for 5xx.
onError(err, req) {
logger.warn({ err }, 'clipmux handler')
},
})
```
The webhook route is `/api/clipmux/webhook` on your app. ClipMux POSTs to
the URL you registered, so register that one. What the handler does with each
request:
1. Verifies the signature and timestamp. A request that fails gets `400`
with the reason (`missing_header`, `stale`, `bad_signature` or
`invalid_body`), and your callbacks aren't called.
2. Calls `event(event)`, if you passed it.
3. Calls `asset(asset, event)` with the video from `GET /v1/assets/{id}`.
If the video is gone (`404`), it passes the event's copy instead. Within
one process, it skips a video whose `version` is older than one it has
already passed you.
4. Answers `200 {"received": true}`.
If `event` or `asset` throws, the handler answers with a `5xx` and ClipMux retries
the delivery, for up to 24 hours. Throw when your own database fails;
return normally for anything you mean to ignore.
`event` narrows on `type`, so a track event has its `track`:
```ts
async event(event) {
if (event.type === 'video.asset.track.ready') console.log(event.track.kind) // 'subtitles' | 'chapters'
},
```
## Write the handler to be safe [#write-the-handler-to-be-safe]
Delivery is **at least once** and **unordered**. The same event can arrive
twice, and `video.asset.ready` can arrive after a later
`video.asset.updated`. Write your handler so that doesn't matter:
- **Upsert by `passthrough`.** Find your record by `asset.passthrough` and
set its fields, rather than appending or counting.
- **Keep the highest `version`.** Every change to a video raises its
`version`. Store the one you applied and skip any video with a lower one.
The handler does this within one process, but not across restarts or
several instances of your app.
- **Dedupe on the event ID** if an event triggers something that mustn't
run twice, such as an email. `event.id` is the same as the `X-Webhook-Id`
header, and stays the same on every retry.
- **Ignore what isn't yours.** Answer `200` for an event whose
`passthrough` you don't know, so ClipMux doesn't retry it.
A video's status on your record:
| Video `status` | Your record |
| --- | --- |
| `waiting_upload` | Uploading |
| `processing` | Processing |
| `ready`, with an active playback ID | Ready |
| `errored` or `deleted` | Failed or removed |
Tracks are made after the video is ready, so expect `video.asset.ready`
first, then `video.asset.track.ready` or `video.asset.track.errored`.
## Catch up on missed events [#catch-up-on-missed-events]
If your endpoint is down for longer than the 24 hours of retries, its
events are dropped. Run a catch-up job, for example every few minutes or at
start, that walks every video changed since the last run:
```ts
let since = await db.state.get('clipmux_since') // a Date or ISO string you stored
const startedAt = new Date()
for await (const asset of clipmux.assets.changes({ since })) {
await applyAsset(asset) // the same upsert as your asset callback
}
await db.state.set('clipmux_since', startedAt)
```
`assets.changes` pages through `GET /v1/assets?updated_since=…`, oldest
first, deleted videos included. Because your upsert keeps the highest
`version`, running it alongside webhooks is safe.
## Verify by hand [#verify-by-hand]
Without `clipmuxHandler`, verify each request yourself with the raw body:
```ts
import { ClipMux, WebhookVerificationError } from '@clipmux/node'
const clipmux = new ClipMux()
export async function POST(req: Request) {
const raw = await req.text() // the exact bytes; never parse and re-serialize
let event
try {
event = await clipmux.webhooks.verify(raw, req.headers)
} catch (err) {
if (err instanceof WebhookVerificationError) return new Response(null, { status: 400 })
throw err
}
const asset = await clipmux.assets.get(event.data.id) // the body says something changed; re-fetch what
await applyAsset(asset)
return new Response(null, { status: 200 })
}
```
Any `2xx` counts as delivered. Redirects aren't followed. For the scheme
and Python, Go and PHP, see
[Verify webhook signatures](/docs/build/webhooks/verify-signatures).
## Check it works [#check-it-works]
With your app running, upload a short file and watch the events arrive:
```bash
npx @clipmux/node upload sample.mp4 --passthrough lesson_42 --wait
```
Your `asset` callback runs for `video.asset.ready` and your record shows the
video as ready. If nothing arrives, open **Deliveries** on the endpoint in
the dashboard: each try shows its HTTP status or error.
- `400` with `bad_signature`: the secret is wrong, or a middleware parsed
the body before the handler read it.
- `400` with `stale`: your server's clock is more than 5 minutes off.
- `404`: the URL isn't the handler's `/webhook` route, or you passed
neither `asset` nor `event`.
- `connection_failed` or `timeout`: ClipMux can't reach the URL, or your
handler took longer than 10 seconds.
## Next [#next]
- [Verify webhook signatures](/docs/build/webhooks/verify-signatures)
- [Develop locally with listen](/docs/build/webhooks/listen)
- [Retries, redelivery and secret rotation](/docs/build/webhooks/retries)
---
# Verify webhook signatures
Check that a webhook came from your ClipMux server and wasn't changed or replayed, in Node, Python, Go or PHP.
Source: https://clipmux.com/docs/build/webhooks/verify-signatures
Anyone can POST to your webhook URL. Before you trust an event, check its
signature: an HMAC of the timestamp and the body, keyed with your webhook
secret. `clipmuxHandler` and `clipmux.webhooks.verify` do this for you. This
page explains the scheme, and gives tested code for backends in Python, Go
and PHP.
## Before you start [#before-you-start]
- Your endpoint's secret, `whsec_…`, as `CLIPMUX_WEBHOOK_SECRET`. It's
shown once, when the endpoint is made.
- Your framework's raw request body: the bytes exactly as they arrived.
## The scheme [#the-scheme]
Every delivery carries these headers:
```http
POST /api/clipmux/webhook
Content-Type: application/json
X-Webhook-Event: video.asset.ready
X-Webhook-Id: evt_…
X-Webhook-Timestamp: 1800000000
X-Webhook-Signature: sha256=2efc953e06016fe9b4da70ab219f4420b381a8d5ad1a9f253f9e31da718a15d1
```
To verify one:
1. Read `X-Webhook-Timestamp` and `X-Webhook-Signature`. If either is
missing, refuse it.
2. Check the timestamp is whole Unix seconds within 300 seconds of your
clock, either way. This stops an old delivery being replayed.
3. Compute HMAC-SHA256 over `{timestamp}.{raw body}`: the timestamp as it
appears in the header, a full stop, then the body's bytes. Key it with
the whole secret, `whsec_` prefix included, as bytes.
4. Compare `sha256=` followed by the lowercase hex of that HMAC with the
header, in constant time.
If any step fails, answer `400` and ignore the body. If they pass, parse
the body as JSON.
The timestamp is fresh on every try, so a retried delivery has a new
timestamp and signature but the same `X-Webhook-Id`.
## The raw body [#the-raw-body]
The signature covers the body byte for byte. Parse it and serialize it
again, and spacing or key order changes, so the signature no longer
matches. Read the raw body before anything parses it:
- **Next.js, Hono, Bun, Deno, Workers:** `await req.text()` or
`await req.arrayBuffer()` on the `Request`.
- **Express:** mount the webhook route before `express.json()`, or give it
`express.raw({ type: '*/*' })`. A route after `express.json()` gets an
object, and the signature can't match.
- **PHP:** `file_get_contents('php://input')`.
## Verify [#verify]
```ts title="webhook.ts"
import { ClipMux, WebhookVerificationError } from '@clipmux/node'
const clipmux = new ClipMux() // reads CLIPMUX_WEBHOOK_SECRET
export async function POST(req: Request) {
try {
const event = await clipmux.webhooks.verify(await req.text(), req.headers)
// event.type, event.data.id, …
} catch (err) {
if (err instanceof WebhookVerificationError) return new Response(err.reason, { status: 400 })
throw err
}
return new Response(null, { status: 200 })
}
```
`verify` takes the body as a string, `Uint8Array` or `ArrayBuffer`, and the
headers as a `Headers` object or a Node headers record. It throws a
`WebhookVerificationError` whose `reason` is `missing_header`, `stale`,
`bad_signature` or `invalid_body`. `verifyWebhook(secret, rawBody, headers)`
is the same without a client.
```python title="verify_webhook.py"
import hashlib
import hmac
import json
import re
import time
class WebhookError(Exception):
"""Answer 400. reason is "missing_header", "stale" or "bad_signature"."""
def __init__(self, reason: str):
super().__init__(reason)
self.reason = reason
def verify_webhook(secret: str, raw_body: bytes, headers, tolerance: int = 300, now: int | None = None) -> dict:
"""Check a ClipMux webhook and return its event.
secret is CLIPMUX_WEBHOOK_SECRET, whsec_ prefix included. raw_body is the
request body exactly as it arrived: parsed and serialized again, it no
longer matches. headers is your framework's (case-insensitive) headers.
"""
timestamp = headers.get("X-Webhook-Timestamp")
signature = headers.get("X-Webhook-Signature")
if not timestamp or not signature:
raise WebhookError("missing_header")
now = int(time.time()) if now is None else now
if not re.fullmatch(r"[0-9]+", timestamp) or abs(now - int(timestamp)) > tolerance:
raise WebhookError("stale")
mac = hmac.new(secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256)
if not hmac.compare_digest(signature.encode(), f"sha256={mac.hexdigest()}".encode()):
raise WebhookError("bad_signature")
return json.loads(raw_body)
```
Pass the raw body as bytes, such as `request.get_data()` in Flask or
`await request.body()` in FastAPI, and the request's headers.
```go title="verify_webhook.go"
package clipmux
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"net/http"
"strconv"
"time"
)
// Answer 400 for any of these.
var (
ErrMissingHeader = errors.New("missing_header")
ErrStale = errors.New("stale")
ErrBadSignature = errors.New("bad_signature")
)
// VerifyWebhook checks a ClipMux webhook. secret is CLIPMUX_WEBHOOK_SECRET,
// whsec_ prefix included, and body is the request body exactly as it
// arrived. Unmarshal the body into the event only after it passes.
func VerifyWebhook(secret string, body []byte, h http.Header, now time.Time) error {
ts, sig := h.Get("X-Webhook-Timestamp"), h.Get("X-Webhook-Signature")
if ts == "" || sig == "" {
return ErrMissingHeader
}
for _, r := range ts {
if r < '0' || r > '9' {
return ErrStale
}
}
sent, err := strconv.ParseInt(ts, 10, 64)
if err != nil || now.Unix()-sent > 300 || sent-now.Unix() > 300 {
return ErrStale
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(ts + "."))
mac.Write(body)
if !hmac.Equal([]byte(sig), []byte("sha256="+hex.EncodeToString(mac.Sum(nil)))) {
return ErrBadSignature
}
return nil
}
```
Read the body with `io.ReadAll(r.Body)`, call
`VerifyWebhook(secret, body, r.Header, time.Now())`, and unmarshal the body
only when it returns `nil`.
```php title="verify_webhook.php"
$tolerance) {
throw new ClipmuxWebhookError('stale');
}
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
if (!hash_equals($expected, $signature)) {
throw new ClipmuxWebhookError('bad_signature');
}
return json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
}
```
Call it with `file_get_contents('php://input')` and the
`X-Webhook-Timestamp` and `X-Webhook-Signature` headers, which PHP puts in
`$_SERVER['HTTP_X_WEBHOOK_TIMESTAMP']` and
`$_SERVER['HTTP_X_WEBHOOK_SIGNATURE']`.
Don't write your own if one of these fits: the comparison must be constant
time, and the timestamp check matters as much as the HMAC.
## Test against the vectors [#test-against-the-vectors]
ClipMux publishes test vectors, the cases its own server, Node SDK and the
snippets above are tested against:
[`internal/webhooks/testdata/vectors.json`](https://github.com/visheshgubrani/clipmux/blob/main/internal/webhooks/testdata/vectors.json).
Each case gives a `secret`, a clock (`now`), a `body` and the `headers`,
with whether it should verify (`valid`) and, when not, the `reason`. Run
your verifier over every case with your clock set to `now`; it must give
the same answers.
## During a secret rotation [#during-a-secret-rotation]
While you rotate a secret, deliveries are signed with the old secret until
you activate the new one, then with the new one. Your verifier should accept
either for that time: try the new secret, and if the signature doesn't
match, try the old one. See
[Retries, redelivery and secret rotation](/docs/build/webhooks/retries).
## Check it works [#check-it-works]
Forward real events to your handler with `listen`, which signs them with
your `CLIPMUX_WEBHOOK_SECRET`:
```bash
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook --since 10m
```
Each forwarded event prints your handler's status. `200` means it verified.
`400` means it didn't:
- `bad_signature`: the handler's secret isn't the one `listen` signs with,
or the body was parsed before you verified it.
- `stale`: your machine's clock is more than 5 minutes off.
- `missing_header`: a proxy in front of your app dropped the headers.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Develop locally with listen](/docs/build/webhooks/listen)
- [Webhook events](/docs/reference/webhooks)
---
# Develop locally with listen
Receive your app's webhook events on a laptop the ClipMux server can't reach, signed so your handler verifies them unchanged.
Source: https://clipmux.com/docs/build/webhooks/listen
While you develop, your app runs on `localhost`, and the ClipMux server
can't POST webhooks to it. `listen` fixes that without a tunnel: it
long-polls your app's events from the server and forwards each one to your
local handler, signed as a real delivery would be. Your handler's code
doesn't change between development and production.
There are two versions: `npx @clipmux/node listen` for apps built with the
Node SDK, and the server binary's `clipmux listen` for any other language.
## Before you start [#before-you-start]
- `CLIPMUX_URL` and `CLIPMUX_API_KEY` for your app, in your env file or
environment. The key needs `assets:read`, which the default scopes
include.
- Your app running locally, with its webhook handler.
- Your app doesn't need a webhook endpoint registered for this. `listen`
reads the same events an endpoint would receive.
## With @clipmux/node [#with-clipmuxnode]
```bash
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
```txt
Forwarding "My app dev" events to http://localhost:3000/api/clipmux/webhook, signed with CLIPMUX_WEBHOOK_SECRET. Ctrl-C stops.
✓ video.asset.ready ast_… → 200
```
It signs each event with your own `CLIPMUX_WEBHOOK_SECRET`, so
`clipmuxHandler` or `clipmux.webhooks.verify` accepts it as it is. Any
secret works here. If your app has no webhook endpoint yet, `init` writes a
local one (`whsec_local_…`) for `listen`, and `doctor` warns that it's for
`listen` only.
| Flag | What it does |
| --- | --- |
| `--forward-to URL` | Your local webhook URL. Required. Without a scheme, `http://` is assumed. |
| `--since DURATION` | Also replay events from this long ago, such as `10m` or `2h`. Without it, only new events. |
| `--events LIST` | Only these event types, comma separated, such as `video.asset.ready,video.asset.track.ready`. |
| `--env-file FILE` | Where to read the settings. Default `.env.local`, or `.env` if there's no `.env.local`. |
Each event is tried up to four times if your handler is unreachable or
answers `5xx`, then `listen` moves on.
## With clipmux listen, for any language [#with-clipmux-listen-for-any-language]
The server binary has its own `listen`. It signs with a secret it makes
for you, which you set as your app's webhook secret:
```bash
CLIPMUX_API_KEY=cmx_… clipmux listen --server https://video.example.com --forward-to localhost:8000/webhooks
```
```txt
Forwarding events to http://localhost:8000/webhooks
Webhook secret: whsec_… (set it as your app's webhook secret; it stays the same next time)
```
It reads `CLIPMUX_API_KEY` from the environment, not from an env file. The
secret is kept in a `clipmux` folder in your user's config directory (or
`CLIPMUX_AGENT_DIR`), so it stays the same between runs. To choose it yourself, set `CLIPMUX_LISTEN_SECRET`. `--server`
defaults to `CLIPMUX_SERVER`, then `CLIPMUX_URL`. It takes `--events` and
`--since` like the Node version; `--since` takes a Go duration such as
`10m` or `1h30m`. See [Command line](/docs/reference/cli).
## What it forwards [#what-it-forwards]
Each event is POSTed to your URL exactly as a webhook endpoint receives it,
with the same headers: `X-Webhook-Event`, `X-Webhook-Id`,
`X-Webhook-Timestamp` and `X-Webhook-Signature`. Underneath, both versions
read `GET /v1/events`, the app's events oldest first, long-polling for new
ones.
`listen` sees only your API key's app. Make a separate ClipMux app for each
developer, so your test uploads and events don't mix with anyone else's or
with production.
## Check it works [#check-it-works]
1. Start your app, then `listen`.
2. Upload a short file to the same app:
```bash
npx @clipmux/node upload sample.mp4 --passthrough lesson_42
```
3. When encoding finishes, `listen` prints `✓ video.asset.ready ast_… → 200`.
If the line shows another status, it's your handler's answer:
- `400`: the signature didn't verify. With `npx @clipmux/node listen`, your
app must read the same `CLIPMUX_WEBHOOK_SECRET`. With `clipmux listen`,
set your app's secret to the one it printed.
- `404`: `--forward-to` isn't your handler's route.
- `unreachable`: nothing is listening on that port.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Verify webhook signatures](/docs/build/webhooks/verify-signatures)
- [Production checklist](/docs/build/going-live/production-checklist)
---
# Retries, redelivery and secret rotation
How ClipMux retries a failed webhook for 24 hours, how to send one again, and how to change a webhook secret without losing events.
Source: https://clipmux.com/docs/build/webhooks/retries
A webhook that fails isn't lost at once. ClipMux retries it on a schedule
for 24 hours, backs off from an endpoint that keeps failing, and keeps a
log of every delivery that the server's owner can read and redeliver from
the dashboard. This page covers that schedule, redelivery, and changing an
endpoint's secret with no downtime.
## Before you start [#before-you-start]
- A webhook endpoint for your app; see [Receive webhooks](/docs/build/webhooks).
- For redelivery and rotation, the owner's account on the ClipMux server.
These are owner actions in the dashboard; an API key can't reach them.
## What counts as delivered [#what-counts-as-delivered]
Any `2xx` answer within 10 seconds. Everything else is a failure: another
status, a redirect (never followed), a timeout, or a connection that
fails. Each try is signed with a fresh timestamp, and every try of the same
event has the same `X-Webhook-Id`.
## The retry schedule [#the-retry-schedule]
After a failed try, ClipMux waits, then tries again:
| Try | About this long after the event |
| --- | --- |
| 1 | at once |
| 2 | 30 seconds |
| 3 | 2½ minutes |
| 4 | 12½ minutes |
| 5 | 42½ minutes |
| 6 | 1 hour 42½ minutes |
| 7 | 3 hours 42½ minutes |
| 8 | 7 hours 42½ minutes |
| 9 | 15 hours 42½ minutes |
| 10 | 23 hours 42½ minutes |
| 11 | 24 hours, the last |
After the last try fails, the delivery is marked `failed`. Your
[catch-up job](/docs/build/webhooks) picks up anything you missed, or the
owner can redeliver it.
Events are delivered independently, so a failing one doesn't hold up the
next, and they can arrive out of order.
## When an endpoint keeps failing [#when-an-endpoint-keeps-failing]
After 5 failed tries in a row to the same endpoint, ClipMux stops sending
to it for a minute, then for twice as long after each further failure, up
to an hour. Deliveries skipped this way aren't charged a try, and their
24-hour window doesn't move, so an endpoint that comes back catches up. One
success resets the count.
In the dashboard, an endpoint shows **Healthy**, the number of failures in
a row, or **Paused after N failures** while it's being skipped.
## See deliveries and redeliver [#see-deliveries-and-redeliver]
Under **Apps & API**, open your app, then **Webhooks**, and choose
**Deliveries** on an endpoint. The latest 100 deliveries show their event
type, HTTP status or error (`timeout`, `connection_failed`, `http_500` and
so on), how many tries they took, and when the next try is due. A delivery
that gave up has **Redeliver**: it's retried on the same schedule for a
fresh 24 hours.
The same as owner routes:
- `GET /v1/webhook-endpoints/{id}/deliveries` lists the latest 100, each
with `status` (`pending`, `delivered` or `failed`), `attempts`,
`last_status`, `last_error` and `next_attempt_at`.
- `POST /v1/webhook-deliveries/{id}/redeliver` answers `202` for a `failed`
delivery, and `409 not_redeliverable` for any other.
Since delivery is at least once, a redelivered event may be one your
handler already applied. An idempotent handler doesn't care.
## Rotate a secret with no downtime [#rotate-a-secret-with-no-downtime]
An endpoint can hold a new secret beside the current one. Deliveries stay
signed with the current secret until you activate the new one, so you can
deploy first and switch after.
### Create the new secret [#create-the-new-secret]
In the dashboard, choose **Rotate secret** on the endpoint, or call
`POST /v1/webhook-endpoints/{id}/secret`, which answers
`201 {"secret": "whsec_…", "active": false}`. The secret is shown once;
copy it into your secret store.
### Deploy a verifier that accepts both [#deploy-a-verifier-that-accepts-both]
Deploy your app so it accepts the new secret and the current one. With the
Node SDK, try one, then the other:
```ts title="webhook.ts"
import { verifyWebhook, WebhookVerificationError } from '@clipmux/node'
async function verifyEither(raw: string, headers: Headers) {
try {
return await verifyWebhook(process.env.CLIPMUX_WEBHOOK_SECRET!, raw, headers) // the new secret
} catch (err) {
const previous = process.env.PREVIOUS_WEBHOOK_SECRET
if (!(err instanceof WebhookVerificationError) || err.reason !== 'bad_signature' || !previous) throw err
return verifyWebhook(previous, raw, headers)
}
}
```
The Python, Go and PHP functions in
[Verify webhook signatures](/docs/build/webhooks/verify-signatures) work the
same way: call them with the new secret, and on `bad_signature` with the
old one.
### Activate it [#activate-it]
Choose **Activate new secret** in the dashboard, or call
`POST /v1/webhook-endpoints/{id}/secret/activate`, which answers
`{"active": true}`. From the next try, deliveries are signed with the new
secret, retries of older events included. Without a waiting secret it
answers `409 no_pending_secret`.
### Drop the old secret [#drop-the-old-secret]
Once you've seen deliveries verify with the new secret, remove the old one
from your app.
`clipmuxHandler` verifies with one secret. If you use it, set
`CLIPMUX_WEBHOOK_SECRET` to the new secret, deploy, and activate right
after. Deliveries that arrive in between fail and are retried, so nothing
is lost; they arrive a little late.
If a secret leaked, rotate it the same way, and activate as soon as your
app accepts the new one.
## Check it works [#check-it-works]
After activating, open **Deliveries**: new deliveries show `200`. A row
with `400` means your app is still checking only the old secret, or not yet
the new one.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Verify webhook signatures](/docs/build/webhooks/verify-signatures)
- [Management API](/docs/reference/management-api)
---
# Views, watch time and unique viewers
Read how often your videos are watched, for how long and by how many people, counted by ClipMux's delivery with no player beacon.
Source: https://clipmux.com/docs/build/analytics
ClipMux counts playback where it serves it. Every view, every segment of
watch time and every byte comes from delivery's own requests, so there is
no analytics script to add to your pages and nothing for a viewer's ad
blocker to stop. Your backend reads the numbers from the API; the server's
owner sees them under **Analytics** in the dashboard.
## Before you start [#before-you-start]
- An API key with the `analytics:read` scope. Keys don't have it by
default, including the one `init` makes; the server's owner adds it to a
new key on the server:
```bash
clipmux admin create-key --app "My app" --scopes uploads:write,assets:read,assets:write,analytics:read
```
The owner can also create one with `POST /v1/apps/{id}/api-keys` and
`"scopes"` in the body.
- For unique viewers, tokens signed with a viewer ID; see below.
## Read the numbers [#read-the-numbers]
```ts
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux({ apiKey: process.env.ANALYTICS_API_KEY })
const app = await clipmux.analytics.get('30d') // every video of the key's app
const one = await clipmux.analytics.asset('ast_…', '7d') // one video
```
```bash
curl -s 'https://video.example.com/v1/analytics?range=30d' \
-H "Authorization: Bearer $ANALYTICS_API_KEY"
curl -s 'https://video.example.com/v1/analytics/assets/ast_…?range=7d' \
-H "Authorization: Bearer $ANALYTICS_API_KEY"
```
`range` is `24h`, `7d`, `30d` or `90d`; anything else is
`400 invalid_request`. `GET /v1/analytics` covers the key's own app.
`GET /v1/analytics/assets/{id}` covers one of its videos, and a deleted
video keeps its history.
```json
{
"totals": { "views": 1840, "watch_seconds": 302400, "unique_viewers": 412, "bytes_delivered": 98123456789 },
"previous": { "views": 1502, "watch_seconds": 251000, "unique_viewers": null, "bytes_delivered": 80211000000 },
"series": [{ "t": "2026-11-03T00:00:00Z", "views": 260, "watch_seconds": 43100, "bytes_delivered": 14000000000 }],
"top_assets": [{ "asset_id": "ast_…", "title": "Lesson 42", "views": 310, "watch_seconds": 61000, "bytes_delivered": 17000000000 }],
"storage": { "source_bytes": 524288000, "media_bytes": 2147483648, "total_bytes": 2671771648 },
"collecting": { "builtin": true, "edge": "not_used" }
}
```
| Field | What it is |
| --- | --- |
| `totals` | The range's views, watch time in seconds, unique viewers and bytes. They include deleted videos' history. |
| `previous` | The same for the same length of time immediately before, to show a change. |
| `series` | One bucket per hour for `24h`, per UTC day otherwise, oldest first, with empty buckets as zeros. `t` is the bucket's start. The last bucket is the current one, so it's partial. |
| `top_assets` | Up to 10 live videos, by views (and bytes when sampled views read zero). Not in the one-video response. A `title` may be missing. |
| `storage` | Current storage taken across live sources (`source_bytes`), encoded outputs and tracks (`media_bytes`), and their sum (`total_bytes`). Zeros for deleted videos. |
| `collecting` | Where counts come from and edge pull health; see [Edge counts](#edge-counts). |
## What counts [#what-counts]
- **A view** is one `master.m3u8` served. A player loads the master once
when it starts, so a view is one play start. A viewer who reloads the page
makes another view.
- **Watch time** is 6 seconds for each audio segment served (or video
segment, for a video with no audio). It counts what was fetched, not what
was watched, so it overcounts by the player's buffer ahead: a viewer who
stops after 10 seconds may have fetched 30.
- **Bytes** are every body delivery sent.
Only successful answers count; refusals never do. Dashboard previews,
library posters and the server's setup test aren't counted. Plays through
[share links](/docs/build/play/share-links) are.
## Unique viewers [#unique-viewers]
ClipMux doesn't know who your viewers are. To count them, put a stable ID
for each viewer in the playback token's `vid` claim:
```ts
// clipmuxHandler's playback callback
return { viewerId: user.id }
// or when you sign a token yourself
await clipmux.playback.token('pid_…', { viewerId: user.id })
```
For anonymous viewers, use a random ID you keep in their session. ClipMux
stores only a keyed hash of `vid`, never the ID itself. `unique_viewers`
counts distinct viewers by hour for `24h` (matching exact `[start, stop)`
and `previous` windows) and by UTC day for longer ranges, excluding poster
requests, and is `null` when no view in the range carried a `vid`.
Nothing in analytics stores an IP address, User-Agent, referrer, token or
raw viewer ID.
## How long numbers are kept [#how-long-numbers-are-kept]
- Hourly counts, behind the `24h` range: 14 days.
- Daily counts and viewer hashes: 180 days, enough for two `90d` ranges.
Older numbers are deleted.
## Edge counts [#edge-counts]
With [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare), most
requests never reach the ClipMux server. The Cloudflare Worker counts them
instead, and the server pulls those counts in every 5 minutes once the
owner connects [edge analytics](/docs/self-host/delivery/edge-analytics).
`collecting.edge` says which applies:
| `collecting.edge` | Meaning |
| --- | --- |
| `not_used` | No Cloudflare delivery. The server counts everything. |
| `not_connected` | Cloudflare delivers, but its counts aren't pulled in, so most plays are missing. |
| `connected` | Edge counts are pulled in. The last few minutes appear on the next pull. |
With Cloudflare delivery, Cloudflare serves your viewers, and the Worker
records each counted request in Cloudflare's Analytics Engine: the
project, app, video and playback IDs, the kind of request, the views,
watch time and bytes, and the keyed viewer hash. The ClipMux server reads
them back with a read-only token.
## Check it works [#check-it-works]
Play a video for a minute with a token that carries a `vid`, then:
```bash
curl -s 'https://video.example.com/v1/analytics/assets/ast_…?range=24h' \
-H "Authorization: Bearer $ANALYTICS_API_KEY"
```
`totals.views` is at least 1 and `unique_viewers` at least 1. Counts reach
Postgres within about 15 seconds.
- `403 insufficient_scope`: the key lacks `analytics:read`.
- `404 not_found`: the video belongs to another app.
- `unique_viewers` is `null`: no token in the range had a `vid`.
## Next [#next]
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Edge analytics](/docs/self-host/delivery/edge-analytics)
- [Analytics API reference](/docs/reference/api/analytics)
---
# Next.js integration
Add ClipMux uploads, playback and webhooks to a Next.js App Router app with one route file and one client component.
Source: https://clipmux.com/docs/build/frameworks/nextjs
In Next.js, ClipMux is one route handler and one client component. The
route handler answers the uploader, the player and ClipMux's webhooks; the
component puts the two elements on your page. This is the setup the
[quickstart](/docs/build/quickstart) walks through, with the details
around it.
For a whole app built this way, see
[`examples/nextjs-lms`](https://github.com/visheshgubrani/clipmux/tree/main/examples/nextjs-lms): a small course site where
instructors upload, enrolled students watch, and anyone else is refused.
## Before you start [#before-you-start]
- A Next.js app with the App Router, on Node 20.19 or later.
- A ClipMux server and its owner to approve your app.
- The packages, and your app connected:
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
## The env file [#the-env-file]
`init` writes five variables to `.env.local`, which Next.js loads on the
server:
| Variable | What it is |
| --- | --- |
| `CLIPMUX_URL` | The ClipMux server's public URL. |
| `CLIPMUX_API_KEY` | Your app's API key, `cmx_…`. |
| `CLIPMUX_SIGNING_KID` | The ID of your app's signing key. |
| `CLIPMUX_SIGNING_KEY` | The signing key itself, a PEM. |
| `CLIPMUX_WEBHOOK_SECRET` | The webhook secret, `whsec_…`. |
None has the `NEXT_PUBLIC_` prefix, so none reaches the browser. Keep it
that way, and keep `.env.local` out of git. In production, set the same
five in your host's secret settings.
## The route file [#the-route-file]
```ts title="app/api/clipmux/[action]/route.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
export const POST = clipmuxHandler({
// Someone wants to upload: say what the upload is, or return null to refuse.
async upload(req, { file }) {
await requireInstructor(req)
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name, generate: { subtitles: true } }
},
// Someone wants to watch: say who they are, or return null to refuse.
async playback(req, { playbackId }) {
const user = await getUser(req)
return (await canWatch(user, playbackId)) ? { viewerId: user.id } : null
},
// A verified webhook, with the video re-fetched so it's current.
async asset(asset) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
})
```
The `[action]` segment makes this one file answer POSTs to
`/api/clipmux/upload`, `/api/clipmux/playback` and
`/api/clipmux/webhook`. `requireInstructor`, `getUser`, `canWatch` and `db`
stand for your own code.
- `upload` runs when someone chooses a file. Return the upload's settings,
or `null` to refuse with `403`.
- `playback` runs when someone presses play, and again when the token runs
out. Return `{ viewerId }`, or `null` to refuse.
- `asset` runs for each verified webhook, with the video re-fetched.
A callback you leave out makes its route a `404`. See
[Receive webhooks](/docs/build/webhooks) for `event` and `onError`.
The handler reads the request body itself, so the webhook's raw body
reaches it untouched; there's nothing to configure. It uses only Web APIs,
so the route also runs on the Edge runtime.
## The client component [#the-client-component]
```tsx title="app/lessons/[id]/video.tsx"
'use client'
import type {} from '@clipmux/player/react' // JSX types only
import type {} from '@clipmux/uploader/react'
import { useEffect } from 'react'
export function LessonVideo({ lessonId, playbackId }: { lessonId: string; playbackId?: string }) {
// The elements need the DOM, so load them in the browser only.
useEffect(() => {
import('@clipmux/uploader/element')
import('@clipmux/player/element')
}, [])
return (
<>
{playbackId && }
>
)
}
```
`'use client'` and the `import()` inside `useEffect` keep the elements out
of the server render: they need the DOM, and the player needs Media Source.
The two `import type` lines add the elements' JSX types without loading
them.
Render it from a server component, which reads the playback ID from your
database:
```tsx title="app/lessons/[id]/page.tsx"
import { LessonVideo } from './video'
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const lesson = await db.lesson.findUnique({ where: { id } })
return
}
```
To react when a viewer is refused, handle `clipmux-denied` and call
`router.refresh()` to re-render the page's locked state. See
[Add the player](/docs/build/play/player).
## Content-Security-Policy [#content-security-policy]
If your app sends a Content-Security-Policy, pages with the elements must
allow ClipMux's origins. `doctor` prints them:
```bash
npx @clipmux/node doctor
```
For each directive (`connect-src`, `media-src`, `img-src` and `style-src`), it
names the exact origins your server uses.
Add those sources to the directives your app already sets, in
`next.config.ts` headers or your middleware. `connect-src` also lists the
storage bucket that upload parts go to, when it isn't the ClipMux server.
## Check it works [#check-it-works]
Run `npx @clipmux/node doctor`; it ends with `✓ Ready.` Then forward
webhooks and upload from the lesson page:
```bash
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
`listen` prints `✓ video.asset.ready ast_… → 200` when encoding is done,
and the video plays after a reload.
- The uploader shows an error at once: your `upload` callback returned
`null`, or threw.
- `/api/clipmux/upload` answers with Next.js's own 404 page: the file isn't
at `app/api/clipmux/[action]/route.ts`.
- `listen` shows `400`: the app reads a different `CLIPMUX_WEBHOOK_SECRET`
from the one `listen` signs with.
## Next [#next]
- [Production checklist](/docs/build/going-live/production-checklist)
- [Add the player](/docs/build/play/player)
- [Troubleshooting](/docs/build/going-live/troubleshooting)
---
# Express integration
Mount the ClipMux handler in an Express app with toNodeListener, before any body parser.
Source: https://clipmux.com/docs/build/frameworks/express
`clipmuxHandler` is a Fetch handler: it takes a `Request` and returns a
`Response`. `toNodeListener` from `@clipmux/node/express` adapts it to
Node's `(req, res, next)` shape, so one Express route answers the uploader,
the player and ClipMux's webhooks.
[`examples/express`](https://github.com/visheshgubrani/clipmux/tree/main/examples/express) is a whole app built this way.
## Before you start [#before-you-start]
- An Express app on Node 20.19 or later.
- The packages, and your app connected with `init`, which writes the
`CLIPMUX_*` settings to `.env.local` (or `.env`, if you have one and no
`.env.local`):
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
`new ClipMux()` reads the settings from `process.env`, so load the env file
before the handler runs, for example with `node --env-file=.env.local`.
## Mount the route [#mount-the-route]
```ts
import { clipmuxHandler } from '@clipmux/node/handlers'
import { toNodeListener } from '@clipmux/node/express'
app.post('/api/clipmux/:action', toNodeListener(clipmuxHandler({ … }))) // before express.json()
```
The `{ … }` holds your `upload`, `playback` and `asset` callbacks, exactly as
in the [quickstart](/docs/build/quickstart)'s route file. The route answers
POSTs to `/api/clipmux/upload`, `/api/clipmux/playback` and
`/api/clipmux/webhook`.
Mount it before `express.json()`. The webhook's signature covers the raw
body, and a body another middleware already parsed can't be checked. If
the route must come later, give it `express.raw({ type: '*/*' })`. A body
parsed into an object is refused with an error that says so.
Each callback gets a Fetch `Request`, not Express's `req`. Read cookies and
headers from `req.headers`, and query parameters from `new URL(req.url)`.
The handler reads the body itself: the upload's `file` and the player's
`playbackId` are in the callback's second argument.
An error the adapter can't turn into a response goes to Express's `next`,
so your error middleware sees it.
## Add the elements [#add-the-elements]
In any page your app serves, load the two elements and point them at the
route:
```html
```
The bare imports need a bundler, or an import map that points
`@clipmux/uploader/element` and `@clipmux/player/element` at the files in
`node_modules`.
## Fastify and plain node:http [#fastify-and-plain-nodehttp]
The same listener runs wherever Node's request and response objects are.
On plain `node:http`, route to it yourself:
```ts title="server.ts"
import { createServer } from 'node:http'
import { clipmuxHandler } from '@clipmux/node/handlers'
import { toNodeListener } from '@clipmux/node/express'
const clipmux = toNodeListener(clipmuxHandler({ /* upload, playback, asset */ }))
createServer((req, res) => {
if (req.url?.startsWith('/api/clipmux/')) return clipmux(req, res)
res.statusCode = 404
res.end()
}).listen(3000)
```
In Fastify, pass it the raw request and response, `request.raw` and
`reply.raw`. The listener reads the body from the raw request, so Fastify
must not have read it first.
## Check it works [#check-it-works]
```bash
npx @clipmux/node doctor
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
`doctor` ends with `✓ Ready.` Upload a file from your page; when it's
encoded, `listen` prints `✓ video.asset.ready ast_… → 200`.
- `listen` shows `500`, and your server logs `the request body was already
parsed`: the route is after `express.json()`.
- `listen` shows `400`: the secret is wrong, or the body was changed before
the handler read it.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Add the player](/docs/build/play/player)
- [Production checklist](/docs/build/going-live/production-checklist)
---
# Hono integration
Add ClipMux uploads, playback and webhooks to a Hono app by passing its raw request to the ClipMux handler on one route.
Source: https://clipmux.com/docs/build/frameworks/hono
`clipmuxHandler` takes a Fetch `Request` and returns a `Response`, and Hono
gives you the raw `Request` as `c.req.raw`. One route answers the uploader,
the player and ClipMux's webhooks.
## Before you start [#before-you-start]
- A Hono app on a runtime with `process.env`: Node 20.19 or later, or Bun.
On Cloudflare Workers, see
[SvelteKit, Remix, Bun, Deno and Workers](/docs/build/frameworks/fetch-runtimes).
- The packages, and your app connected with `init`, which writes the
`CLIPMUX_*` settings to `.env.local`:
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
## Mount the route [#mount-the-route]
```ts title="src/index.ts"
import { Hono } from 'hono'
import { clipmuxHandler } from '@clipmux/node/handlers'
const clipmux = clipmuxHandler({
async upload(req, { file }) {
const user = await requireInstructor(req)
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name, generate: { subtitles: true } }
},
async playback(req, { playbackId }) {
const user = await getUser(req)
return (await canWatch(user, playbackId)) ? { viewerId: user.id } : null
},
async asset(asset) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
})
const app = new Hono()
app.post('/api/clipmux/:action', (c) => clipmux(c.req.raw))
export default app
```
The callbacks are the same as in the [quickstart](/docs/build/quickstart)'s
route file; `requireInstructor`, `getUser`, `canWatch` and `db` stand for
your own code. They get the Fetch `Request`, so read cookies and headers
from `req.headers` and query parameters from `new URL(req.url)`.
Let the handler read the body. Don't parse it in a middleware or validator
on this route first: the webhook's signature covers the raw body.
## Add the elements [#add-the-elements]
Load the two elements in your pages and point them at the route:
```html
```
## Check it works [#check-it-works]
```bash
npx @clipmux/node doctor
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
`doctor` ends with `✓ Ready.` Upload a file from your page; when it's
encoded, `listen` prints `✓ video.asset.ready ast_… → 200`. A `400` there
means the secret is wrong, or the body was read before the handler.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Add the player](/docs/build/play/player)
- [Production checklist](/docs/build/going-live/production-checklist)
---
# SvelteKit, Remix, Bun, Deno and Workers
Wire the ClipMux handler into any framework or runtime that speaks Fetch requests and responses.
Source: https://clipmux.com/docs/build/frameworks/fetch-runtimes
`clipmuxHandler` is a Fetch handler: a function from `Request` to
`Response`, using only Web APIs. Any framework or runtime that hands you a
`Request` can run it. Each section below is the whole wiring; the
callbacks are the same everywhere.
## Before you start [#before-you-start]
- The packages, and your app connected with `init`, which writes the
`CLIPMUX_*` settings to `.env.local`:
```bash
npm i @clipmux/node @clipmux/uploader @clipmux/player
npx @clipmux/node init --server https://video.example.com
```
```bash
pnpm add @clipmux/node @clipmux/uploader @clipmux/player
pnpm dlx @clipmux/node init --server https://video.example.com
```
- Your callbacks. Every example below imports them from a module of your
own, `$lib/clipmux` or `./clipmux`:
```ts title="clipmux.ts"
import type { HandlerOptions } from '@clipmux/node/handlers'
export const callbacks: HandlerOptions = {
async upload(req, { file }) {
const user = await requireInstructor(req)
const lesson = new URL(req.url).searchParams.get('lesson')
return { passthrough: `lesson_${lesson}`, title: file.name, generate: { subtitles: true } }
},
async playback(req, { playbackId }) {
const user = await getUser(req)
return (await canWatch(user, playbackId)) ? { viewerId: user.id } : null
},
async asset(asset) {
await db.lesson.update({
where: { ref: asset.passthrough },
data: { status: asset.status, playbackId: asset.playback_ids[0]?.id },
})
},
}
```
`requireInstructor`, `getUser`, `canWatch` and `db` stand for your own code.
The handler picks its route from the last part of the URL path, `upload`,
`playback` or `webhook`, and answers only POST. Mount it so those three
paths reach it, and let it read the request body itself: the webhook's
signature covers the raw body.
## SvelteKit [#sveltekit]
```ts title="src/routes/api/clipmux/[action]/+server.ts"
import { ClipMux } from '@clipmux/node'
import { clipmuxHandler } from '@clipmux/node/handlers'
import { env } from '$env/dynamic/private'
import type { RequestHandler } from './$types'
import { callbacks } from '$lib/clipmux'
const clipmux = clipmuxHandler({ ...callbacks, clipmux: new ClipMux({ env }) })
export const POST: RequestHandler = ({ request }) => clipmux(request)
```
`$env/dynamic/private` gives the client the server's environment in
development and on every adapter, and never reaches the browser. In
development, SvelteKit reads `.env` and `.env.local`.
## Remix [#remix]
```ts title="app/routes/api.clipmux.$action.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
import type { ActionFunctionArgs } from '@remix-run/node'
import { callbacks } from '~/clipmux'
const clipmux = clipmuxHandler(callbacks)
export const action = ({ request }: ActionFunctionArgs) => clipmux(request)
```
`new ClipMux()` reads `process.env`. Make sure the `CLIPMUX_*` settings are
there in development too, for example by starting the dev server with
`node --env-file=.env.local` or loading the file with dotenv.
## Bun [#bun]
```ts title="server.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
import { callbacks } from './clipmux'
const clipmux = clipmuxHandler(callbacks)
Bun.serve({
port: 3000,
fetch(req) {
if (new URL(req.url).pathname.startsWith('/api/clipmux/')) return clipmux(req)
return new Response('Not found', { status: 404 })
},
})
```
Bun loads `.env.local` into `process.env` by itself.
## Deno [#deno]
```ts title="server.ts"
import { ClipMux } from '@clipmux/node'
import { clipmuxHandler } from '@clipmux/node/handlers'
import { callbacks } from './clipmux.ts'
const clipmux = clipmuxHandler({ ...callbacks, clipmux: new ClipMux({ env: Deno.env.toObject() }) })
Deno.serve({ port: 3000 }, (req) => {
if (new URL(req.url).pathname.startsWith('/api/clipmux/')) return clipmux(req)
return new Response('Not found', { status: 404 })
})
```
Passing `env` hands the client its settings directly. Run it with
`deno run --allow-net --allow-env --env-file=.env.local server.ts`. Install
the packages with npm as above, or import them with the `npm:` prefix
(`npm:@clipmux/node`).
## Cloudflare Workers [#cloudflare-workers]
Workers have no `process.env`; their settings arrive as `env` with each
request. Give the handler a client built from it:
```ts title="src/index.ts"
import { ClipMux } from '@clipmux/node'
import { clipmuxHandler } from '@clipmux/node/handlers'
import { callbacks } from './clipmux'
export default {
fetch: (req: Request, env: Record) =>
clipmuxHandler({ ...callbacks, clipmux: new ClipMux({ env }) })(req),
}
```
Set the five `CLIPMUX_*` values as secrets of the Worker, for example with
`wrangler secret put CLIPMUX_API_KEY`, rather than in `wrangler.toml`. Route
only `/api/clipmux/*` to this code if the Worker serves other paths too.
## Add the elements [#add-the-elements]
In your pages, load the two elements and point them at the route:
```html
```
In a server-rendered framework, load the elements in the browser only:
in SvelteKit from `onMount`, in Remix from `useEffect`, as in
[Add the player](/docs/build/play/player).
## Check it works [#check-it-works]
```bash
npx @clipmux/node doctor
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
```
Use your app's port. `doctor` ends with `✓ Ready.` Upload a file from your
page; when it's encoded, `listen` prints `✓ video.asset.ready ast_… → 200`.
- `500` from the handler, with a `ClipMuxConfigError` in your logs naming a
variable: the settings didn't reach the client. On SvelteKit, Workers and
Deno, check you passed `clipmux: new ClipMux({ env })`.
- `400` in `listen`: the secret is wrong, or something read the body first.
## Next [#next]
- [Receive webhooks](/docs/build/webhooks)
- [Express](/docs/build/frameworks/express), for Node servers with
middleware
- [Production checklist](/docs/build/going-live/production-checklist)
---
# Any language
Use ClipMux from Python, Go, PHP, Ruby or any backend with its REST API, an API key and two small pieces of tested code.
Source: https://clipmux.com/docs/build/frameworks/any-language
There is a server SDK for Node only, but nothing in ClipMux needs it. Your
backend makes three kinds of call, and each works from any language:
- **REST calls** with an API key, to create uploads and read videos.
- **Signing playback tokens**, locally, with your app's signing key.
- **Verifying webhooks**, an HMAC check over the raw body.
The browser elements, `` and ``, talk to
your own routes, so they work with a backend in any language.
## Before you start [#before-you-start]
- Your app's credentials. Approve the app with
`npx @clipmux/node init --server https://video.example.com` from any
folder (it needs Node, but your backend doesn't), or on the server run
`clipmux admin create-integration --app NAME --webhook-url URL >> .env`.
Either way you get `CLIPMUX_URL`, `CLIPMUX_API_KEY`,
`CLIPMUX_SIGNING_KID`, `CLIPMUX_SIGNING_KEY` and
`CLIPMUX_WEBHOOK_SECRET`.
- Keep all but `CLIPMUX_URL` on your server, out of browser code and logs.
## Call the API [#call-the-api]
Every call goes to the server's public URL with the API key as a bearer
token:
```bash
curl -s https://video.example.com/v1/app \
-H "Authorization: Bearer $CLIPMUX_API_KEY"
```
`GET /v1/app` returns your app, its scopes, the media origin (`base_url`)
and the longest token lifetime. A key's default scopes are `uploads:write`,
`assets:read` and `assets:write`. Requests and responses are JSON, and an
error is `{"error": {"code": "…", "message": "…"}}` with a stable `code`.
Every `POST` takes an `Idempotency-Key` header. A retry with the same key
and the same request returns the first response, so a network error never
makes a second upload:
```bash
curl -s https://video.example.com/v1/uploads \
-H "Authorization: Bearer $CLIPMUX_API_KEY" \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: lesson_42' \
-d '{"size": 10485760, "passthrough": "lesson_42", "title": "Lesson 42"}'
```
A `429 rate_limited` carries `Retry-After` in seconds; wait that long and
retry.
### The OpenAPI spec [#the-openapi-spec]
The server describes its integration API, delivery URLs and webhooks as
OpenAPI 3.1 at `GET /openapi.json`, with no credential:
```bash
curl -s https://video.example.com/openapi.json -o clipmux-openapi.json
```
Generate a client from it with your language's OpenAPI tools, or browse it
in the [API reference](/docs/reference/api).
## Uploads from the browser [#uploads-from-the-browser]
`` POSTs `{"size", "name",
"type"}` to your route, with the page's cookies. Your route checks the user,
calls `POST /v1/uploads` with its API key, and answers with ClipMux's
response plus one field, `endpoint`, set to your `CLIPMUX_URL`:
```json
{
"upload_id": "upl_…",
"asset_id": "ast_…",
"part_size": 33554432,
"part_count": 1,
"upload_token": "…",
"playback_ids": [{ "id": "pid_…", "policy": "signed", "playable": false, "status": "active" }],
"endpoint": "https://video.example.com"
}
```
The browser then sends the file in parts straight to storage with the
`upload_token`, which reaches only that upload. Answer `401` or `403` to
refuse. See [Upload from the browser](/docs/build/upload/browser).
## Playback [#playback]
For ``, give it your own token route with `getToken`, or a
route that answers its `session-url` POST. Either way your route checks the
viewer and signs a token. The signing code for Python, Go and PHP is in
[Sign playback tokens](/docs/build/play/sign-tokens); the player's side is
in [Add the player](/docs/build/play/player).
## Webhooks [#webhooks]
Verify each webhook over the raw body with your `whsec_…` secret, then
re-fetch the video with `GET /v1/assets/{id}` before you store anything.
The verifying code for Python, Go and PHP, and the test vectors to check
your own, are in
[Verify webhook signatures](/docs/build/webhooks/verify-signatures). To
receive webhooks on your laptop, run `clipmux listen`; see
[Develop locally with listen](/docs/build/webhooks/listen).
## Check it works [#check-it-works]
```bash
curl -s -o /dev/null -w '%{http_code}\n' https://video.example.com/v1/app \
-H "Authorization: Bearer $CLIPMUX_API_KEY"
```
- `200`: the key works.
- `401 unauthorized`: the key is wrong or revoked.
- `403 insufficient_scope` on a later call: the key lacks that call's
scope.
Then follow [Your first video with curl](/docs/build/first-video) from
upload to playback.
## Next [#next]
- [Your first video with curl](/docs/build/first-video)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Verify webhook signatures](/docs/build/webhooks/verify-signatures)
---
# Production checklist
Check credentials, webhooks, playback and error handling before real viewers use your ClipMux integration.
Source: https://clipmux.com/docs/build/going-live/production-checklist
Work through this list before your app's first real upload. Each item is
something that works in development and fails, or leaks, in production when
it's missed.
## Credentials [#credentials]
- [ ] **A separate ClipMux app for production.** Make one app per
environment: production, staging, and one per developer. Videos,
events and `passthrough` lookups are scoped to the app, so a test
upload never shows up in production.
- [ ] **The production credentials only in production.** Put the five
`CLIPMUX_*` values in your host's secret store, not in a committed
file or a container image.
- [ ] **Secrets stay on the server.** `CLIPMUX_API_KEY`,
`CLIPMUX_SIGNING_KEY` and `CLIPMUX_WEBHOOK_SECRET` never appear in
browser code, and no variable holding them has a public prefix such as
`NEXT_PUBLIC_`.
- [ ] **The key has only the scopes it needs.** The defaults are
`uploads:write`, `assets:read` and `assets:write`. Give
`analytics:read` to a separate key if only part of your app reads
analytics.
- [ ] **Nothing logs tokens, playback URLs, keys or webhook signatures.** A
playback URL contains its token.
## The server [#the-server]
- [ ] **The ClipMux server has its real public URL, on HTTPS.** Browsers
upload to it and play from its media origin, so `localhost` won't do.
The server refuses to make API keys while its public URL is loopback.
- [ ] **`doctor` passes with the production settings.**
```bash
npx @clipmux/node doctor --env-file .env.production
```
It must end with `✓ Ready.`
## Your pages [#your-pages]
- [ ] **The Content-Security-Policy allows ClipMux's origins.** Use the
`connect-src`, `media-src`, `img-src` and `style-src` sources that
`doctor` prints for the production app.
- [ ] **Uploads reach storage from your production origin.** Upload a file
from the production site, and watch the parts in the browser's network
panel. The record goes from uploading to processing to ready without a
reload.
## Webhooks [#webhooks]
- [ ] **A webhook endpoint is registered for the production app,** at a URL
ClipMux can reach, and it answers `200`.
- [ ] **`CLIPMUX_WEBHOOK_SECRET` is that endpoint's secret.** A
`whsec_local_…` secret from `init` is for `listen` only, and `doctor`
warns about it.
- [ ] **The handler is idempotent.** It upserts by `passthrough`, keeps the
highest `version`, and answers `200` for events that aren't yours.
- [ ] **A catch-up job runs.** Walk `clipmux.assets.changes({ since })` on
a schedule, so an event missed after 24 hours of retries is still
applied. See [Receive webhooks](/docs/build/webhooks).
- [ ] **The handler answers non-2xx only when your own store fails,** so
ClipMux retries what you couldn't save and nothing else.
## Playback [#playback]
- [ ] **Tokens are short.** 15 minutes, the SDK's default, for
``, which renews them. Sign longer only for native
playback.
- [ ] **`native` is passed through.** If you sign tokens yourself, pass the
player's `native` to `playback.token`, or Safari before 17.1 stops
when the first token expires.
- [ ] **A long session keeps playing.** Watch for more than 15 minutes and
check that renewals succeed.
- [ ] **A refused viewer sees your own state,** such as a sign-in or enrol
page, on `clipmux-denied`, not an error.
- [ ] **Tokens carry a viewer ID.** Pass `viewerId` so analytics count
unique viewers. ClipMux keeps only a keyed hash.
## Errors and clean-up [#errors-and-clean-up]
- [ ] **Errors are handled by `code`.** `ClipMuxError` has a stable `code`
and `status`; branch on those, not the message. See
[Troubleshooting](/docs/build/going-live/troubleshooting).
- [ ] **Uploads use an idempotency key,** such as your record's ID, so a
retried request can't make a second upload.
- [ ] **Videos you no longer need are deleted.** Delete replaced and
cancelled uploads' videos from a scheduled job, so a failure is
retried: `200`, `202` and `404` from `assets.delete` all mean done.
## Next [#next]
- [Troubleshooting](/docs/build/going-live/troubleshooting)
- [Receive webhooks](/docs/build/webhooks)
- [Security checklist](/docs/self-host/operate/security-checklist), for the
server's owner
---
# Troubleshoot your integration
What each error from the SDK, the handler, the player and the uploader means, and what to do about it.
Source: https://clipmux.com/docs/build/going-live/troubleshooting
Start with `doctor`. It checks the server, the API key and its scopes, the
signing key and the webhook secret, and says which line to fix:
```bash
npx @clipmux/node doctor
```
Every error from ClipMux has a stable `code`. A failed SDK call throws a
`ClipMuxError` with `status`, `code` and `details`, and its message says what
to do next. Every code is in [Errors](/docs/reference/errors); the common
ones are below.
## Settings and keys [#settings-and-keys]
| Symptom | Cause and fix |
| --- | --- |
| `ClipMuxConfigError` naming a variable | That setting is missing where your server runs. Run `init`, or set the variable in your host's settings. On Cloudflare Workers, pass `clipmux: new ClipMux({ env })`. |
| `401 unauthorized` | The API key is wrong or revoked. Run `doctor`. |
| `403 insufficient_scope` | The key lacks the scope the call needs. Create a key with the default scopes (`uploads:write`, `assets:read`, `assets:write`), or with `analytics:read` for analytics. |
| `500 clipmux_misconfigured` in the browser | The handler's key or app is wrong. Your server logged the cause; run `doctor` there. |
| `502 clipmux_unavailable` in the browser | ClipMux couldn't be reached, or failed. The elements retry by themselves. |
| `429 rate_limited` | Too many requests. Wait `Retry-After` seconds; the SDK already did, and retried. |
| `409 public_url_required` when making a key | The server's public URL is still `localhost`. The owner sets it in the dashboard first. |
## Uploads [#uploads]
| Symptom | Cause and fix |
| --- | --- |
| The uploader fails at once with `create_denied` | Your `upload` callback returned `null`, or your route answered `401` or `403`. |
| `413 too_large` | The file is larger than the server or its storage allows. |
| Parts fail with a CORS or CSP error in the console | Your page's `connect-src` doesn't allow the storage origin. Add the origins `doctor` prints. |
| `upload_not_active` | The idempotency key belongs to an upload that has finished. Create the upload with a new key. |
| The video stays `waiting_upload` | The browser never finished sending. An idle upload stays open for 24 hours; after that, delete the video. |
| `ERR_PNPM_…` about a minimum release age on install | pnpm 10 refuses packages newer than its `minimumReleaseAge`. Keep the `minimumReleaseAgeExclude` entry `pnpm add` wrote to `pnpm-workspace.yaml`, and commit it. |
## Processing [#processing]
| Symptom | Cause and fix |
| --- | --- |
| `409 asset_not_ready` | The video is still processing. Wait for `video.asset.ready` before the call. |
| `409 job_active` | Another job is changing the video; `job_id` names it. Wait, or pass `supersede: true`. |
| The video ends `errored` | Its `error_code` says why; see [Errors](/docs/reference/errors). |
| A chapters track always ends `errored` with `llm_not_connected` | No LLM is connected for chapters. The owner connects one under **Captions & AI**; then ask again for existing videos with `tracks.create(id, { kind: 'chapters' })`. Until then, show nothing rather than an error. |
| `409 chapters_not_connected` | The same, refused up front. |
| `409 subtitles_not_ready` | Chapters need ready subtitles. Ask for subtitles first. |
## Webhooks [#webhooks]
| Symptom | Cause and fix |
| --- | --- |
| `bad_signature` | The secret is wrong, or the body was parsed and re-serialized before it was checked. In Express, mount the route before `express.json()`. |
| `stale` | Your server's clock is more than 5 minutes off. Fix its time sync. |
| `missing_header` | Something in front of your app stripped the `X-Webhook-*` headers, or the request isn't from ClipMux. |
| Nothing arrives in development | The server can't reach your laptop. Run [listen](/docs/build/webhooks/listen). |
| Nothing arrives in production | Open **Deliveries** on the endpoint in the dashboard. Each try shows its HTTP status, or `timeout` (your handler took over 10 seconds) or `connection_failed`. |
| The endpoint shows **Paused after N failures** | It failed 5 times in a row, so ClipMux is backing off. Fix the handler; it catches up. See [Retries](/docs/build/webhooks/retries). |
| `doctor` warns the secret is a local one | `CLIPMUX_WEBHOOK_SECRET` is the `whsec_local_…` that `init` writes for `listen`. In production, use your registered endpoint's secret. |
## Playback [#playback]
| Symptom | Cause and fix |
| --- | --- |
| `401 token_expired` | Normal. The player gets a new token by itself. In another player, sign a new one. |
| `403 denied` from delivery | The token is malformed, for another playback ID, or signed with another app's key or a revoked one. Check `CLIPMUX_SIGNING_KID` with `doctor`. An expired token is `401`, not `403`. |
| `clipmux-denied` fires | Your `playback` callback returned `null`, your session route answered `401` or `403`, or delivery answered `403`. Show your sign-in or enrol state. |
| `clipmux-error` with `status: 404` | The playback ID was revoked or never existed, or the video isn't ready. Show that the video was removed. |
| `clipmux-error` with `status: 0` | A network or media error. Check the browser console. |
| Playback stops after about 15 minutes on older iPhones | Safari before 17.1 plays HLS itself and can't renew tokens. Pass `native` through to `playback.token` or `playback.session`, so the token outlives the session. |
| Requests blocked with a Content-Security-Policy error | Add the media origin to `connect-src`, `media-src` (with `blob:`) and `img-src`, and `'unsafe-inline'` to `style-src`. `doctor` prints them. |
| The player is unstyled or blank | The element never loaded: import `@clipmux/player/element` in the browser. In React, import it inside `useEffect`. |
| TypeScript errors inside Video.js's types | Keep `"skipLibCheck": true` in `tsconfig.json`. |
| No subtitles in the captions menu | The subtitles track isn't `ready` yet, or wasn't asked for. See [Subtitles and transcripts](/docs/build/captions/subtitles). |
| No chapters on the time slider | With `getToken`, set `chapters-track` to the ready chapters track's ID. With `session-url`, the session must list the track: pass the asset in your `playback` callback's answer. |
## Still stuck [#still-stuck]
Collect the failing request's method, path, status and error `code`, the
output of `doctor` (it prints no secrets), and your SDK versions, and open
an issue on [GitHub](https://github.com/visheshgubrani/clipmux/issues).
Leave tokens, keys and signed URLs out.
## Next [#next]
- [Errors](/docs/reference/errors)
- [Production checklist](/docs/build/going-live/production-checklist)
- [Server troubleshooting](/docs/self-host/operate/troubleshooting), for the
server's owner
---
# Self-host ClipMux
Install ClipMux on your own server, then connect storage, encoding and delivery.
Source: https://clipmux.com/docs/self-host
ClipMux runs as three containers on one Linux server: the app (one Go
binary with its built-in encoder), Postgres, and Caddy for TLS. Out of the
box it stores videos on the server's disk, encodes them on the server's GPU
or CPU, and serves playback itself. Each of those can move later, to a
bucket, a rented GPU or Cloudflare's edge, without changing the API your
apps call.
You need a Linux server (amd64 or arm64) with Docker and Compose v2, ports 80
and 443 free, and two DNS names pointing at it: one for the dashboard and API,
one for media. Then run:
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh
```
The installer puts ClipMux, Postgres and Caddy in `/opt/clipmux`, generates
the database password and the secrets key, starts the stack, and prints the
address and a setup token. Run the same command again to upgrade in place;
the data, keys and sessions are kept.
ClipMux runs as one server process. It doesn't run as several replicas
behind a load balancer.
## Get started [#get-started]
The server, disk, memory and DNS names you need.
What the installer checks, downloads and writes.
Create the owner, set the URLs, and run the setup test.
## Configure [#configure]
This server's disk, an S3-compatible bucket, or R2.
This server, Modal, RunPod, or a PC you own.
Serve playback from this server or from Cloudflare's edge.
Subtitles with whisper.cpp or a speech API, chapters from an LLM.
## Operate [#operate]
Postgres, the secrets key and the media, together.
Metrics, logs and health checks.
Move to a new release, or remove ClipMux.
What to check before real viewers arrive.
## Next [#next]
- [Requirements and sizing](/docs/self-host/requirements)
- [Install with one line](/docs/self-host/install)
- [A tour of the dashboard](/docs/self-host/dashboard)
---
# Requirements and sizing
The server, disk, memory and DNS names ClipMux needs, and how to size them for your library.
Source: https://clipmux.com/docs/self-host/requirements
ClipMux runs on one Linux server with Docker. This page lists what that
server needs before you install, what the installer checks for you, and how
to size the disk and memory for the videos you expect.
## The server [#the-server]
| Need | Why |
| --- | --- |
| Linux on amd64 or arm64 | The images are built for those two architectures. The installer refuses any other. |
| Docker with the Compose v2 plugin (`docker compose`) | The stack is a Compose project. Run the installer as root, or as a user in the `docker` group. |
| Ports 80 and 443 free | The bundled Caddy serves HTTP and HTTPS on them, and gets a certificate for each of your hostnames. If another proxy already owns them, see [Behind your own reverse proxy](/docs/self-host/install-options/reverse-proxy). |
| A kernel with Landlock (5.13 or later, enabled in the kernel's LSM list) | The built-in encoder confines ffmpeg with Landlock and seccomp. Without Landlock it doesn't start, and uploads wait in `processing` until another encoder takes them. |
Most current distributions' kernels have Landlock on. If yours doesn't, you
can still run ClipMux and encode on [Modal](/docs/self-host/encoding/modal),
[RunPod](/docs/self-host/encoding/runpod) or a
[PC you own](/docs/self-host/encoding/your-pc).
## Two DNS names [#two-dns-names]
Point two hostnames at the server before you finish setup, for example:
- `video.example.com`, the **public URL**: the dashboard, the API, and where
browsers send uploads when videos are stored on this server.
- `media.example.com`, the **media URL**: where viewers' players fetch
video.
Put the media hostname on a different registrable domain from the public
URL if you can (`example-media.com` rather than `media.example.com`), so a
hostile stored file can never reach the dashboard's cookies. You can leave
the media URL blank to serve playback from the public URL, but that is for
trying ClipMux out, not for production.
If you'll encode on Modal or RunPod, the public URL must be reachable from
the internet: their machines call your server for each job.
## What the installer checks [#what-the-installer-checks]
Before it downloads anything, the installer checks:
- that `docker compose` works and Docker answers;
- the machine's architecture;
- free disk space, in the install directory and in Docker's own directory
(usually `/var/lib/docker`): it stops below **4 GiB**, and warns below
**20 GiB**;
- on a first install, that ports 80 and 443 (or the ports you chose) are
free, when `ss` is there to ask.
## Disk [#disk]
Everything ClipMux keeps on the server lives in Docker volumes: Postgres,
and the data volume, which holds videos stored on this server and the
encoder's scratch space. Plan for three things:
- **The originals.** ClipMux keeps every upload as it arrived, so it can
encode it again.
- **The encoded files.** The renditions' video bitrates add up to about
10.3 Mbit/s for a 1080p source and 38 Mbit/s for a 4K one, and real files
come in under that. Measured on lectures: 67 minutes of 1080p made 5.2 GB
of encoded files, and 54 minutes of 4K made 5.9 GB.
- **Room to encode.** An encode needs about three times the source's size
free in the encoder's scratch space while it runs.
If you store videos in a bucket instead, only the scratch space stays on
the server. See [Where videos are stored](/docs/self-host/storage).
## CPU or GPU [#cpu-or-gpu]
The built-in encoder uses the server's GPU when Docker gives the container
one: NVIDIA through NVENC, AMD and Intel through VAAPI. Otherwise it encodes
on the CPU with libx264. Encoding runs at idle priority, so the API and
playback stay responsive while it works, but a CPU encode of a long or 4K
video takes a long time. Each media tool is limited to 8 GiB of memory by
default (`CLIPMUX_TOOL_MEMORY_MB`).
A small VPS can hand encoding to a cloud GPU or a PC instead. See
[Encode on this server](/docs/self-host/encoding/this-server) for passing a
GPU into the container, and
[Encoding performance](/docs/self-host/encoding/performance) for measured
times.
## Memory for subtitles [#memory-for-subtitles]
Subtitles come from whisper.cpp, which runs inside the encoder. Its model
(large-v3-turbo, quantised) is about 0.9 GB and is already in the image, so
nothing is downloaded. With `CLIPMUX_SPEECH` left at `auto`, the encoder
transcribes on a GPU when one passes its test, and otherwise on the CPU only
when the machine has at least 4 cores and 6 GiB of memory. On a smaller
server, subtitles need a
[speech API](/docs/self-host/captions-and-ai/speech-apis) or another
encoder.
## One server process [#one-server-process]
ClipMux supports one `serve` process. Rate limits, sign-in limits, the setup
token and several caches live in that process's memory, so a second replica
behind a load balancer would not share them. To grow, move work off the
server: storage to a bucket, encoding to a cloud GPU, playback to
Cloudflare.
## Control-plane capacity [#control-plane-capacity]
The capacity test ramps from 10 to 200 API reads per second, with one
multipart upload per second. It measures an asset lookup, a 100-asset
catch-up page, an app lookup and the upload create, sign and complete calls.
A simulated encoder claims each job and reports a terminal result. The
webhook goes to a receiver on the same host. The claim measurement starts
when the job is queued. The webhook measurement starts when the event is
written.
For this workload, the sizing objectives are 99.9% successful API requests,
API p95 under 200 ms on each route, enqueue-to-claim p95 under 2 seconds
with an available worker, and event-to-webhook p95 under 10 seconds with a
healthy receiver. Remote worker wake-up, encoding time and internet latency
add to the time an integration sees. Use the
[monitoring recording rules](/docs/self-host/operate/monitoring) to track
your own API response times and server errors.
The November 2026 run used a shared 2-vCPU ARM64 VM and PostgreSQL 18.6.
ClipMux, Postgres and the load generator had 4 GiB of memory limits
combined. Each column shows **p50 / p95 in milliseconds** over one minute.
| Operation | 10 reads/s | 50 reads/s | 100 reads/s | 200 reads/s |
| --- | ---: | ---: | ---: | ---: |
| List 100 assets | 4.9 / 18.2 | 4.8 / 17.4 | 4.6 / 34.4 | 5.2 / 255.5 |
| Read an asset | 3.2 / 9.3 | 2.8 / 11.1 | 2.7 / 25.4 | 3.3 / 236.2 |
| Read app details | 2.8 / 10.8 | 2.5 / 8.0 | 2.5 / 20.1 | 2.6 / 229.9 |
| Create an upload | 7.8 / 22.2 | 7.9 / 26.2 | 7.8 / 34.6 | 11.9 / 197.5 |
| Sign upload parts | 2.7 / 10.4 | 2.6 / 11.2 | 3.2 / 12.4 | 5.8 / 132.6 |
| Complete an upload | 5.5 / 19.2 | 5.7 / 23.4 | 7.8 / 37.5 | 11.7 / 118.4 |
| Enqueue to claim | 401 / 986 | 402 / 968 | 468 / 972 | 448 / 991 |
| Event to webhook delivery | 2,373 / 4,516 | 2,551 / 4,642 | 2,481 / 4,810 | 2,446 / 4,559 |
The run met all four objectives through 100 reads/s plus one upload/s.
At 200 reads/s, the three read routes exceeded the p95 objective and the
load generator dropped 187 of 12,000 scheduled reads. Every read that
reached ClipMux succeeded in this run.
With R2 storage, a 1 GiB upload takes 32 part PUTs of 32 MiB each. R2
receives all 1 GiB directly from the uploader. On a successful upload with
one signing batch, ClipMux handles three API calls to create the upload,
sign the parts and complete it. With Cloudflare Worker delivery and a
video whose encoded files are in R2, 100 viewers averaging 5 Mbit/s each
receive about 500 Mbit/s from Cloudflare. The ClipMux origin serves zero
of those media bytes. Budget origin bandwidth separately for files still
served through origin fallback.
## Next [#next]
- [Install with one line](/docs/self-host/install)
- [Where videos are stored](/docs/self-host/storage)
- [Encode on this server](/docs/self-host/encoding/this-server)
---
# Install with one line
Run the installer to start ClipMux, Postgres and Caddy on your server, and get the setup token.
Source: https://clipmux.com/docs/self-host/install
One command installs ClipMux from the latest release. When it finishes, the
app, Postgres and Caddy are running under Docker in `/opt/clipmux`, and the
installer prints the address to open and the setup token that creates the
owner account.
## Before you start [#before-you-start]
- A server that meets the [requirements](/docs/self-host/requirements):
Linux on amd64 or arm64, Docker with Compose v2, ports 80 and 443 free.
- Root, or a user in the `docker` group.
- Two DNS names pointing at the server, for example `video.example.com` and
`media.example.com`. You can install before DNS is ready, but you need
both names to finish [first run](/docs/self-host/first-run).
## Run the installer [#run-the-installer]
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh
```
`https://clipmux.com/install.sh` redirects to `install.sh` on the latest
GitHub release (until v1.0.0, the newest release candidate). The script then:
1. Checks Docker, Compose, the architecture, free disk space and, on a first
install, that ports 80 and 443 are free.
2. Downloads the release's `SHA256SUMS`, `compose.yml` and `Caddyfile`, and
checks both files against `SHA256SUMS`. It never runs anything it
downloads.
3. Writes `.env` with a random Postgres password and a new secrets key,
readable only by root.
4. Pulls the images and starts the stack, waiting up to 10 minutes for it to
become healthy. Pulling takes a few minutes the first time.
5. Reads the setup token from the app's log and prints it.
## What lands in /opt/clipmux [#what-lands-in-optclipmux]
- **`.env`** holds `CLIPMUX_VERSION` (the release), `POSTGRES_PASSWORD` and
`CLIPMUX_SECRETS_KEY`, which seals every secret ClipMux keeps in Postgres.
It also has commented-out `CLIPMUX_PUBLIC_URL` and `CLIPMUX_MEDIA_URL`
lines, for pinning the URLs instead of choosing them in the dashboard.
Keep this file.
- **`compose.yml`** runs three services: `app` (ClipMux), `postgres` and
`caddy`. The app is published only on `127.0.0.1:8080`, for commands on
the host; everything else reaches it through Caddy.
- **`Caddyfile`** names no hostnames. Caddy asks ClipMux before it gets a
certificate, and ClipMux approves only the public and media URLs you set.
Your videos, Postgres and Caddy's certificates live in Docker volumes
(`data`, `pgdata`, `caddy-data`), not in this folder.
## What it prints [#what-it-prints]
```text
ClipMux v1.0.0 is running.
Open: http://203.0.113.10
http://10.0.0.5 from the server's own network
Ports 80 and 443 must be open to it: check the cloud firewall
or security group, if there is one.
Setup token: N4V3…
Secrets key: v1:…
Store this off the host, with your database backups.
```
- **Open** is first the address the internet sees the server at, which the
installer asks clipmux.com's CDN for (`https://clipmux.com/cdn-cgi/trace`,
the host the script came from), then the server's own address, when the
two differ. On a cloud VM or behind NAT the own address is private, so
open the first. A home server whose router doesn't forward ports 80 and
443 is reached at the second from its own network. If the lookup fails,
the installer prints the own address and says when it is private. Your
DNS names work as well once they point at the server.
- **Setup token** creates the owner account. It works for a day; restarting
the app prints a new one. If the installer couldn't find it, run
`cd /opt/clipmux && sudo docker compose logs app | grep setup_token`.
- **Secrets key** is also in `.env`. Copy it somewhere off the server now.
Without it, a database backup can't be restored: every stored secret and
every encoded video becomes unusable.
## Options [#options]
Pass options to the script after `sh -s --`:
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --version v1.0.0
```
| Option | What it does |
| --- | --- |
| `--version vX.Y.Z` | Installs that release instead of the latest. |
| `--dir DIR` | Installs in `DIR` instead of `/opt/clipmux`. Pass the same `--dir` when you upgrade or uninstall. |
| `--restore` | On a new server: restores the latest backup from the target your saved `.env` names, then starts ClipMux. Put the `.env` in the install directory first. See [Back up and restore](/docs/self-host/operate/backups#restore). |
| `--uninstall` | Stops and removes the stack, keeping the volumes and `.env`. See [Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall). |
| `--purge` | With `--uninstall`, also deletes the volumes and the folder. |
## Installer variables [#installer-variables]
The installer reads these from its environment. Put them after `sudo` so
they reach the script:
```bash
curl -fsSL https://clipmux.com/install.sh | sudo CLIPMUX_ADMIN_PORT=8090 sh
```
| Variable | Default | What it does |
| --- | --- | --- |
| `CLIPMUX_HTTP_PORT` | `80` | The host port for Caddy's HTTP. Saved in `.env` on the first install. |
| `CLIPMUX_HTTPS_PORT` | `443` | The host port for Caddy's HTTPS. Saved in `.env` on the first install. |
| `CLIPMUX_ADMIN_PORT` | `8080` | The loopback port the app is published on, for commands on the host. Saved in `.env` on the first install. |
| `CLIPMUX_IMAGE` | `ghcr.io/visheshgubrani/clipmux` | The image, without its tag, for a mirror. Saved in `.env` when set. |
| `CLIPMUX_RELEASE_URL` | the release on GitHub | Where to download `SHA256SUMS`, `compose.yml` and `Caddyfile` from, for a mirror. |
Caddy's certificates come from Let's Encrypt, which connects to ports 80
and 443 from the internet. Other HTTP and HTTPS ports only work if something
forwards 80 and 443 to them.
## Check it works [#check-it-works]
```bash
curl -fsS http://127.0.0.1:8080/readyz
```
It prints `ok` once the app is up and Postgres answers (use your
`CLIPMUX_ADMIN_PORT` if you changed it). Then open the
printed address in a browser: the page asks for the setup token.
If the installer stopped instead:
- **`port 80 is in use`**: another web server owns the port. Stop it, or
follow [Behind your own reverse proxy](/docs/self-host/install-options/reverse-proxy).
- **`only N GiB free under …`**: free disk space; ClipMux needs at least
4 GiB.
- **`can't reach Docker`**: run it with `sudo`, or as a user in the `docker`
group.
- **`ClipMux didn't become healthy`**: the app's last 50 log lines are
printed above the error. The last line says why, for example a
variable that doesn't parse.
## Next [#next]
- [First run](/docs/self-host/first-run): create the owner, set the URLs,
run the setup test
- [Requirements and sizing](/docs/self-host/requirements)
- [Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall)
---
# First run
Create the owner account, set the public and media URLs, turn on two-factor sign-in, and run the setup test.
Source: https://clipmux.com/docs/self-host/first-run
A fresh install already works: it stores videos on the server's disk,
encodes them with the built-in encoder and serves playback itself. First
run gives it an owner and its addresses, and proves the whole path with a
sample video. It takes a few minutes.
## Before you start [#before-you-start]
- ClipMux installed and running. See [Install with one line](/docs/self-host/install).
- The setup token the installer printed.
- Your two DNS names, for example `video.example.com` and
`media.example.com`, pointing at the server.
## Set up the instance [#set-up-the-instance]
### Create the owner account [#create-the-owner-account]
Open the address the installer printed (`http://` and the server's address).
The page asks for:
- **Setup token**: the token from the installer. It lasts a day. If it has
run out, or you lost it, find the current one with
`cd /opt/clipmux && sudo docker compose logs app | grep setup_token`.
- **Email** and **Password**: at least 12 characters.
An instance has one owner. Once the account exists, sign-up closes for good,
and later visitors see only the sign-in page.
### Set the public and media URLs [#set-the-public-and-media-urls]
The next page, **Where will people reach ClipMux?**, asks for two URLs:
- **Public URL**: where browsers and apps reach the dashboard and the API,
for example `https://video.example.com`.
- **Media URL**: where videos play from, for example
`https://media.example.com`. Leave it blank to use the public URL.
Write both with `https://`. Caddy gets a certificate for each hostname the
first time someone visits it, so open `https://video.example.com` once
you've saved, and sign in there.
You can keep `localhost` to try things out, but while the public URL is
loopback, apps can't get API keys: upload URLs and playback URLs would point
at this machine. You can change both URLs later under **Settings**. If
`CLIPMUX_PUBLIC_URL` is set in `.env`, the fields are read-only and show the
pinned values.
### Turn on two-factor sign-in [#turn-on-two-factor-sign-in]
In **Settings**, open the **Account** tab and find **Two-factor sign-in**.
Enter your password and choose **Set up two-factor sign-in**, add the key it
shows to any authenticator app, then enter the code the app shows and choose
**Turn on**.
ClipMux then shows ten recovery codes, once. Each signs you in once if you
lose the authenticator. Keep them offline.
### Run the setup test [#run-the-setup-test]
In **Settings**, on the **General** tab, choose **Run the setup test**. A
sample video goes through upload, encoding, encryption and playback, and the
page shows each check as it passes. The test then checks that:
- a playback token plays the video and fetches its key;
- a poster-only token can't fetch a segment or the key;
- a request with no token is refused;
- a segment read straight from storage is encrypted, not a plain video
file.
When every check passes, the sample plays on the page. The setup test runs
only when you ask, and on its own after you connect or disconnect
Cloudflare and when you connect a cloud GPU. From the server you can run the
same test with:
```bash
cd /opt/clipmux && sudo docker compose exec app clipmux admin setup-test --wait
```
## Check it works [#check-it-works]
- **Settings** shows **All N checks passed** under **Setup test**.
- `https://video.example.com` opens the dashboard with a valid certificate.
If the browser shows a certificate error, the hostname's DNS doesn't point
at this server yet, or ports 80 and 443 aren't reachable from the
internet.
- **Home** shows **Finish setting up**, with the optional steps below.
If a check fails, its line says which step and why. The setup test sends
its sample to the encoder that takes new videos, so a failure in
**encode** points at [encoding](/docs/self-host/encoding/this-server), and a
failure in playback at [delivery](/docs/self-host/delivery/built-in).
If you get locked out:
- **Lost the authenticator and the recovery codes:**
`cd /opt/clipmux && sudo docker compose exec app clipmux admin reset-totp`
turns off two-factor sign-in.
- **Forgot the password:** put the new password on one line in a file, then
run `sudo docker compose exec -T app clipmux admin reset-password < new-password.txt`
from `/opt/clipmux`. It also signs out every browser.
## What to do next [#what-to-do-next]
**Home** lists the optional steps in **Finish setting up**:
- **Store uploads in a bucket**: R2 or any S3-compatible store, instead of
this server's disk. See [Where videos are stored](/docs/self-host/storage).
- **Connect Cloudflare**: serve playback from Cloudflare's edge. See
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare).
- **Add a cloud GPU**: Modal or RunPod, with a monthly spend limit. See
[Encode on Modal](/docs/self-host/encoding/modal).
- **Turn on chapters**: connect an LLM. See
[Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm).
- **Create an app**: credentials for your own site. See the
[Quickstart](/docs/build/quickstart).
## Next [#next]
- [A tour of the dashboard](/docs/self-host/dashboard)
- [Back up and restore](/docs/self-host/operate/backups): copy the secrets
key off the server first
- [Quickstart](/docs/build/quickstart)
---
# A tour of the dashboard
What each page of the ClipMux dashboard shows and what you can do there.
Source: https://clipmux.com/docs/self-host/dashboard
The dashboard is where the owner runs the instance: videos, encoding,
storage, delivery, captions and the apps that use the API. It is an API
client like any other, with no private path into the server, so everything
it does can also be done through the
[management API](/docs/reference/management-api). It works in light and dark
themes, on a laptop or a phone.
The sidebar has two groups: **Home**, **Videos**, **Analytics** and
**Jobs**, then **Encoding**, **Storage**, **Delivery**, **Captions & AI**
and **Apps & API**, with **Settings** at the bottom. The menu under your
email holds the theme switch, **Settings** and **Sign out**.
## Home [#home]
A summary line and an **Upload** button, then:
- **Finish setting up**: the optional steps left (store uploads in a
bucket, connect Cloudflare, add a cloud GPU, turn on chapters, create an
app), until they're done or you hide them.
- **Needs attention**: videos that failed or are still encoding, with what
to do.
- **Recent videos**, and a status line for encoding, delivery, uploads and
captions, each linking to its page.
## Videos [#videos]

Every video, as a poster grid or a list. Search by title, reference or ID,
filter by status (**All**, **Ready**, **Encoding**, **Failed**) and, when
there's more than one, by app. Drop files anywhere on the page to upload
them.
## A video [#a-video]

Opening a video shows four tabs:
- **Overview**: the player, a chapter strip under it when the video has
chapters, and the details (duration, privacy, app, resolutions, captions,
ID and reference).
- **Captions & chapters**: the subtitles and chapters as timed rows, to
generate again or delete.
- **Sharing**: who can watch (signed or public), share links, and playback
IDs. A public video shows its stream URL and a ``
snippet.
- **Analytics**: views, watch time and other metrics for this video.
From the video's header you can rename it, re-encode it (with a choice of
resolutions) or delete it.
## Upload [#upload]
Choose or drop several files at once. Each shows its progress, can be
paused or cancelled, and resumes after a reload. Before uploading you choose
who can watch, whether to generate subtitles and chapters, which
resolutions to encode, and, under advanced options, the app and a
reference of your own. Chapters need an LLM connected under
**Captions & AI**.
## Analytics [#analytics]
Views, watch time, unique viewers and bandwidth for the last 24 hours, 7,
30 or 90 days, compared with the period before, and the top videos. Filter
by app. See [Views, watch time and unique viewers](/docs/build/analytics)
for what counts.
## Jobs [#jobs]
Every job: encodes, re-encodes, imports, subtitles, chapters, moves and
deletes, filtered by status and kind. A row opens into its attempts: where
each ran, why it was routed there, which encoder each output used and any
that failed, and the error.
## Encoding [#encoding]

Where new videos are encoded: **This server**, **Modal** or **RunPod**.
Connect a cloud GPU here, see its spend this month against its limit, and
choose whether this server takes over when the cloud GPU can't. See
[Encode on this server](/docs/self-host/encoding/this-server) and
[Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits).
## Storage [#storage]
Where uploaded originals are kept: this server's disk, R2 buckets and
S3-compatible stores, with how many videos each holds and which is the
default. Add a bucket, rotate an S3 store's keys, remove one no video uses,
and move existing uploads to the default. See
[Where videos are stored](/docs/self-host/storage).
## Delivery [#delivery]
How viewers get videos: from this server, or from Cloudflare's edge with
encoded files in R2. Connect or disconnect Cloudflare, move existing
encoded files to R2, and connect edge analytics. See
[Built-in delivery](/docs/self-host/delivery/built-in) and
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare).
## Captions & AI [#captions--ai]

Where subtitles are made, on machines you run or by a speech API you
connect, each choice saying what leaves your servers; and the LLM that
titles chapters. See
[Transcribe with whisper.cpp](/docs/self-host/captions-and-ai/whisper),
[Use a speech API](/docs/self-host/captions-and-ai/speech-apis) and
[Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm).
## Apps & API [#apps--api]

One app per site or service that uses ClipMux. **Create app** shows its
secrets once. Each app has tabs for **API keys**, **Signing keys**,
**Webhooks** (with each endpoint's health and deliveries, redelivery, and
secret rotation) and a **Danger zone** to disable it. See the
[Quickstart](/docs/build/quickstart).
## Settings [#settings]
- **General**: the public and media URLs, and the setup test.
- **Account**: your password and two-factor sign-in.
- **Security**: rotating the content key, and a reminder about backups.
- **About**: the licences. Run `clipmux version` on the server for the
release.
## Next [#next]
- [First run](/docs/self-host/first-run)
- [Where videos are stored](/docs/self-host/storage)
- [Management API](/docs/reference/management-api)
---
# Install from source with Compose
Build the ClipMux image from a clone of the repository and run it with Docker Compose.
Source: https://clipmux.com/docs/self-host/install-options/compose-from-source
The one-line installer runs a published release. To run a commit of your
own, or to change the code, build the image from a clone instead. You get
the same stack: the app, Postgres and Caddy, defined in
`deploy/compose.yml`.
## Before you start [#before-you-start]
- A server that meets the [requirements](/docs/self-host/requirements),
with `git` and `openssl`.
- Ports 80 and 443 free, or see
[Behind your own reverse proxy](/docs/self-host/install-options/reverse-proxy).
## Build and start [#build-and-start]
### Clone the repository [#clone-the-repository]
```bash
git clone https://github.com/visheshgubrani/clipmux && cd clipmux
```
### Write deploy/.env [#write-deployenv]
```bash
cp deploy/compose.env.example deploy/.env
```
Fill in the two required values:
- `POSTGRES_PASSWORD`: any long random string, for example from
`openssl rand -hex 24`.
- `CLIPMUX_SECRETS_KEY`: `v1:` and 64 hex digits. Generate it once:
```bash
echo "v1:$(openssl rand -hex 32)"
```
The file also has commented-out lines for `CLIPMUX_PUBLIC_URL` and
`CLIPMUX_MEDIA_URL` (to pin the URLs instead of choosing them in the
dashboard) and the host ports
`CLIPMUX_HTTP_PORT`, `CLIPMUX_HTTPS_PORT` and `CLIPMUX_ADMIN_PORT`.
Never commit `deploy/.env`.
Copy the secrets key somewhere off the server as well. Without it, a
database backup can't be restored: every stored secret and every encoded
video becomes unusable.
### Build and start the stack [#build-and-start-the-stack]
```bash
docker compose -f deploy/compose.yml up -d --build --wait
```
This builds the image, with FFmpeg, Shaka Packager and whisper.cpp, which
takes a while the first time. Postgres starts first, then the app, then
Caddy.
### Get the setup token [#get-the-setup-token]
```bash
docker compose -f deploy/compose.yml logs app | grep setup_token
```
Open `http://` and the server's address, and continue with
[First run](/docs/self-host/first-run).
## How it differs from the installer [#how-it-differs-from-the-installer]
- The image is built from your checkout and tagged `clipmux:local`, rather
than pulled from the registry.
- Settings live in `deploy/.env`, not `/opt/clipmux/.env`, and every
`docker compose` command needs `-f deploy/compose.yml`.
- Cloud GPUs on Modal and RunPod can't run your local image. A local build
names no worker image for them, so when you connect one, enter an image
they can pull under **Advanced**, **Worker image**.
- You upgrade with git, not the installer:
```bash
git pull
docker compose -f deploy/compose.yml up -d --build --wait
```
The app applies new database migrations when it starts. See
[Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall).
## Check it works [#check-it-works]
```bash
docker compose -f deploy/compose.yml ps
curl -fsS http://127.0.0.1:8080/readyz
```
All three services show `healthy`, and `readyz` prints `ok`.
- **Compose refuses to start** with `set POSTGRES_PASSWORD in deploy/.env`
or `set CLIPMUX_SECRETS_KEY in deploy/.env`: that value is empty.
- **The app keeps restarting**: `docker compose -f deploy/compose.yml logs app`
ends with the reason, for example a variable that doesn't parse.
## Next [#next]
- [First run](/docs/self-host/first-run)
- [Behind your own reverse proxy](/docs/self-host/install-options/reverse-proxy)
- [Environment variables](/docs/reference/configuration)
---
# Behind your own reverse proxy
Run ClipMux without its bundled Caddy, behind a Caddy, nginx or Traefik you already run on ports 80 and 443.
Source: https://clipmux.com/docs/self-host/install-options/reverse-proxy
If another proxy already owns ports 80 and 443 on the server, for example a
Caddy or nginx serving other sites, run ClipMux without its own Caddy and
point your proxy at it. `deploy/compose.proxy.yml` does this: it leaves the
bundled Caddy out and has the setup test reach your public URLs through
your proxy. Your proxy then terminates TLS for both of ClipMux's hostnames.
## Before you start [#before-you-start]
- A server that meets the [requirements](/docs/self-host/requirements), with
a reverse proxy already serving ports 80 and 443.
- Two DNS names pointing at it, for example `video.example.com` and
`media.example.com`, and certificates for both from your proxy.
- `openssl` and `sha256sum` on the server.
Don't use the one-line installer on this server. It starts the bundled
Caddy on ports 80 and 443: a first install stops because the ports are in
use, and an upgrade with it fails to start.
## Start ClipMux without Caddy [#start-clipmux-without-caddy]
As root, download a release's `compose.yml` and check it, then fetch
`compose.proxy.yml` from the same tag. Set `V` to the release you want:
```bash
mkdir -p /opt/clipmux && cd /opt/clipmux
V=v1.0.0
curl -fsSL -O "https://github.com/visheshgubrani/clipmux/releases/download/$V/SHA256SUMS" \
-O "https://github.com/visheshgubrani/clipmux/releases/download/$V/compose.yml"
sha256sum --check --ignore-missing SHA256SUMS
curl -fsSL -o compose.proxy.yml "https://raw.githubusercontent.com/visheshgubrani/clipmux/$V/deploy/compose.proxy.yml"
```
Write `.env`, readable only by root:
```bash
umask 077
cat > .env <
From a clone with `deploy/.env` written as in
[Install from source with Compose](/docs/self-host/install-options/compose-from-source):
```bash
docker compose -f deploy/compose.yml -f deploy/compose.proxy.yml up -d --build --wait
docker compose -f deploy/compose.yml -f deploy/compose.proxy.yml logs app | grep setup_token
```
Copy `CLIPMUX_SECRETS_KEY` from `.env` somewhere off the server. Without
it, a database backup can't be restored.
The app now listens on `127.0.0.1:8080`, and only there. If 8080 is taken,
set `CLIPMUX_ADMIN_PORT` in `.env` to another port and run the `up`
command again.
## What your proxy must do [#what-your-proxy-must-do]
- **Serve both hostnames.** Forward the public and the media hostname to
`127.0.0.1:8080`, with TLS for each.
- **Keep the `Host` header.** ClipMux compares it with the public and media
URLs to decide where to redirect and when to send HSTS.
- **Send `X-Forwarded-For` and `X-Forwarded-Proto`.** ClipMux believes them
only from `CLIPMUX_TRUSTED_PROXIES`, which compose sets to Docker's private
ranges: that is where a proxy on the host connects from. Rate limits and
sign-in limits use the client address, and when the public URL is
`https`, a request that says it came over `http` is redirected to `https`.
A proxy that sends `X-Forwarded-Proto: http` for HTTPS traffic causes a
redirect loop.
- **Allow large request bodies.** With videos stored on this server,
browsers upload 32 MiB parts through `/_storage/` on the public hostname,
and encoders upload their output there too.
- **Allow slow responses.** Connecting a cloud GPU or Cloudflare, and the
setup test, can take up to 5 minutes to answer; encoders hold requests
open for up to 45 seconds while they wait for work.
- **Hide `/_tls/`.** `/_tls/ask` tells the bundled Caddy which hostnames may
get a certificate. The bundled config answers `404` to it from outside;
do the same.
ClipMux uses no WebSockets.
Keep the public hostname off any CDN proxy that challenges API clients,
such as Cloudflare's Browser Integrity Check: it refuses `@clipmux/node`,
the CLI and encoders, and hides the client's address. Point its DNS
straight at the server ("DNS only" on Cloudflare). Playback goes through the
media hostname, which can be served by
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare) later.
The setup test fetches your public and media URLs from inside the app
container, through your proxy, so the server must be able to reach its own
hostnames.
## Example configurations [#example-configurations]
```txt title="Caddyfile"
video.example.com, media.example.com {
respond /_tls/* 404
reverse_proxy 127.0.0.1:8080
}
```
Caddy keeps the `Host` header, sets `X-Forwarded-For` and
`X-Forwarded-Proto`, and limits neither body size nor response time by
default. If your Caddy uses on-demand TLS, point its `ask` at
`http://127.0.0.1:8080/_tls/ask`, which approves only the hostnames you set
in ClipMux.
```nginx title="/etc/nginx/conf.d/clipmux.conf"
server {
listen 80;
server_name video.example.com media.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name video.example.com media.example.com;
ssl_certificate /etc/ssl/clipmux/fullchain.pem;
ssl_certificate_key /etc/ssl/clipmux/privkey.pem;
# Upload parts are 32 MiB; ClipMux checks each part's length itself.
client_max_body_size 0;
proxy_request_buffering off;
proxy_buffering off;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
location /_tls/ {
return 404;
}
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
The certificate must cover both hostnames. nginx's defaults would refuse
upload parts (`client_max_body_size` is 1 MB) and cut off the slower
requests after 60 seconds.
## On a small or shared server [#on-a-small-or-shared-server]
Encoding on a server that also runs other services competes with them for
CPU. With `compose.proxy.yml`, set `CLIPMUX_BUILTIN_WORKER=false` in `.env`
and run the `up` command again: the app then runs no encoder of its own.
Connect [Modal](/docs/self-host/encoding/modal),
[RunPod](/docs/self-host/encoding/runpod) or a
[PC you own](/docs/self-host/encoding/your-pc) first, so new videos have
somewhere to encode, and the setup test runs there.
## Upgrade [#upgrade]
Edit `CLIPMUX_VERSION` in `.env`, download that release's `compose.yml` and
`compose.proxy.yml` as above, then pull and restart:
```bash
cd /opt/clipmux
docker compose -f compose.yml -f compose.proxy.yml pull app
docker compose -f compose.yml -f compose.proxy.yml up -d --wait
```
The app applies database migrations when it starts. See
[Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall)
for what changes between releases and how to roll back.
## Restore from a backup [#restore-from-a-backup]
The installer's `--restore` starts Caddy, so on this server run the same steps
by hand. Put the `.env` you saved from the old server in `/opt/clipmux`, with
`compose.yml` and `compose.proxy.yml` as above, then bring Postgres up, restore
in a one-off container while nothing else uses the database, and start the rest:
```bash
cd /opt/clipmux
docker compose -f compose.yml -f compose.proxy.yml up -d --wait postgres
docker compose -f compose.yml -f compose.proxy.yml run --rm -T --no-deps app admin restore --latest --yes
docker compose -f compose.yml -f compose.proxy.yml up -d --wait
docker compose -f compose.yml -f compose.proxy.yml exec app clipmux admin restore report
```
The restore leaves the restore fence up. Read the report, then lift it; see
[Back up and restore](/docs/self-host/operate/backups#restore).
## Check it works [#check-it-works]
```bash
curl -fsS http://127.0.0.1:8080/readyz
curl -fsSI https://video.example.com/readyz
```
The first prints `ok`: the app is up. The second answers `200` through your
proxy once the certificate is in place.
- **`502` or `connection refused` from the proxy**: the app isn't
listening yet, or your proxy points at another port than
`CLIPMUX_ADMIN_PORT`.
- **A redirect loop**: your proxy sends `X-Forwarded-Proto: http` for HTTPS
requests.
- **Uploads stop at the first part**: the proxy's body size limit is below
32 MiB.
- **The setup test fails to reach a URL**: the server can't reach its own
hostnames through the proxy.
## Next [#next]
- [First run](/docs/self-host/first-run)
- [Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall)
- [Security checklist](/docs/self-host/operate/security-checklist)
---
# Upgrade and uninstall
Move ClipMux to a new release, pin or roll back a version, or remove it from the server.
Source: https://clipmux.com/docs/self-host/install-options/upgrade-and-uninstall
An install from the one-line installer upgrades by running the installer
again. Your data, keys, sessions and settings stay where they are: only the
release in `.env` changes, and the app brings the database up to date when
it starts.
## Before you start [#before-you-start]
- An install made with [the one-line installer](/docs/self-host/install).
For other setups, see
[Install from source with Compose](/docs/self-host/install-options/compose-from-source)
and [Behind your own reverse proxy](/docs/self-host/install-options/reverse-proxy).
- A fresh [backup](/docs/self-host/operate/backups) of Postgres, and the
secrets key stored off the server. An upgrade can't be undone past a
database migration without one.
## Upgrade [#upgrade]
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh
```
On a server that already has `/opt/clipmux/.env`, the installer:
1. Downloads the release's `compose.yml` and `Caddyfile` and checks them
against its `SHA256SUMS`, as on a first install.
2. Changes `CLIPMUX_VERSION` in `.env` and leaves every other line alone,
including your ports and any URLs you pinned.
3. Pulls the new image and restarts the stack, waiting for it to become
healthy.
4. Prints `ClipMux upgraded from vA to vB`.
It doesn't check the ports again, and it prints no setup token.
If you installed with `--dir`, pass the same `--dir` again.
### Install a given release [#install-a-given-release]
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --version v1.0.0
```
`--version` installs that release, newer or older than the current one.
Going back to an older release works only if no database migration has run
since; see below.
### What happens at boot [#what-happens-at-boot]
- **Migrations.** The app applies new database migrations when it starts,
holding a lock so two processes never migrate at once. If there are any
to apply, it first backs the database up as it is (a `pre_migrate` backup
on your [backup target](/docs/self-host/operate/backups)), and if that
fails it doesn't migrate and stops with the reason in its log. Set
`CLIPMUX_BACKUP_BEFORE_MIGRATE=false` to migrate without one. The
`clipmux admin` commands do the same. `clipmux admin migrate status` lists
what the database has.
- **A database newer than the app.** An older release refuses to start
against a database a newer one migrated, with `schema_newer` in its log.
Run the newer release, or roll the database back first with it (below).
- **Stopping drains.** When the old container stops, the app stops handing
out jobs, lets the built-in encoder hand its job back, and finishes
requests in flight, within compose's 40-second grace period. Uploads
resume and players retry, so nothing is lost.
- **Cloud GPUs follow.** Unless you set `CLIPMUX_WORKER_IMAGE`, Modal and
RunPod machines run the new release's image from the next job.
- **Cloudflare.** With Cloudflare delivery, the Delivery page says when the
Worker needs redeploying for the new release.
### Roll back past a migration [#roll-back-past-a-migration]
While the newer release is still running, roll the database back to the
older release's newest migration, which `migrate status` showed before you
upgraded:
```bash
cd /opt/clipmux
sudo docker compose exec app clipmux admin migrate down-to VERSION --yes
```
Then install the older release with `--version`. Rolling back can lose
whatever the newer migrations added, which is why the backup comes first.
If the upgrade went wrong and you would rather have the database exactly as it
was, restore the `pre_migrate` backup that was taken just before it with the
older release; see [Restore](/docs/self-host/operate/backups#restore).
## Uninstall [#uninstall]
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --uninstall
```
This stops and removes the containers. The Docker volumes (your videos,
Postgres and Caddy's certificates) and `/opt/clipmux/.env` stay, so running
the installer again brings the same instance back.
### Delete everything [#delete-everything]
`--purge` deletes every video, the database, every key and setting, and
`/opt/clipmux` with the secrets key in it. It can't be undone. Videos you
stored in your own buckets stay in those buckets, but without the
database and the secrets key, the encoded ones can't be played.
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --uninstall --purge
```
## Check it works [#check-it-works]
```bash
cd /opt/clipmux
sudo docker compose exec app clipmux version
sudo docker compose exec app clipmux admin migrate status
```
`clipmux version` names the new release. If the installer stopped with
`ClipMux didn't become healthy`, the app's last log lines are printed above
the error: `schema_newer` means the database is ahead of this release, and a
secrets key that opens nothing means `.env` holds a different key from the
one the database was sealed with.
After `--uninstall`, `docker ps` lists no ClipMux containers, and
`docker volume ls` still lists its volumes until you `--purge`.
## Next [#next]
- [Back up and restore](/docs/self-host/operate/backups)
- [Changelog](/docs/reference/changelog)
- [Troubleshooting](/docs/self-host/operate/troubleshooting)
---
# Where videos are stored
Keep videos on this server's disk, in any S3-compatible bucket, or in Cloudflare R2, and move your library between them.
Source: https://clipmux.com/docs/self-host/storage
Every video has two parts in storage: the **upload**, the original file as
it arrived, which ClipMux keeps so it can encode again; and the **encoded
files**, the encrypted HLS renditions viewers play. A fresh install keeps
both on this server's disk. You can add buckets, choose which one new
uploads go to, and move existing videos there. Apps see none of this: their
API calls and playback URLs stay the same.
## Before you start [#before-you-start]
- An owner account on the dashboard.
- For R2: a Cloudflare account with R2 enabled.
- For any other bucket: an S3-compatible service (AWS S3, or Garage or
SeaweedFS that you run), a bucket, and keys that can read, write, list and
delete in it and set its CORS rules.
## Where each part goes [#where-each-part-goes]
| Part | Where it goes |
| --- | --- |
| Upload | The **default** storage on the Storage page, chosen when the video is created. |
| Encoded files | The default storage too, beside the upload. With [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare) connected, the delivery bucket in R2 instead, so the edge can serve them. |
Each video remembers where its parts are. Changing the default, or
connecting Cloudflare, changes where new videos go; existing videos stay
where they are, and keep playing at the same URLs, until you move them.
## The kinds of storage [#the-kinds-of-storage]
- **This server's disk.** Always there, and the default on a fresh install.
Files live in the app's data volume. Browsers upload to the public URL,
under `/_storage/`, with URLs ClipMux signs for each part.
- **An S3-compatible bucket.** Browsers upload parts straight to the
bucket with presigned URLs, so uploads don't pass through your server.
- **Cloudflare R2.** An S3-compatible bucket that ClipMux sets up from one
Cloudflare token.
With a bucket as storage, the bucket's provider holds the uploads exactly
as they arrived (not encrypted), and, when it is also where encoded files
go, the encoded files, which are AES-128 encrypted. ClipMux never sends
the content keys to the provider.
## Add an R2 bucket [#add-an-r2-bucket]
### Create a token [#create-a-token]
On **Storage**, choose **Add R2 bucket**. The dialog links to Cloudflare's
token page with the permission it needs already chosen: **Workers R2
Storage: Edit**, and nothing else. Create the token and paste it into **API
token**. If it reaches more than one account, choose the **Account**.
### Choose the bucket [#choose-the-bucket]
Pick an existing bucket or name a new one; ClipMux creates it if it doesn't
exist (`clipmux-media` by default). Tick **Use it for new uploads** to make
it the default now.
### Check and add [#check-and-add]
ClipMux derives the bucket's S3 keys from the token, checks them with a test
write, read, list and delete, sets the bucket's CORS rules, and saves it.
Each step's result shows in the dialog.
The keys derive from the token, so keep the token active in Cloudflare:
revoking or rolling it cuts ClipMux off from the bucket. To renew the keys
with a new token, add the same bucket again. This doesn't change how videos
are delivered; for edge delivery, see
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare), which can
reuse the same bucket.
The same call through the API is `POST /v1/storage/r2`. R2 buckets in a
jurisdiction such as the EU need `CLIPMUX_R2_ENDPOINT` set to that
jurisdiction's endpoint.
## Add S3-compatible storage [#add-s3-compatible-storage]
On **Storage**, choose **Add S3 storage** and fill in:
- **Endpoint**: the service's S3 endpoint, for example
`https://s3.eu-central-1.amazonaws.com`.
- **Bucket**, and **Region** if the service needs one.
- **Access key ID** and **Secret access key**.
- **Public endpoint**: only when browsers must reach the bucket at another
address than the one ClipMux uses, for example when ClipMux reaches a
Garage bucket on a private network.
**Check and add** saves it only after a test write, read, list and delete
pass and ClipMux has set the bucket's CORS rules, so browsers on any origin
can upload parts and read the `ETag` of each. The presigned URL is what
authorises an upload, so the rule doesn't check the origin. A new store
isn't the default until you choose **Use for new uploads**.
Through the API, this is `POST /v1/storage`. Keys are sealed with the
secrets key in Postgres and never returned.
## Choose the default [#choose-the-default]
**Use for new uploads** on any store, this server's disk included, makes it
the default (`POST /v1/storage/{id}/default`). New videos go there from then
on. Existing videos stay where they are until you move them.
## Move the library [#move-the-library]
When some videos have a part away from where the settings now put it, the
Storage page says how many keep their upload on another storage, and offers
**Move them to** the default. The Delivery page does the same for encoded
files. Either button moves both parts of every such video:
- the upload goes to the default storage;
- the encoded files go to where encoded files now belong;
- a part already in place is skipped, and the video's playback routes are
published again.
Encrypted files move as they are, and playback URLs don't change, so videos
keep playing during and after the move. Each video is a `move` job: progress
shows on **Jobs**, and a failed move is listed there. Moves run inside the
server, never on an encoder, because they need storage keys.
Through the API, `GET /v1/storage/moves` counts the videos that have a part
elsewhere and the moves running, done and failed, and
`POST /v1/storage/moves` queues a move for each video that needs one and has
no other job running.
## Rotate an S3 store's keys [#rotate-an-s3-stores-keys]
Create new keys at the provider, then choose **Rotate keys** on the store
and paste them (`PUT /v1/storage/{id}/credentials`). ClipMux runs the same
checks with the new keys and keeps the old ones until they pass. Then delete
the old keys at the provider. For an R2 bucket, add the same bucket again
with a new token instead. This server's disk has no keys.
## Remove a store [#remove-a-store]
**Remove** (`DELETE /v1/storage/{id}`) forgets a store and its keys. The
files in the bucket stay where they are. ClipMux refuses to remove:
- this server's disk;
- the default store: choose another default first;
- the Cloudflare delivery bucket: disconnect Cloudflare first;
- a store that still holds any part of a video: move the library first. A
deleted video counts until its files are gone.
## What ClipMux doesn't do [#what-clipmux-doesnt-do]
- It doesn't set a lifecycle rule on your bucket. An upload abandoned
midway can leave its parts in the bucket if aborting it fails; a lifecycle
rule that aborts incomplete multipart uploads after a few days cleans them
up.
- It doesn't copy or replicate a bucket for backup. See
[Back up and restore](/docs/self-host/operate/backups).
## Check it works [#check-it-works]
- The store shows on **Storage** with **Default** next to it, a count
of videos, and the bytes held across sources and encoded outputs (`total_bytes`,
with `source_bytes` and `media_bytes` breakdown in `GET /v1/storage`).
- Upload a short video from **Upload**. It reaches **Ready**, and the
default store's count goes up by one.
- If **Check and add** fails, the failed step says why: usually the
endpoint, the bucket name or the keys, or keys that can't set CORS.
- If uploads to a bucket fail in the browser but the store was added, the
browser can't reach the endpoint: set **Public endpoint**.
## Next [#next]
- [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare)
- [Back up and restore](/docs/self-host/operate/backups)
- [Management API](/docs/reference/management-api)
---
# Encode on this server
Use the built-in encoder on the ClipMux server, with its NVIDIA, AMD or Intel GPU when Docker passes one in.
Source: https://clipmux.com/docs/self-host/encoding/this-server
The ClipMux server encodes videos itself, with no setup. The app starts a
built-in encoder beside the API, which uses the server's GPU when it can see
one and the CPU otherwise. This page covers giving the container a GPU,
choosing the encoder, turning the built-in encoder off, and the sandbox it
runs in.
## Before you start [#before-you-start]
- ClipMux installed with the [one-line installer](/docs/self-host/install)
or [from source](/docs/self-host/install-options/compose-from-source).
- For a GPU: an NVIDIA card with its driver and the NVIDIA Container
Toolkit on the host, or an AMD or Intel GPU with a render node under
`/dev/dri`.
- A kernel with Landlock. See [Requirements](/docs/self-host/requirements).
## How it chooses an encoder [#how-it-chooses-an-encoder]
When the built-in encoder starts, it runs a two-frame test encode on each
GPU path, inside the same sandbox jobs use, and offers only the paths that
pass:
| Path | Hardware | What runs where |
| --- | --- | --- |
| `nvenc` | NVIDIA with NVENC | Decode, scale and encode on the GPU |
| `vaapi` | AMD (Radeon), Intel (iHD driver) | Decode, scale and encode on the GPU |
| `cuda-decode` | NVIDIA without NVENC | Decode on the GPU, encode with libx264 |
| `cpu` | Every machine | libx264 |
A source the GPU can't decode, such as 10-bit or 4:2:2 video, decodes on
the CPU and still scales and encodes on the GPU: `nvenc-hybrid` and
`vaapi-hybrid`. If a path fails during a job, the whole set of renditions
runs again on the next path, ending with the CPU, within the same attempt.
Every path encodes the same bitrates and keyframes, so renditions match
whichever path made them. **Jobs** shows the path each output used, and any
that failed.
`CLIPMUX_ENCODER` picks the first path to try (`auto`, `nvenc`, `vaapi`,
`cuda-decode` or `cpu`; the CPU always backs it up), and
`CLIPMUX_VAAPI_DEVICE` picks a render node, for example
`/dev/dri/renderD129`, when there is more than one.
## Give the container a GPU [#give-the-container-a-gpu]
Docker gives a container no GPU unless asked. Put the request in an override
file beside `compose.yml`, for example `/opt/clipmux/compose.gpu.yml`:
```yaml title="compose.gpu.yml"
services:
app:
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
```
This needs the NVIDIA Container Toolkit on the host. The image already asks
the runtime for the driver's video, compute and graphics libraries, which
NVENC and whisper.cpp use.
```yaml title="compose.gpu.yml"
services:
app:
devices:
- /dev/dri:/dev/dri
group_add:
- "992"
```
Replace `992` with your host's `render` group ID, from
`getent group render | cut -d: -f3`. The app runs as an unprivileged user,
and the group lets it open the render node.
To set `CLIPMUX_ENCODER` or `CLIPMUX_VAAPI_DEVICE`, add them to the same
file under `app`, as `environment:` entries. Then start the stack with both
files:
```bash
cd /opt/clipmux
sudo docker compose -f compose.yml -f compose.gpu.yml up -d --wait
```
The installer's upgrade starts the stack with `compose.yml` alone, so the
app comes back without the GPU. After each upgrade, run the command above
again.
## Turn the built-in encoder off [#turn-the-built-in-encoder-off]
On a small or shared server, you may want the app to encode nothing and
send every video to [Modal](/docs/self-host/encoding/modal),
[RunPod](/docs/self-host/encoding/runpod) or a
[PC you own](/docs/self-host/encoding/your-pc). Set
`CLIPMUX_BUILTIN_WORKER=false` in `.env`, then restart with
`docker compose up -d --wait`.
Connect the other encoder first: with no encoder online, new videos wait in
`processing`.
To cap how much CPU encoding takes, add `cpus:` to the `app` service in an
override (for example `cpus: 4`). Without a cap, encoding runs at idle
priority, so it yields to the API and playback but uses whatever CPU is
free.
## The sandbox [#the-sandbox]
Every ffmpeg, Shaka Packager and whisper.cpp run is confined with Landlock
and seccomp:
- no network;
- writes only to the job's own directory;
- reads only system paths and the job's source;
- CPU, memory and file limits, with 8 GiB of memory per tool by default
(`CLIPMUX_TOOL_MEMORY_MB`);
- a GPU path may also open its own device nodes, and local sockets that
CUDA needs, never a network socket.
The encoder holds no storage keys: it fetches the source and uploads its
output through the app, with URLs signed for that one job.
The built-in encoder refuses to start on a kernel without Landlock, because
its tools could otherwise read the server's keys. Uploads then wait in
`processing`. `CLIPMUX_UNSANDBOXED_WORKER=true` runs it anyway; set it only
if the host isolates the app another way. Where only Landlock is missing,
the tools keep seccomp and the limits.
## Check it works [#check-it-works]
- **Encoding** shows **This server** as **Online**.
- The app's log names the paths that passed, best first:
```bash
cd /opt/clipmux && sudo docker compose logs app | grep '"msg":"encoders"'
```
A line with `"order":"nvenc (NVIDIA …), cpu"` or
`"order":"vaapi (/dev/dri/renderD128), cpu"` means the GPU passed its
test. `"order":"cpu"` alone means it didn't: the container can't see the
GPU, or the driver is too old for this FFmpeg.
- `built-in worker not started` in the log says why the encoder didn't
start, for example a kernel without Landlock.
- Upload a video and open it on **Jobs**: the attempt shows the path each
output used.
## Next [#next]
- [Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits)
- [Encoding performance](/docs/self-host/encoding/performance)
- [Transcribe with whisper.cpp](/docs/self-host/captions-and-ai/whisper)
---
# Encode on Modal
Rent a GPU machine on Modal for each video, with a monthly spend limit, and keep this server as the fallback.
Source: https://clipmux.com/docs/self-host/encoding/modal
Modal starts a GPU machine for each job and stops it when the job is done,
so you pay only while a video encodes. Once connected, Modal takes new
videos and this server takes over when Modal can't. The machine runs the
same ClipMux image as your server, claims one job, and never holds your
storage keys.
## Before you start [#before-you-start]
- A Modal account.
- A public URL that Modal's machines can reach from the internet, for
example `https://video.example.com`. Connect refuses a public URL that
resolves to a private, loopback or link-local address. With videos stored
on this server's disk, the machines also download sources and upload
output through it.
- A server built from a published release. A local build names no image for
Modal to run; enter one under **Advanced**, **Worker image**.
For each job, Modal's machine receives the video's source file and the
content key for the output it encodes, and holds them for that job's
length. It uploads the encrypted output back through URLs signed for that
one job. If the machine also makes the subtitles, it gets the video's
audio. Modal never receives your storage keys, your other videos or your
Modal token: the token stays sealed in your database.
## Connect Modal [#connect-modal]
### Choose the GPUs [#choose-the-gpus]
On **Encoding**, choose **Connect Modal**. The dialog lists Modal's GPUs
with NVENC, each priced per hour with the CPU and memory its machine gets.
ClipMux tries the ones you tick in order, moving to the next when one has no
capacity. **L4** and **A10G** are ticked by default: both decode AV1 on the
GPU. The **T4** is cheaper but can't decode AV1, so an AV1 upload decodes
on the machine's CPUs, about four times slower. **L40S** is also offered.
### Check the limits [#check-the-limits]
The dialog shows the limits ClipMux sets: **up to 10 machines at once** and
**$50 a month**. Choose **Change** to edit them. Each video gets its own
machine, so a long 4K encode doesn't hold up the uploads behind it, and the
monthly limit still caps the spend. Set 1 to encode one video at a time.
### Approve on Modal [#approve-on-modal]
Choose **Connect with Modal**. Modal's own approval page opens, the one its
CLI uses to issue tokens. Approve there, and the token goes straight to your
server; you never copy it.
To paste a token instead, choose **Paste a token instead**, create a token
in Modal under **Settings**, **API Tokens**, and paste the `modal token set …`
command it shows: that fills both fields.
### Wait for the sample [#wait-for-the-sample]
ClipMux checks the token by opening this install's Modal app
(`clipmux-` and a tag of this install), checks that the public URL
resolves to a public address, pins the worker image to its digest, saves the token sealed with
the secrets key, and runs the [setup test](/docs/self-host/first-run) on a
Modal machine. **Encoding** shows **Checking** meanwhile.
When the sample encodes and plays, Modal shows **Ready** and becomes where
new videos encode, with this server as the fallback when it runs the
built-in encoder. Until then, new videos encode where they did before.
Through the API, connect with `POST /v1/executors/modal/connect`, or start
the browser approval with `POST /v1/executors/modal/authorize`. See
[Management API](/docs/reference/management-api).
## Settings and defaults [#settings-and-defaults]
| Setting | Default | Notes |
| --- | --- | --- |
| GPUs | L4, then A10G | Tried in order until one has capacity. |
| CPU | 4 cores | Per machine. |
| Memory | 16 GiB | Per machine. |
| Disk | 50 GB | A machine takes only sources that fit three times over. Larger ones go to the fallback, if there is one. |
| Machines at once | 10 | One per video. The monthly limit still applies. |
| Monthly limit | $50 | Calendar month, UTC. |
| Rate | the dearest chosen GPU's price | Includes the machine's CPU and memory, at Modal's published prices. |
ClipMux estimates spend from the rate and each machine's running time.
Modal's own billing report then replaces the estimate up to the last hour
it covers. **Encoding** shows this month's spend against the limit, and how
many machines are running. What happens at the limit is in
[Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits).
Connect again to change any of these or to rotate the token. Modal then
needs a new setup test before it takes videos again.
## How machines run [#how-machines-run]
- **One job per machine.** A machine runs the ClipMux image with a one-time
key that claims one job, before a deadline. It holds no storage
credentials: each step gets URLs signed for that job alone.
- **Only its own machines.** Machines run in the app `clipmux-{tag}`,
tagged with this install, so ClipMux only ever lists or stops its own.
- **Stopped on time.** Modal ends a machine when its job exits, or after
6 h 15 min at most. ClipMux also stops one whose attempt ended, or that
didn't claim its job in time.
- **Sandboxed.** Modal runs machines under gVisor, which has no Landlock.
The media tools still run with their resource limits, `no_new_privs` and
seccomp.
## Disconnect [#disconnect]
On **Encoding**, choose **Disconnect** under Modal, or call
`DELETE /v1/executors/{kind}`. ClipMux forgets the token, and if Modal was
where new videos encode, they go back to this server. It refuses while a
Modal machine may still be running.
## Check it works [#check-it-works]
- **Encoding** shows Modal as **Ready**, with its spend this month.
- Upload a short video. **Jobs** shows it routed to Modal, and the attempt
ran there.
- The Connect dialog shows each step's result. A failed `public_url` step
means the public URL is private or doesn't resolve; a failed `image` step
means the worker image can't be found or pulled.
- If Modal shows **Check failed** after connecting, the line under it names
the setup test's check that failed, and new videos keep encoding on this
server. Choose **Connect again** to retry.
## Next [#next]
- [Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits)
- [Encoding performance](/docs/self-host/encoding/performance)
- [Encode on RunPod](/docs/self-host/encoding/runpod)
---
# Encode on RunPod
Rent a GPU pod on RunPod's Secure Cloud for each video, with a monthly spend limit, and keep this server as the fallback.
Source: https://clipmux.com/docs/self-host/encoding/runpod
RunPod starts a GPU pod on its Secure Cloud for each job, and ClipMux stops
it when the job is done. Once connected, RunPod takes new videos and this
server takes over when RunPod can't. The pod runs the same ClipMux image as
your server, claims one job, and never holds your storage keys.
## Before you start [#before-you-start]
- A RunPod account with credit.
- A public URL that RunPod's pods can reach from the internet, for example
`https://video.example.com`. Connect refuses a public URL that resolves to
a private, loopback or link-local address. With videos stored on this
server's disk, pods also download sources and upload output through it.
- A server built from a published release. A local build names no image for
RunPod to run; enter one under **Advanced**, **Worker image**.
For each job, RunPod's pod receives the video's source file and the
content key for the output it encodes, and holds them for that job's
length. It uploads the encrypted output back through URLs signed for that
one job. If the pod also makes the subtitles, it gets the video's audio.
RunPod never receives your storage keys or your other videos. Your RunPod
API key stays sealed in your database.
## Connect RunPod [#connect-runpod]
### Get an API key [#get-an-api-key]
On **Encoding**, choose **Connect RunPod**, then **Get a key from RunPod**.
RunPod's console opens, creates a key for ClipMux and shows it; paste it into
**RunPod API key**. A key you create yourself under **Settings**, **API
Keys** works too, with read and write access to pods and container registry
auths.
### Choose the GPUs [#choose-the-gpus]
The dialog then lists the Secure Cloud GPUs whose NVENC the encoder can
use, each with its price per hour, the **L4** recommended. By default
ClipMux asks for an L4, then an RTX A4000, then an RTX A5000, until one
has capacity; the GPUs you choose are tried in the order the dialog lists
them.
RunPod's RTX 4090 hosts refuse NVENC sessions, so they aren't offered.
### Check the limits [#check-the-limits]
The dialog shows the limits ClipMux sets: **up to 10 machines at once** and
**$50 a month**. Choose **Change** to edit them. Each video gets its own
pod, so a long 4K encode doesn't hold up the uploads behind it, and the
monthly limit still caps the spend. Set 1 to encode one video at a time.
### Connect and wait for the sample [#connect-and-wait-for-the-sample]
Choose **Connect RunPod**. ClipMux checks the key and the public URL, pins
the worker image to its digest, saves the key sealed with the secrets key,
and runs the [setup test](/docs/self-host/first-run) on a RunPod pod.
**Encoding** shows **Checking** meanwhile.
When the sample encodes and plays, RunPod shows **Ready** and becomes where
new videos encode, with this server as the fallback when it runs the
built-in encoder. Until then, new videos encode where they did before.
Through the API, connect with `POST /v1/executors/runpod/connect`, or start
the browser approval with `POST /v1/executors/runpod/authorize`. See
[Management API](/docs/reference/management-api).
## Settings and defaults [#settings-and-defaults]
| Setting | Default | Notes |
| --- | --- | --- |
| GPUs | L4, RTX A4000, RTX A5000 | Tried in order until one has capacity. |
| Disk | 50 GB | A pod takes only sources that fit three times over. Larger ones go to the fallback, if there is one. |
| Machines at once | 10 | One per video. The monthly limit still applies. |
| Monthly limit | $50 | Calendar month, UTC. |
| Rate | the dearest chosen GPU's Secure Cloud price | |
ClipMux estimates RunPod spend from the rate and each pod's running time;
it doesn't read RunPod's bill. **Encoding** shows this month's estimate
against the limit, and how many pods are running. What happens at the
limit is in
[Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits).
Connect again to change any of these or to rotate the key. RunPod then needs
a new setup test before it takes videos again.
## How pods run [#how-pods-run]
- **One job per pod.** A pod runs the ClipMux image with a one-time key
that claims one job, before a deadline. It holds no storage credentials:
each step gets URLs signed for that job alone. Its media tools always run
sandboxed.
- **Only its own pods.** Pods are named `clipmux-{tag}-{dispatch}`, with
this install's tag. ClipMux never lists, stops or touches any other pod in
the account.
- **Secure Cloud only.** A pod sees the source and the output's content key,
and Community Cloud hosts are other people's machines, so ClipMux doesn't
offer them.
- **Stopped by ClipMux.** RunPod restarts a container that exits, so ClipMux
stops each pod when its attempt ends, when it hasn't claimed its job
within 10 minutes, or after 6 h 15 min at most. Every 15 minutes, and when
the server starts, it also stops any of its pods that no job accounts for.
## Disconnect [#disconnect]
On **Encoding**, choose **Disconnect** under RunPod, or call
`DELETE /v1/executors/{kind}`. ClipMux forgets the key, and if RunPod was
where new videos encode, they go back to this server. It refuses while a
RunPod pod may still be running.
## Check it works [#check-it-works]
- **Encoding** shows RunPod as **Ready**, with its spend this month.
- Upload a short video. **Jobs** shows it routed to RunPod, and the attempt
ran there.
- The Connect dialog shows each step's result. A failed `credentials` step
means RunPod refused the key; a failed `public_url` step means the public
URL is private or doesn't resolve.
- If RunPod shows **Check failed** after connecting, the line under it names
the setup test's check that failed, and new videos keep encoding on this
server. Choose **Connect again** to retry.
- **RunPod has none of the GPUs ClipMux encodes on for rent right now**:
RunPod's Secure Cloud has no capacity for them at the moment; try again
later.
## Next [#next]
- [Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits)
- [Encoding performance](/docs/self-host/encoding/performance)
- [Encode on Modal](/docs/self-host/encoding/modal)
---
# Encode on a PC you own
Connect a computer with a GPU, at home or in an office, as an encoder for your ClipMux server.
Source: https://clipmux.com/docs/self-host/encoding/your-pc
A PC agent is a computer you own that encodes for your ClipMux server, with
its GPU if it has one. It connects out to the server, so it works behind
NAT, and it holds no storage credentials: each job gives it a token and
signed URLs for that job alone. It suits a small server with a GPU
elsewhere, or a library of videos already on one machine.
This is a command-line option. The dashboard doesn't list PCs: you pair,
route and revoke them with `clipmux` commands and the
[management API](/docs/reference/management-api). Most installs don't need
one, because the server's own encoder already uses its GPU, and a VPS can
use [Modal](/docs/self-host/encoding/modal) or
[RunPod](/docs/self-host/encoding/runpod).
## Before you start [#before-you-start]
- On Linux: amd64 or arm64 with glibc 2.39 or newer, such as Ubuntu 24.04,
Debian 13 or Fedora 40 and later. Elsewhere (Windows, macOS, or another
Linux), Docker.
- The server's public URL, for example `https://video.example.com`,
reachable from the PC. With videos stored on the server's disk, the PC
downloads sources and uploads output through it.
- A shell on the ClipMux server, to make a pairing code.
## Install the agent on Linux [#install-the-agent-on-linux]
### Make a pairing code [#make-a-pairing-code]
On the server:
```bash
cd /opt/clipmux && sudo docker compose exec app clipmux admin create-pairing --app studio-pc
```
`--app` names the PC (the default is its hostname). The code is already
approved, works once, and expires after 15 minutes. `POST /v1/agents/pairings`
makes one through the API.
### Run the installer on the PC [#run-the-installer-on-the-pc]
```bash
curl -fsSL https://clipmux.com/install-agent.sh | sudo sh -s -- \
--server https://video.example.com --pair ABCD-EFGH
```
The installer downloads the agent for the PC's architecture, checks it
against the release's `SHA256SUMS`, and sets up a systemd service that
starts it at boot. The agent comes with its own FFmpeg, Shaka Packager and
VAAPI drivers, so nothing else needs installing.
- **With `sudo`**, it installs to `/opt/clipmux-agent`, with a system
service that runs as a `clipmux-agent` user in the `video` and `render`
groups, for the GPU.
- **Without `sudo`**, it installs to `~/.local/share/clipmux-agent`, with a
user service, and asks systemd to keep it running while you're logged out.
On a machine without systemd, it prints the command to run the agent
yourself.
| Option | What it does |
| --- | --- |
| `--server URL` | The ClipMux server's public URL. |
| `--pair CODE` | The pairing code. Not needed to upgrade. |
| `--name NAME` | What to call this PC. The default is its hostname. |
| `--version vX.Y.Z` | Install that release instead of the latest. |
| `--uninstall` | Stop and remove the agent. Its connection is kept for a reinstall. |
| `--purge` | With `--uninstall`, also forget the connection. |
Run the installer again to upgrade; the connection is kept.
## Or connect from the PC itself [#or-connect-from-the-pc-itself]
If `clipmux` is already on the PC, start it with the server's URL:
```bash
clipmux worker --server https://video.example.com
```
It prints a code and opens the server's **Connect a PC** page
(`/workers/connect`) in your browser. Check the code matches, and choose
**Connect**. On a machine without a browser, open the printed link anywhere
you're signed in to the dashboard. The agent keeps its key in `agent.json`
(mode 0600) in your config directory, so from then on `clipmux worker` alone
starts it.
## Run the agent in Docker [#run-the-agent-in-docker]
On Windows, macOS, or a Linux without glibc 2.39, the ClipMux image is also
the agent:
```bash
docker run -d --name clipmux-agent --restart unless-stopped --no-healthcheck \
--user "$(id -u):$(id -g)" \
-v "$HOME/.config/clipmux:/var/lib/clipmux-agent" -e CLIPMUX_AGENT_DIR=/var/lib/clipmux-agent \
ghcr.io/visheshgubrani/clipmux:v1.0.0 worker --server https://video.example.com --pair ABCD-EFGH
```
The image tag is your server's own release, so the agent speaks its worker
API. It runs as your user and keeps its connection in `~/.config/clipmux`, where
a restarted container finds it again. For a GPU, add one of these after
`docker run`:
- **NVIDIA** (Linux, or Windows through WSL2 and Docker Desktop):
`--gpus all`. This needs the NVIDIA Container Toolkit.
- **AMD or Intel** (Linux):
`--device /dev/dri --group-add "$(getent group render | cut -d: -f3)"`.
Docker Desktop on a Mac runs Linux in a VM without the GPU, so it encodes on
the CPU. The sandbox still holds there.
## Send jobs to PCs [#send-jobs-to-pcs]
A fresh install sends jobs to this server and paired PCs alike, so a PC
starts taking jobs as soon as it connects. Choosing **This server** or a
cloud GPU on **Encoding** changes that: PCs then take only the jobs of
videos they registered themselves (below).
To send jobs to PCs again, set routing through the API, signed in as the
owner (the routes need the dashboard's session cookie):
```bash
curl -X PUT https://video.example.com/v1/settings/routing \
-H 'Content-Type: application/json' \
--cookie "__Host-clipmux_session=…" \
-d '{"primary_executor": "workers"}'
```
`workers` is this server and PCs; `agents` is PCs only. See
[Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits).
## Encoders [#encoders]
The agent tests each GPU path when it starts and offers only the ones that
pass: `nvenc`, `vaapi`, `cuda-decode`, then `cpu`, with the hybrid paths for
sources the GPU can't decode. It's the same choice as on the server; see
[Encode on this server](/docs/self-host/encoding/this-server). `--encoder`
(or `CLIPMUX_ENCODER`) picks the first path to try, `CLIPMUX_VAAPI_DEVICE`
picks a render node, and `--encoder cpu` skips the GPU.
The Linux agent has no CUDA build of whisper.cpp, so on an NVIDIA card it
transcribes with Vulkan.
## Videos that stay on the PC [#videos-that-stay-on-the-pc]
```bash
clipmux push --local ~/Videos/course
```
The files aren't uploaded. The agent on this PC registers them, encodes them
where they are, and uploads only the encrypted output. Without an API key
they become your own uploads, as if from the dashboard; with
`CLIPMUX_API_KEY` set, the key's app owns them.
- Jobs for these videos run only on this PC. While it's asleep they wait,
and they fail as `agent_unavailable` if it stays away for 7 days.
- A file that changes or disappears before it's encoded fails its job as
`source_changed` or `source_missing`, and the video keeps playing what it
had.
- `--upload-source` also uploads each file to the server's storage after
encoding it here, so any encoder can re-encode it later.
- To limit which folders `push --local` may hand over, list them in
`agent.json`: `{ "roots": ["/home/me/Videos"] }`.
- In Docker, mount the videos at the same path inside the container, for
example `-v "$HOME/Videos:$HOME/Videos:ro"`.
These videos' sources never leave the PC unless you pass
`--upload-source`. Back them up yourself: if the PC's disk dies, the
videos keep playing, but can't be re-encoded.
## The sandbox [#the-sandbox]
Every ffmpeg and packager run on the PC is confined: no network, writes
only to the job's own directory, reads only system paths and the job's
source, with CPU, memory and file limits. An agent where the sandbox can't
hold (not Linux, or an old kernel) refuses to start unless you pass
`--unsandboxed`. It then takes only jobs pinned to it and the files you
upload in the dashboard, never an app's uploads or a file imported from a
URL.
## Check it works [#check-it-works]
```bash
clipmux worker doctor
```
It checks the connection, the server, the key, the tool versions, the
sandbox, each encoder and scratch disk space, marking each with ✓ or ✗. Fix
the first ✗. `clipmux worker doctor --offline` skips the first three, to
check a machine before it's connected. With the system service, run it as
the service's user:
`sudo -u clipmux-agent /usr/local/bin/clipmux worker doctor`.
- **`key accepted` ✗**: the server revoked this PC. Remove `agent.json` and
pair again.
- **`scratch disk`**: a source needs about three times its size free.
- **The installer says the agent didn't connect**: the code expired or was
used. Make a new one.
`GET /v1/agents` lists the PCs the server knows, with whether each is online
and sandboxed. The service's log is in `journalctl -u clipmux-agent` (or
`journalctl --user -u clipmux-agent` for a user install).
## Disconnect a PC [#disconnect-a-pc]
`DELETE /v1/agents/{id}` revokes the PC at once: its key stops working, and
a job it was running moves to another encoder without using up a retry. If
you no longer trust what it encoded, `POST /v1/agents/{id}/reencode`
re-encodes every video whose current version that PC made. The dashboard
lists no PCs, so revoke one you no longer use: it keeps its key until you
do. Then run the installer with `--uninstall --purge` on the PC.
## Next [#next]
- [Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits)
- [Encode on this server](/docs/self-host/encoding/this-server)
- [Command line](/docs/reference/cli)
---
# Routing, fallback and spend limits
How ClipMux decides where each job runs, when it uses the fallback, and how cloud GPU spend is held under its limit.
Source: https://clipmux.com/docs/self-host/encoding/routing-and-limits
Each job goes to one **primary** encoder, with an optional **fallback**
that takes over when the primary can't. ClipMux decides again for every
queued job as things change, and the **Jobs** page shows where each job was
sent and why. Cloud GPUs carry two limits, machines at once and spend per
month, which ClipMux checks before it starts a machine.
## Before you start [#before-you-start]
- An owner account on the dashboard.
- For a cloud GPU as primary: Modal or RunPod connected, with its setup
test passed. See [Encode on Modal](/docs/self-host/encoding/modal) and
[Encode on RunPod](/docs/self-host/encoding/runpod).
## Choose the primary and the fallback [#choose-the-primary-and-the-fallback]
On **Encoding**, choose where new videos encode:
- **This server**: the built-in encoder is the primary, with no fallback.
- **Modal** or **RunPod**, once it shows **Ready**: the cloud GPU is the
primary. Tick **If Modal can't start a machine, encode on this server
instead** (or RunPod) to make this server the fallback.
A cloud GPU becomes the primary by itself when its connect test passes,
with this server as the fallback when the server runs the built-in encoder.
The API takes more choices than the page offers
(`PUT /v1/settings/routing`, with the owner's session):
| Field | Values |
| --- | --- |
| `primary_executor` | `builtin` (this server), `workers` (this server and PCs), `agents` (PCs only), `modal`, `runpod` |
| `fallback_executor` | `builtin`, or none. It can't be part of the primary. |
| `queue_age_fallback_minutes` | 1 to 1440, or none. Needs a fallback. |
A fresh install's primary is `workers`, so a paired PC shares jobs with this
server. Saving a choice on **Encoding** turns queue-age fallback off again.
## When a job goes to the fallback [#when-a-job-goes-to-the-fallback]
| Condition | What happens |
| --- | --- |
| The primary can take the job | It runs on the primary. |
| The primary has had no encoder online for 60 seconds | It goes to the fallback. |
| The primary is a cloud GPU whose machines' disk is too small for the source (three times its size) | It goes to the fallback. |
| Queue-age fallback is on and the job has waited longer than that | It goes to the fallback. |
| An attempt fails for a reason that isn't the file's (a network error, a full disk, a lost lease) | It's retried, on the fallback if the primary is still offline. |
| An attempt fails in a way that may be the file's fault | It never goes to the fallback, so a broken file can't run up a cloud bill. A source that can't be encoded marks the video `errored`. |
| The video's source lives on a PC | It waits for that PC, with no fallback. |
## Route reasons on Jobs [#route-reasons-on-jobs]
A queued job says where it's routed and why; an attempt says why it ran
where it did.
| Reason | What it means |
| --- | --- |
| `primary` | The primary could take it. |
| `primary_offline` | Sent to the fallback: the primary was offline. |
| `queue_age` | Sent to the fallback: it waited too long for the primary. |
| `pinned` | Its PC holds the file, so only that PC can run it. |
| `no_fallback` | Waiting: the primary is offline and there is no fallback. |
| `fallback_refused` | Waiting: an earlier attempt on this video failed, so it stays off the fallback. |
| `fallback_offline` | Waiting: the primary and the fallback are both offline. |
| `fallback_limit` | Waiting: the primary is offline and the fallback is at its machine or spend limit. |
| `primary_limit` | Waiting: the primary is a cloud GPU at its machine or spend limit. |
| `setup_test` | A setup test's sample, which runs only on the encoder its test names. |
## Spend limits [#spend-limits]
Each cloud GPU has a **monthly limit** ($50 unless you change it) and a
**rate** per machine-hour, which defaults to the dearest GPU you chose.
ClipMux counts spend per calendar month, in UTC:
- A machine costs its rate from when it was started until it was stopped.
- **Before a machine starts, its job reserves an estimated run**: one hour
per 4 GiB of source, at least 15 minutes and at most 6 h 15 min. A source
of unknown size, such as an import from a URL, counts as one hour. The
reservation counts until the machine stops, so the limit holds before any
machine has run long enough to show its cost.
- A machine starts only if this month's spend plus the job's reservation
fits under the limit, and fewer machines than the limit are running.
- For Modal, ClipMux reads Modal's own bill, which replaces the estimate up
to the last hour it covers. RunPod's spend stays the estimate.
**Encoding** shows this month's spend against the limit, and how many
machines are running.
### At the limit [#at-the-limit]
- A machine that is already running isn't stopped. Its job finishes, so a
month can end over the limit by what the running machines take past
their reservations.
- New jobs wait for the cloud GPU (`primary_limit`). The fallback doesn't
take them, unless you set queue-age fallback, which sends a job to the
fallback once it has waited that long.
- If the cloud GPU is the fallback, jobs wait for the primary
(`fallback_limit`).
- After failed machine starts, ClipMux backs off from the provider for a
while; **Encoding** shows until when.
Raise the limit with **Connect again** on **Encoding**, or let the month
roll over.
## Check it works [#check-it-works]
- Upload a video and open **Jobs**: the job says where it's routed and why,
and its attempt shows where it ran.
- `GET /v1/settings/routing` returns the primary, the fallback, the
queue-age setting, whether the built-in encoder is online, and which cloud
GPUs are ready.
- A job stuck on `no_fallback` or `fallback_offline` needs an encoder online:
check **This server** shows **Online** on **Encoding**.
## Next [#next]
- [Encode on Modal](/docs/self-host/encoding/modal)
- [Encoding performance](/docs/self-host/encoding/performance)
- [Troubleshooting](/docs/self-host/operate/troubleshooting)
---
# Encoding performance
Measured encode and transcription times on Modal GPUs and a local AMD card, and what drives them.
Source: https://clipmux.com/docs/self-host/encoding/performance
These are measurements of real ClipMux runs, with the hardware and the date
of each. They aren't guarantees: your sources, GPUs and network will differ.
Use them to choose where to encode and to estimate how long a library takes.
## What drives encode time [#what-drives-encode-time]
- **The source's resolution and codec.** A 4K source encodes about 4.3
times the pixels of a 1080p one, and gets two more renditions (2160p and
1440p). A codec the GPU can't decode, such as AV1 on a T4, decodes on the
CPU instead (`nvenc-hybrid`), which is much slower.
- **Which renditions you ask for.** By default every standard rendition up
to the source's size is encoded. Asking for fewer encodes less. See
[Choose renditions](/docs/build/upload/renditions).
- **GPU or CPU.** A GPU path decodes, scales and encodes on the card. The CPU
path encodes with libx264, at idle priority on this server.
- **Uploading the output.** A long video makes thousands of files. The
encoder uploads 32 at a time.
- **Subtitles.** Transcription is its own job after the encode, and on a
long video it can take as long as the encode.
- **Cloud start-up.** A Modal machine took 20 to 53 seconds to start after
an upload finished.
## Three videos on Modal [#three-videos-on-modal]
Measured November 2026 on Modal, with the default sandbox (4 CPU cores,
16 GiB), three lectures uploaded back to back with up to 10 machines at
once. Each got its own machine with no queue wait, and every job succeeded
first time. "Upload to subtitles" is from the end of the upload until the
subtitles were ready.
| Video | Source | GPU | Video encode | Output upload | Audio fetch | Transcription (realtime factor) | Upload to subtitles |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 20 min | 1080p VP9 | T4 | 207 s | 41 s (998 files, 207 MB) | 12 s | 162 s (0.14) | 8 min |
| 54 min | 4K AV1, 6 renditions | L4 | 1,086 s | 121 s (3,832 files, 5.9 GB) | 31 s | 763 s (0.23) | 35 min |
| 67 min | 1080p AV1 | T4, `nvenc-hybrid` | 1,372 s | 143 s (3,358 files, 5.2 GB) | 42 s | 1,196 s (0.30) | 48 min |
The 67-minute AV1 video on the T4 spent 23 minutes on video, because the T4
can't decode AV1 and the machine's four CPUs decoded it. A 76-minute 1080p
AV1 video on an L4 spent 6 minutes. That is why the L4 and A10G are Modal's
default GPUs.
## Transcription [#transcription]
The realtime factor is transcription time divided by the audio's length:
0.23 means 10 minutes of audio took 2.3 minutes.
- **On Modal with CUDA** (November 2026), whisper.cpp ran at 0.14 on an
English lecture and 0.23 to 0.30 on Hindi lectures, in the table above.
- **The 14-second JFK test clip**, under the sandbox with CUDA, took 5.2 s on
an L4 and 4.3 s on a T4, including loading the model.
- **On an AMD RX 6600 XT with Vulkan**, under the sandbox, the same clip
took 2.7 s, against 22.8 s on the CPU.
## Short 4K clips [#short-4k-clips]
A 2-second 4K clip, encoded into every rendition, measures the fixed cost of
an encode more than its speed:
| Hardware | Path | Time for 2 s of 4K |
| --- | --- | --- |
| AMD RX 6600 XT, local, November 2026 | `vaapi` | 2.3 s |
| NVIDIA L4 and T4 on Modal, November 2026 | `nvenc` | about 45 to 50 s |
The gap points to a large fixed cost per encode on Modal's runtime, which a
short clip shows and a long video spreads out; the Modal table above is the
better guide for real videos.
## Next [#next]
- [Encode on Modal](/docs/self-host/encoding/modal)
- [Encode on this server](/docs/self-host/encoding/this-server)
- [Requirements and sizing](/docs/self-host/requirements)
---
# Built-in delivery
How your ClipMux server streams encrypted HLS itself, and when to give it its own hostname or move it to Cloudflare.
Source: https://clipmux.com/docs/self-host/delivery/built-in
Out of the box, the ClipMux server streams every video itself. Players fetch
playlists, segments, posters and keys from the media URL, and the server
checks each request against the playback ID's route before it sends a byte.
Nothing else needs to run, and nothing leaves your server.
This page explains what the server does per request, what it lets browsers
and proxies cache, and how to put playback on its own hostname.
## Before you start [#before-you-start]
- A running ClipMux server. See [Install with one line](/docs/self-host/install).
- For a separate media hostname: a DNS name you control, such as
`media.example.com`, that you can point at the same server.
## What happens on each request [#what-happens-on-each-request]
Playback URLs have two shapes:
```txt
https://media.example.com/v/{token}/{playback_id}/master.m3u8 private (signed)
https://media.example.com/p/{playback_id}/master.m3u8 public
```
For every request, the server:
1. Looks up the playback ID's route. An unknown or revoked ID, or a video
that is deleted or not ready yet, is a `404`. A signed ID requested
through `/p/`, or any ID of a disabled app, is `403 denied`.
2. For a signed ID, verifies the token from the path: an ES256 signature by
a signing key of the video's app that isn't revoked or retired, `sub`
equal to the playback ID, an `iat` no more than 60 seconds in the future,
and `exp - iat` within the maximum token lifetime. An expired token is
`401 token_expired`; anything else wrong is `403 denied`.
3. Checks the audience. A `t` token fetches only the poster.
4. Builds the master playlist fresh, pointing every rendition at the
current output, so a viewer stays on one output for the whole session,
even if the video is re-encoded meanwhile.
5. Serves only files the output's committed manifest lists, with a
`Content-Type` from an extension allowlist (`.m3u8`, `.mp4`, `.m4s`,
`.jpg`) and `X-Content-Type-Options: nosniff`.
Every output is encrypted with AES-128. When a player asks for the key, the
server derives it on the spot: an HMAC-SHA256 over the video's asset ID and
the output ID, keyed with the content key secret. No key is stored anywhere,
and a token for one video can't fetch another video's key. Public playback
IDs get the key without a token, so the same output plays under either
policy. See [What encryption does and doesn't do](/docs/build/concepts/encryption).
Players on any origin may fetch: responses carry
`Access-Control-Allow-Origin: *`. The URL is the credential, and no cookie
is involved.
## What's cached [#whats-cached]
| Response | `Cache-Control` |
| --- | --- |
| `master.m3u8` | `no-store`. It's generated per request. |
| The content key | `no-store` |
| Rendition playlists, segments and the output's poster, under `{playback_id}/{output_id}/` | `max-age=31536000, immutable`. An output's files never change. |
| `poster.jpg` at the top level | `max-age=300`, since it follows the current output |
| Subtitle and chapter files (`.vtt`) | `max-age=31536000, immutable` |
| Subtitle playlists | `no-store` |
Files of a private video are marked `private`, so shared caches and CDNs
don't keep them; files of a public video are marked `public`.
The server also caches routes, signing keys and outputs in memory for 30
seconds. On one server, a published change (a revoked playback ID or signing
key, a new output) applies at the next request. A change to the maximum
token lifetime can take up to 30 seconds.
## Give playback its own hostname [#give-playback-its-own-hostname]
By default the media URL is the public URL, so videos play from the same
origin as the dashboard and the API. For production, serve them from a
separate registrable domain, such as `example-media.com` next to
`video.example.com`. A hostile file that somehow got stored then can't
reach dashboard cookies. A different hostname on the same domain, such as
`media.example.com`, is better than the same origin, but not as strong.
### Point DNS at the server [#point-dns-at-the-server]
Create a DNS record for the media hostname that points at the same server as
the public URL. With the one-line install, Caddy obtains a certificate for
it on its first request.
### Set the media URL [#set-the-media-url]
In the dashboard, open **Settings**, and under **Addresses** set
**Media URL** to `https://media.example.com`. Or set
`CLIPMUX_MEDIA_URL=https://media.example.com` in the server's environment,
along with `CLIPMUX_PUBLIC_URL`, and restart. When the environment sets the
URLs, the dashboard shows them read-only.
### Let your apps pick it up [#let-your-apps-pick-it-up]
`GET /v1/app` returns the media URL as `base_url`. Apps that build playback
URLs from `base_url` follow it. Update any Content-Security-Policy that
names the old origin: `npx @clipmux/node doctor` prints the origins it
must allow.
## Check it works [#check-it-works]
Play a public video's master playlist and look at the headers:
```bash
curl -sI https://media.example.com/p/pid_…/master.m3u8
```
- `200` with `Cache-Control: no-store` and
`Content-Type: application/vnd.apple.mpegurl`: delivery works.
- `404`: the playback ID doesn't exist or was revoked, or the video isn't
ready.
- `403 denied`: the playback ID is signed, and plays only through
`/v/{token}/`. Or its app is disabled.
- A TLS or connection error: DNS doesn't reach the server yet, or Caddy
hasn't been able to get a certificate for the hostname.
The setup test checks the whole path, including playback: run it from
**Settings**, or with `clipmux admin setup-test --wait` on the server.
## When to move to Cloudflare [#when-to-move-to-cloudflare]
Built-in delivery sends every byte from your server. The dashboard describes
it as fine for a few hundred viewers at once. Move to Cloudflare when your
server's bandwidth is the limit, when viewers are far from it, or when you
want playback to keep working while the server restarts: the ClipMux Worker
serves from R2 and caches at the edge. Your apps, tokens and playback IDs
stay the same.
## Next [#next]
- [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Security model](/docs/self-host/security-model)
---
# Cloudflare edge delivery
Serve playback from Cloudflare's edge with the ClipMux Worker and an R2 bucket, connected from the dashboard with one token.
Source: https://clipmux.com/docs/self-host/delivery/cloudflare
Connecting Cloudflare moves playback from your server to the ClipMux Worker,
which runs in your own Cloudflare account, reads an R2 bucket and caches at
the edge. Your apps, tokens, playback IDs and `base_url` stay the same; the
Worker checks tokens and derives keys exactly as
[built-in delivery](/docs/self-host/delivery/built-in) does.
You paste one API token into the dashboard. ClipMux reads what the token can
reach, creates the bucket, deploys the Worker and points your media
hostname at it.
Cloudflare stores the encoded, encrypted video files of new videos in your
R2 bucket, and holds the content key secret as a Worker secret so it can
derive each video's key at the edge. Viewers' playback requests go to
Cloudflare instead of your server. Uploaded originals stay where
**Storage** keeps them.
## Before you start [#before-you-start]
- A domain that is an **active zone** in your Cloudflare account, and a media
hostname in it, such as `media.example.com`. It must differ from the public
URL's hostname; a different registrable domain is better still.
- **Workers Paid** on the account. Video delivery exceeds the free plan's
request quota, and Cloudflare's terms ask for a paid service for video.
See [Workers pricing](https://developers.cloudflare.com/workers/platform/pricing/).
- A public URL that Cloudflare can reach. Videos encoded before you connect
keep their files on your server, and the Worker fetches them from there.
- The owner's dashboard sign-in.
## Connect Cloudflare [#connect-cloudflare]
### Create the token [#create-the-token]
In the dashboard, open **Delivery** and choose **Connect Cloudflare**, then
**Create token on Cloudflare**. Cloudflare's create-token form opens with
every permission already chosen:
| Permission | On |
| --- | --- |
| Workers Scripts: Edit | the account |
| Workers Routes: Edit | the account |
| Workers R2 Storage: Edit | the account |
| Billing: Read | the account |
| Zone: Read | its zones |
| DNS: Edit | its zones |
Pick the account, create the token and copy it. To limit R2 to one bucket,
create the bucket first and scope the token to it there.
### Paste it and choose [#paste-it-and-choose]
Paste the token into **API token**. ClipMux reads what it reaches, so
nothing is typed by hand: the **Account** (only when the token reaches
several), the **Media hostname** as a subdomain of one of the account's
active zones, and the **R2 bucket** new videos are encoded into, an
existing one or `clipmux-media`, created for you. If the account isn't on
Workers Paid, the dialog says so before anything changes.
### Connect [#connect]
Choose **Connect Cloudflare**. ClipMux runs these steps in order and shows
each one, stopping at the first that fails:
1. Checks the token and the account.
2. Finds the zone and checks it is active.
3. Checks Workers Paid.
4. Creates the bucket if it's missing, derives R2 credentials from the
token, checks the bucket and applies CORS.
5. Deploys the Worker, with the content key secret and the analytics key
as Worker secrets.
6. Writes a route record for every playback ID to the bucket, so the Worker
serves from its first request.
7. Removes the DNS records at the media hostname, and attaches the Worker
to it as a custom domain.
8. Sets the media URL to `https://media.example.com`.
9. Saves the connection and queues the setup test through the Worker.
Every step is safe to repeat: fix what failed and connect again.
The Worker is named after its hostname: `media.example.com` deploys
`clipmux-media-example-com`. Two installs can share one Cloudflare account
without overwriting each other's Worker. Connecting again to the same
hostname redeploys the Worker made before, whatever it's called.
ClipMux uses the token for the request and keeps only its ID. Its Workers
and DNS permissions stay live in Cloudflare: narrow or revoke them there
when you no longer need to redeploy.
R2's credentials are derived from the token. Revoking or rolling the token
cuts off storage, and **Delivery** then shows "R2 refuses the stored
credentials". Connect again with a new token to fix it.
If `CLIPMUX_MEDIA_URL` is set in the server's environment, ClipMux can't
change the media URL. Set it to the Worker's hostname and restart, then
connect again.
## What changes [#what-changes]
- **New videos' encoded files go to the R2 bucket.** Where uploads go
doesn't change: **Storage** keeps the originals, on this server's disk or
a bucket you chose.
- **Older videos keep playing.** The Worker fetches their files from your
server until you move them. **Delivery** shows how many videos still play
through this server, with a button to move their encoded files to the
bucket. Progress shows on **Jobs**.
- **Revocations reach the edge within a minute.** The Worker caches route
records for 60 seconds, so a revoked playback ID or signing key stops
playing within that time.
## Redeploy the Worker [#redeploy-the-worker]
A ClipMux upgrade can carry a newer Worker. **Delivery** then shows "A newer
Worker is available", with the deployed and current versions. Choose
**Connect again** and paste a token; Connect redeploys the Worker in place.
Rotating the content key secret also redeploys the Worker, so it needs a
token too. See [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets).
To move to a different media hostname, connect again with the new one.
ClipMux deploys a new Worker named after it. The old Worker and its custom
domain stay in your account, serving from route records that are no longer
updated, until you remove them in Cloudflare.
## Disconnect [#disconnect]
Choose **Disconnect Cloudflare** on **Delivery**, or call
`DELETE /v1/cloudflare`. ClipMux puts the media URL back to the public URL,
switches delivery back to this server, removes the Worker's route records
and keys from the bucket so it refuses every playback ID, forgets the
connection and queues a setup test.
- Files already on R2 stay there and keep playing through this server. The
bucket stays a storage config.
- The Worker and its custom domain stay in your Cloudflare account, since
ClipMux keeps no token to remove them. Delete them in Cloudflare.
- While `CLIPMUX_MEDIA_URL` names the Worker's hostname, disconnecting
answers `409 pinned`. Change the variable first.
Connect from the dashboard is the supported way to set up the Worker.
Deploying it by hand isn't, because ClipMux has no command that exports
the content key secrets or switches delivery to a Worker you deployed.
## Check it works [#check-it-works]
The last step of Connect queues the setup test through the Worker. Its
result shows under **Settings**, or run it on the server:
```bash
docker compose exec app clipmux admin setup-test --wait
```
Then fetch a public video through the new hostname:
```bash
curl -sI https://media.example.com/p/pid_…/master.m3u8
```
- `200`: the Worker answers.
- `404` for a video that plays through built-in delivery: its route
record hasn't reached the bucket. `clipmux admin outbox` on the server
lists route publications that keep failing.
- A failed step in Connect: its detail says what to fix. Connect again
once it's fixed.
## Next [#next]
- [Edge analytics](/docs/self-host/delivery/edge-analytics): count playback
at the edge
- [Where videos are stored](/docs/self-host/storage)
- [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)
---
# Edge analytics
Bring the playback the Cloudflare Worker counts into ClipMux's Analytics with a second, read-only token.
Source: https://clipmux.com/docs/self-host/delivery/edge-analytics
With Cloudflare delivery, the Worker answers viewers instead of your server,
so your server no longer sees those plays. The Worker counts them itself,
the same way built-in delivery does, and writes the counts to Analytics
Engine in your Cloudflare account. Connecting edge analytics lets ClipMux
pull those counts back, so views, watch time, bandwidth and unique viewers
in **Analytics** include playback at the edge.
## Before you start [#before-you-start]
- [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare), connected.
- Access to the Cloudflare account the Worker runs in, to create a token.
## What the Worker counts [#what-the-worker-counts]
The Worker counts what built-in delivery counts: a view per generated master
playlist, 6 seconds of watch time per audio segment, and the bytes actually
streamed for every GET response (including partial transfers cancelled early).
It writes one data point per counted response to the Analytics Engine dataset
`clipmux_delivery`.
A data point holds the project, app, video, playback ID, file kind, a viewer
key (an HMAC of `vid` under the project's analytics key, omitted on poster
requests), and a per-install `INSTALL_ID` (`blob7`) so multiple installs
sharing a Cloudflare account never mix their counts. Dashboard previews
(even on public IDs), library posters and the setup test aren't counted;
[share links](/docs/build/play/share-links) are.
## Connect edge analytics [#connect-edge-analytics]
### Create a read-only token [#create-a-read-only-token]
On **Delivery**, in the **Edge analytics** card, choose
**Create token on Cloudflare**. The form opens with only
**Account Analytics: Read** chosen. Create the token on the account the
Worker runs in. It can't change anything.
### Paste it [#paste-it]
Paste it into **Read-only API token** and choose
**Connect edge analytics**. ClipMux checks it with one query and keeps it
sealed with the secrets key. It's never returned.
Over the API, the same step is `POST /v1/cloudflare/analytics` with
`{"token": "…"}`. It answers `409 not_connected` without Cloudflare
delivery, and `400 token_rejected` for a token Cloudflare refuses.
## How counts are pulled [#how-counts-are-pulled]
- The server pulls every 5 minutes.
- Each pull recomputes from an hour before the last one and replaces those
hours, so points that arrive late still count and nothing counts twice.
- A first connect starts at the later of 13 days back or when Cloudflare
delivery was connected, and catches up immediately through `now`.
- Pasting a new token keeps the place the pulls have reached.
- Disconnecting forgets the token. Counts already pulled stay in Analytics.
`GET /v1/cloudflare/analytics` returns how far the pulls have reached
(`pulled_through`), the last pull's time and its error, if any.
## What's sampled [#whats-sampled]
Analytics Engine samples high-volume requests. The Worker stratifies its data
point `indexes` by request class (`master`, watch-time segments, non-watch-time
video rendition segments, and metadata/posters) so high-volume video segments
don't drown out master-playlist view counts or bias byte weights. ClipMux
weights views, watch time and bytes back up by `_sample_interval`, so edge
counts stay accurate estimates.
Other limits:
- ClipMux pulls only the last 13 days. If pulls stop for longer than that,
the gap is lost.
- Data points and queries count against Analytics Engine's allowance on
Workers Paid. A viewer-hour writes about 1,200 data points, one per
request. See
[Analytics Engine pricing](https://developers.cloudflare.com/analytics/analytics-engine/pricing/).
- When an older Worker needs an upgrade (for example, to add `INSTALL_ID` and
stratified `indexes`), **Analytics** and **Delivery** prompt you to redeploy
Cloudflare delivery.
## Check it works [#check-it-works]
Play a video through the media hostname, wait 5 minutes, and look at the
**Edge analytics** card on **Delivery**.
- It shows **Connected** and no error: pulls are running. The plays show in
**Analytics** once the pull covers their hour.
- "The last pull failed", with the reason: if the token was revoked, choose
**Replace token** and paste
a new one.
- **Analytics** still says playback through Cloudflare isn't counted: no
token is connected. `collecting.edge` in `GET /v1/analytics` says
`not_connected`.
## Next [#next]
- [Views, watch time and unique viewers](/docs/build/analytics)
- [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare)
- [Retention](/docs/self-host/operate/retention)
---
# Transcribe with whisper.cpp
Make subtitles and transcripts on the machines that encode your videos, with a pinned whisper.cpp model and no speech API.
Source: https://clipmux.com/docs/self-host/captions-and-ai/whisper
By default, ClipMux makes subtitles where your videos are encoded: the
built-in worker on your server, a PC you own, or a Modal or RunPod machine.
The worker runs whisper.cpp on the video's audio, inside the same sandbox as
ffmpeg, and sends the transcript back to the server. No speech API is
involved, and the dashboard's **Captions & AI** page calls this option
**Where videos are encoded**.
This page covers how a worker decides whether, and on what, it transcribes,
the model it uses, and how fast it is.
## Before you start [#before-you-start]
- A worker that encodes your videos: the built-in worker, a
[PC you own](/docs/self-host/encoding/your-pc), or
[Modal](/docs/self-host/encoding/modal) or
[RunPod](/docs/self-host/encoding/runpod).
- Uploads that ask for subtitles. See
[Subtitles and transcripts](/docs/build/captions/subtitles).
On Modal or RunPod, transcription runs on the provider's machine, which
already has the video for encoding. The audio doesn't go anywhere the
video hasn't.
## Choose how a worker transcribes [#choose-how-a-worker-transcribes]
`CLIPMUX_SPEECH` (or `clipmux worker --speech`) sets it. serve passes its
value to the built-in worker.
| Mode | What the worker does |
| --- | --- |
| `auto` | The default. Tries CUDA on an NVIDIA card, then Vulkan on any GPU, then the CPU if it has at least 4 cores and 6 GiB of memory. |
| `cuda` | CUDA only. |
| `vulkan` | Vulkan only. |
| `cpu` | The CPU only, whatever its size. |
| `off` | Doesn't transcribe. |
At start, the worker proves each candidate with a real transcription under
the sandbox, and uses the first that passes. A GPU passes only if whisper.cpp
reports that it actually ran on it, so a GPU that silently falls back to the
CPU fails its probe and the next candidate is tried. The worker's log says
which backend it chose, or why it won't transcribe.
On the CPU, whisper gets half the logical CPUs, leaving the rest to the
encoder.
### Where CUDA is available [#where-cuda-is-available]
- **The amd64 image** carries whisper.cpp with CUDA, built for cards from the
T4 through the A10G, RTX A4000 and A5000, L4 and L40S, with PTX for newer
ones. This is the image the built-in worker, Modal and RunPod run.
- **arm64 images** have no CUDA.
- **The PC agent tarball** leaves CUDA out (about 1 GB), so a PC's NVIDIA card
uses Vulkan, or the CPU if its driver offers no Vulkan.
- **Modal** offers no Vulkan device, so CUDA is the only GPU path there.
## The model [#the-model]
Every worker uses the same pinned model:
- `ggml-large-v3-turbo-q8_0`, whisper large-v3-turbo quantized to 8 bits;
- Silero VAD, which skips the silence between speech.
Together they are about 0.9 GB. The image has them baked in, at
`/usr/share/clipmux/models` (`CLIPMUX_BAKED_MODELS_DIR`), so a Modal or
RunPod machine downloads nothing. A worker without them, such as a PC agent,
downloads them once from Hugging Face, checks each against its pinned
SHA-256, and keeps them in `CLIPMUX_MODELS_DIR` across restarts.
whisper.cpp detects the language of each video on its own. A video gets one
subtitles track, in one language.
## How fast it is [#how-fast-it-is]
Speeds are given as a real-time factor: the time to transcribe divided by
the length of the audio. Lower is faster; 0.25 means an hour of audio takes
15 minutes.
| Where | Backend | Measured |
| --- | --- | --- |
| A 6-core desktop CPU, 6 threads | CPU | 0.40 on 2 minutes of English speech |
| Modal, NVIDIA T4 | CUDA | 0.14 on a 20-minute English video |
| Modal, NVIDIA L4 | CUDA | 0.23 on a 54-minute Hindi lecture |
| Modal, NVIDIA T4 | CUDA | 0.30 on a 67-minute Hindi lecture |
On an AMD RX 6600 XT over Vulkan, under the sandbox, a short test clip took
2.7 seconds against 22.8 seconds on the CPU. Short clips pay a fixed cost:
whisper works in 30-second windows, so an 11-second clip takes about 22
seconds on the CPU.
## Check it works [#check-it-works]
On a PC agent, `clipmux worker doctor` runs the same speech probe the worker
does and prints the result:
- `speech` with a ✓: whisper ran the model on the named backend.
- A note that the model isn't downloaded yet: the worker downloads it at
start.
- A note that there's no `whisper-cli`: this worker won't transcribe.
- `speech` with a ✗: every candidate failed its probe; the line names each
failure.
For any worker, upload a short video that asks for subtitles, and open the
**Captions & chapters** tab on its page in the dashboard. Run
`clipmux admin setup-test --wait` on the server while a worker that can
transcribe is online, and it checks subtitles too.
## Next [#next]
- [Use a speech API](/docs/self-host/captions-and-ai/speech-apis), as the
fallback or instead
- [Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm)
- [Encoding performance](/docs/self-host/encoding/performance)
---
# Use a speech API
Send transcriptions to an OpenAI-compatible speech API, always or only when no worker of yours can transcribe.
Source: https://clipmux.com/docs/self-host/captions-and-ai/speech-apis
Instead of transcribing on your own workers, ClipMux can send a video's
audio to a speech API and make subtitles from what it returns. Any API
that speaks OpenAI's `/audio/transcriptions` with `verbose_json` timestamps
works: OpenAI's `whisper-1`, Groq's `whisper-large-v3-turbo`, or a server on
your own network such as Speaches.
You can use it for every video, or only as a fallback when none of your
workers can transcribe.
Once a mode uses the API, the audio of every video transcribed through it
goes to the provider you connect. Connecting also sends it an 11-second
public-domain speech sample. A server on your own network keeps the audio
with you.
## Before you start [#before-you-start]
- The API's base URL, such as `https://api.groq.com/openai/v1`.
- An API key, unless it's a server that needs none.
- The model name, such as `whisper-large-v3-turbo`.
## Connect a speech API [#connect-a-speech-api]
### Open the form [#open-the-form]
In the dashboard, open **Captions & AI**. Under **Subtitles**, choose
**Connect a speech API**.
### Fill it in [#fill-it-in]
Enter the **Speech API URL** and, if it needs one, the **Speech API key**.
Once the URL is in, **Speech model** lists the models the API offers; pick
one or type its name.
### Connect [#connect]
Choose **Connect**. ClipMux runs three steps and shows each one:
1. `credentials`: lists the API's models at `{base_url}/models`.
2. `transcription`: transcribes the 11-second sample, sent exactly as real
transcriptions send audio, so an API that won't take the format fails
here rather than on a video.
3. `saved`: keeps the connection, with its key sealed by the secrets key.
A failed step leaves any earlier connection as it was.
Over the API, the same is `POST /v1/settings/speech/connect` with
`{"base_url": "…", "model": "…", "api_key": "…"}`. The key is never
returned.
## Choose when it's used [#choose-when-its-used]
| Mode | In the dashboard | Where transcriptions go |
| --- | --- | --- |
| `local` | **Where videos are encoded** | whisper.cpp on your own workers. The API isn't used. |
| `local_then_api` | **Where videos are encoded**, with **If no machine can transcribe, use the speech API** ticked | Your workers, and the API when no worker that can transcribe is online, or when a transcription has waited past the queue-age setting under routing. |
| `api` | **A speech API** | Every transcription goes to the API. |
Over the API, set it with `PUT /v1/settings/speech` and `{"mode": "api"}`.
`api` and `local_then_api` answer `409 speech_not_connected` until an API
is connected. Transcriptions already queued move to match the new mode.
To stop using the API, choose **Disconnect**, or call
`DELETE /v1/settings/speech/connect`. The mode goes back to `local`.
## What to know [#what-to-know]
- **No spend cap or estimate.** Every transcription sent is billed by the
provider, at its prices. ClipMux doesn't count the cost or stop at a limit.
- **Audio goes in chunks** of at most 24 MiB, about 25 minutes, cut at
segment boundaries without overlap. A word spoken across a boundary can
be split or lost.
- **One at a time.** The server sends one transcription to the API at a
time, so a burst of uploads in `api` mode queues behind it.
- **Timing comes from the provider.** Word times are whatever the API
returns; without word times, a cue holds a sentence.
- **Retries.** Rate limits, timeouts and server errors are retried a few
times, then the transcription goes back to the queue. Any other refusal
fails the track, and the reason shows on it.
- **Private addresses are allowed.** The URL isn't filtered for private
addresses, so a server on your network works.
## Check it works [#check-it-works]
Connect itself is the check: the `transcription` step ran the sample through
the API. Then upload a short video that asks for subtitles in `api` mode,
and open the **Captions & chapters** tab on its page in the dashboard.
- `speech_not_connected` when choosing a mode: connect an API first.
- `credentials` fails: the URL or the key is wrong.
- `transcription` fails: the API refused the audio format or the model, or
doesn't return `verbose_json` with timestamps.
## Next [#next]
- [Transcribe with whisper.cpp](/docs/self-host/captions-and-ai/whisper)
- [Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm)
- [Subtitles and transcripts](/docs/build/captions/subtitles)
---
# Choose an LLM for chapters
Connect Claude or any OpenAI-compatible chat API, including a keyless server on your own network, to title a video's chapters from its transcript.
Source: https://clipmux.com/docs/self-host/captions-and-ai/chapters-llm
ClipMux makes chapters by giving a video's transcript to an LLM, which
splits it into sections and titles each one. You connect the LLM once, as
the owner. Until you do, uploads that ask for chapters get none, and their
chapters track ends `llm_not_connected`.
Two kinds of provider work:
- **Claude**, through Anthropic's own API. The default model is
`claude-opus-5-5`.
- **Any OpenAI-compatible `/chat/completions` API**: OpenAI, Ollama, vLLM,
Groq or OpenRouter. A server on your own network that needs no key works
too.
Every time chapters are made, the transcript's text goes to the LLM
provider you connect, never the video or its audio. Connecting also sends
it a short sample transcript. A server on your own network keeps the text
with you.
## Before you start [#before-you-start]
- Subtitles working, since chapters are made from the transcript. See
[Transcribe with whisper.cpp](/docs/self-host/captions-and-ai/whisper) or
[Use a speech API](/docs/self-host/captions-and-ai/speech-apis).
- For Claude: an Anthropic API key.
- For an OpenAI-compatible API: its base URL, such as
`https://api.openai.com/v1` or `http://ollama.lan:11434/v1`, a model name,
and a key if it needs one.
## Connect an LLM [#connect-an-llm]
### Open the form [#open-the-form]
In the dashboard, open **Captions & AI**. Under **Chapters**, choose
**Connect an LLM**.
### Choose the provider [#choose-the-provider]
Under **LLM provider**, choose **Claude (Anthropic)** or
**OpenAI-compatible**. For an OpenAI-compatible API, enter the
**LLM API URL**.
### Add the key and the model [#add-the-key-and-the-model]
Enter the **LLM API key**; for an OpenAI-compatible server that needs none,
leave it empty. **LLM model** lists the provider's models once the key (for
Claude) or the URL is in. For Claude it lists the current models, newest
first; leave it empty for `claude-opus-5-5`. An OpenAI-compatible API needs
a model.
### Connect [#connect]
Choose **Connect**. ClipMux runs three steps and shows each one:
1. `credentials`: lists the API's models at `{base_url}/models`, or for
Claude, reads the chosen model, which proves the key and the model name.
2. `structured_output`: makes chapters of a fixed three-segment transcript.
An OpenAI-compatible server without strict JSON schemas falls back to
JSON mode, and ClipMux remembers which worked.
3. `saved`: keeps the connection, with its key sealed by the secrets key.
A failed step leaves any earlier connection as it was.
Over the API, the same is `POST /v1/settings/chapters/connect`:
```json
{ "provider": "anthropic", "api_key": "…" }
```
```json
{ "provider": "openai_compatible", "base_url": "http://ollama.lan:11434/v1", "model": "llama3.3" }
```
The key is never returned. `GET /v1/settings/chapters` shows the provider,
URL and model.
To stop, choose **Disconnect**, or call
`DELETE /v1/settings/chapters/connect`. Chapters already made keep playing;
chapters still queued end `llm_not_connected`.
## What to know [#what-to-know]
- **No spend estimate.** Each video's chapters are billed by the provider at
its prices. ClipMux doesn't estimate or cap the cost.
- **A Claude refusal is final.** There is no fallback to another model.
- **Failures retry twice.** A rate limit, an overloaded provider or a network
error is retried after 30 seconds and again after 2 minutes; the third
failure ends the track `llm_unavailable`.
- **The transcript is data, not instructions.** It goes to the model as
delimited text under a strict schema, and every chapter boundary is
checked locally. The worst a hostile transcript can do is name its own
chapters.
- **Private addresses are allowed.** The URL isn't filtered for private
addresses, so Ollama on your network works.
## Check it works [#check-it-works]
Connect itself is the check: the `structured_output` step made chapters of
a sample, and its detail lists their titles. Then upload a short video that
asks for chapters, and open the **Captions & chapters** tab on its page in
the dashboard.
- `credentials` fails: the URL, the key or the model name is wrong.
- `structured_output` fails: the model couldn't return chapters in JSON.
- Chapters end `llm_not_connected`: no LLM was connected when they were
made.
## Next [#next]
- [Chapters](/docs/build/captions/chapters), for your app
- [Use a speech API](/docs/self-host/captions-and-ai/speech-apis)
- [Limitations](/docs/self-host/limitations)
---
# Back up and restore
Back up the database, the uploaded videos and the secrets key, check the backups, and restore them on the same server or a new one.
Source: https://clipmux.com/docs/self-host/operate/backups
A ClipMux install is three things, and they only work together. Postgres
holds every record and every secret, sealed with the secrets key. The
secrets key opens them. The stored videos are encrypted with keys derived
from a secret that the secrets key seals.
ClipMux backs up the first for you, copies the originals of the third, and
leaves the second to you, because a backup can't hold the key that opens it.
Losing the secrets key makes every stored secret unusable, and every
encoded video unplayable. Keep a copy somewhere off the server. See
[the recovery kit](#recovery-kit).
The commands below are for the one-line install, which runs in
`/opt/clipmux`. Run them from that directory. For what to do when something
has already gone wrong, start at
[Disaster recovery](/docs/self-host/operate/disaster-recovery).
## Before you start [#before-you-start]
- Shell access to the server, with Docker Compose.
- Somewhere off the server to keep backups: a bucket at a provider other
than the one holding your videos, so one account can't lose both.
## What is backed up [#what-is-backed-up]
| What | How |
| --- | --- |
| Postgres | serve writes an encrypted dump to the backup target every hour. |
| Uploaded originals | serve copies each source, encrypted, to the same target. See [Uploaded sources](#uploaded-sources). |
| Encoded videos | Not copied. After a lost bucket they are encoded again from the originals. |
| The secrets key and `DATABASE_URL` | Yours to keep: the [recovery kit](#recovery-kit). |
Encoded videos are AES-128 ciphertext, so a copy of them is useless without
the other two. If you want one anyway, snapshot the `data` volume, or turn on
versioning or replication for your buckets at the provider.
## Automatic backups [#automatic-backups]
serve backs up its own database, with nothing to install on the host. Every
backup is a `pg_dump` of ClipMux's schema, encrypted with
[age](https://age-encryption.org) as it is written, so no plaintext reaches
the target or the disk. The server's identity is derived from the secrets
key, so the key and the backups are enough to bring everything back.
Without any setting, serve writes a copy a day to `backups/` in the data
directory and keeps seven days. That sits on the same disk as the database, so
a lost disk takes the backups too, and the dashboard says so. Send them
elsewhere, as below.
With a bucket set, a backup is taken every hour
(`CLIPMUX_BACKUP_INTERVAL`; `0` turns backups off). It is written to
`db/hourly/` as `{time}-{id}.dump.age`, beside a `.json` manifest with its
size, SHA-256, ClipMux version and migration version. The first backup of each
day, week and month is also copied to `db/daily/`, `db/weekly/` and
`db/monthly/`, so a lifecycle rule has something to keep.
```bash
docker compose exec app clipmux admin backup check # can the target be written, read and listed; can it delete?
docker compose exec app clipmux admin backup now # take one now
docker compose exec app clipmux admin backup list # what the target holds
```
Before an upgrade's migrations run, serve (and `clipmux admin`) takes a backup
of the database as it is, listed as kind `pre_migrate`, and doesn't migrate if
it can't. That backup is how you go back after a bad upgrade: stop the app,
install the older release and [restore](#restore) it. A new install has nothing
to back up, and `CLIPMUX_BACKUP_BEFORE_MIGRATE=false` turns it off.
## Set up a backup target [#set-up-a-backup-target]
`CLIPMUX_BACKUP_URL` takes `s3://bucket/prefix?endpoint=…®ion=…` for any
S3-compatible bucket, or `file:///path` for a directory. The best setup is a
bucket whose key can write and list but **not delete**, with object lock and
lifecycle rules that expire old backups. Then ransomware on the server, or a
stolen `.env`, can't erase the backups. ClipMux asks the target what its key
may do: with a key that can't delete it prunes nothing and says the target is
immutable; with a key that can, it prunes hourly backups after 3 days, daily
after 35, weekly after 90 and monthly after 400, and always keeps the newest.
### Backblaze B2 [#backblaze-b2]
This is the setup ClipMux is built around.
### Make a locked bucket [#make-a-locked-bucket]
Create a **private** bucket and turn on **Object Lock**, with a default
retention of 7 days, in compliance mode. For a week after it is written, a
file can't be deleted or changed by anyone, whatever key asks. Note the bucket's S3
endpoint and region, such as `https://s3.us-west-004.backblazeb2.com` and
`us-west-004`.
### Add lifecycle rules [#add-lifecycle-rules]
ClipMux doesn't prune a locked bucket, so the bucket does. (On B2 a delete
through the S3 API only hides a file, which even a key without `deleteFiles`
may do; the lock is what keeps each backup for its retention, and ClipMux
reads it.) Add one rule per prefix, each hiding files after the number of
days shown and deleting them a day later:
| Prefix | Hide after |
| --- | --- |
| `db/hourly/` | 3 days |
| `db/daily/` | 35 days |
| `db/weekly/` | 90 days |
| `db/monthly/` | 400 days |
| `_probe/` | 1 day |
`_probe/` holds the tiny object each backup writes to learn what its key may
do. Leave `sources/` without a rule: those are your originals.
### Make two application keys [#make-two-application-keys]
Both limited to this bucket.
- **For the server:** `listFiles`, `readFiles`, `writeFiles` and
`readBucketRetentions`, and not `deleteFiles`. The server reads too, to
check its own backups, and reads the bucket's lock to know not to prune it.
- **For you, kept off the server:** `listFiles` and `readFiles`. A restore only
reads, so this is the key to keep in your recovery kit.
### Point ClipMux at it [#point-clipmux-at-it]
```bash
# /opt/clipmux/.env
CLIPMUX_BACKUP_URL=s3://my-clipmux-backups/clipmux?endpoint=https://s3.us-west-004.backblazeb2.com®ion=us-west-004
CLIPMUX_BACKUP_ACCESS_KEY_ID=…
CLIPMUX_BACKUP_SECRET_ACCESS_KEY=…
```
Restart with `docker compose up -d --wait`, then check it:
```bash
docker compose exec app clipmux admin backup check
```
It should say writes, reads and lists are ok and that object lock is on: the
target is immutable to this server, and ClipMux prunes nothing. If it says the
lock couldn't be read, the key is missing `readBucketRetentions`.
### Other providers [#other-providers]
- **Cloudflare R2.** The endpoint is
`https://.r2.cloudflarestorage.com`, with region `auto`. An R2
token that can write can also delete, so ClipMux will prune, and the
dashboard will say the key can delete. For protection, add a
[bucket lock](https://developers.cloudflare.com/r2/buckets/bucket-locks/)
rule. Use a different Cloudflare account from your media if you can, or a
different provider.
- **Hetzner Object Storage.** The endpoint is
`https://.your-objectstorage.com`, such as
`fsn1.your-objectstorage.com`, with that location as the region. Check what
the credentials of your project can be limited to; `clipmux admin backup check`
tells you what the key you set may do.
- **AWS S3.** Create the bucket with Object Lock on, and give the server's
IAM user `s3:PutObject`, `s3:GetObject` and `s3:ListBucket` on it, and no
`s3:DeleteObject`. Add lifecycle expiration rules for the prefixes above.
- **A directory.** `file:///path` works for a mounted disk or share. Its key
is the host's own, so it can always delete and ClipMux prunes to the same
ages. A directory on another machine, or a network share, is far better than
one on the same disk.
## Checking backups [#checking-backups]
A backup nobody has restored is a hope, so serve restores the newest one every
week, into a scratch database on the same Postgres server, and drops it again.
It checks that the file is whole (its SHA-256 matches the manifest and it
decrypts), that this install's secrets key opens every secret in it, that the
content keys it needs load, and that each counted table has exactly the rows
the manifest recorded, counted in the snapshot the dump read. The result is
kept with the backup, and a failed check is tried again after six hours. It
needs a database role that may create databases, which the compose stack's
role is; without one it proves the file only, and says so. Run it yourself,
for example after changing the secrets key:
```bash
docker compose exec app clipmux admin backup verify
```
## Uploaded sources [#uploaded-sources]
Encoded videos can be made again from the originals you uploaded, but the
originals can't be made again from anything. So serve also copies each
committed source, encrypted the same way, to `sources/{asset}.age` on the
target, twenty a pass, oldest first. Sources on a PC agent aren't copied
until you upload them, and a source you chose not to keep isn't either. The
encoded files are not copied.
When a bucket is lost, or an account is closed, restore the database, point
the stores at new buckets and run:
```bash
docker compose exec app clipmux admin backup restore-sources --all
```
It copies each missing source back to the store it belongs on and queues a
re-encode through the usual job path, for every asset whose source was
restored or whose encoded files are gone. Playback returns as the re-encodes
finish, which takes hours for a large library and not minutes. Running it
again changes nothing that is already restored; `--asset ID` does one asset.
An asset you deleted after the backup has a tombstone on the target, and is
left alone.
A deleted asset's copy stays on the target for 30 days. Where the backup key
may delete, serve then removes it. Where it can't, the copies stay, and you
can clear them now and then with a key that can delete, used for this one
command:
```bash
docker compose exec \
-e CLIPMUX_BACKUP_ACCESS_KEY_ID=… -e CLIPMUX_BACKUP_SECRET_ACCESS_KEY=… \
app clipmux admin backup prune-sources
```
## The recovery kit [#recovery-kit]
Everything on the target is encrypted to a key derived from the secrets key.
So after losing the server, the backups open only if you still have these,
kept somewhere other than the server:
- `CLIPMUX_SECRETS_KEY`, the `v1:…` line of `.env`, and, after a
[rotation](/docs/self-host/operate/rotate-secrets), every older key whose
backups still exist.
- `POSTGRES_PASSWORD` and the rest of `.env`, which names the target.
- The backup target's read key, from the step above.
- If you set `CLIPMUX_BACKUP_RECIPIENTS`, the private half of that age key.
The simplest kit is a copy of `/opt/clipmux/.env` in a password manager, plus
the read key. Tick the dashboard's **Recovery kit stored off this server**
once you have done it; that is your own word, and nothing checks it. Without
the secrets key, backups can't be opened by anyone, ClipMux included.
`CLIPMUX_BACKUP_RECIPIENTS` adds your own age public key (`age-keygen` makes
one) to every backup, so you can open them without the server's key, with only
the private half kept offline. `CLIPMUX_BACKUP_PING_URL` is fetched after every
successful backup: point a healthchecks.io check at it and you are told when
backups stop.
## Open a backup without ClipMux [#open-a-backup-without-clipmux]
A backup is an `age` file around a standard `pg_dump` archive, so the `age` and
`pg_restore` tools open it. With the server's identity:
```bash
age -d -i <(docker compose exec -T app clipmux admin backup identity) 20261123T101500Z-bak_….dump.age > clipmux.dump
pg_restore --list clipmux.dump
```
Or with your own key, if you set `CLIPMUX_BACKUP_RECIPIENTS`:
```bash
age -d -i my-age-identity.txt 20261123T101500Z-bak_….dump.age > clipmux.dump
```
Sources open the same way: `age -d -i … sources/ast_….age > video.mp4`.
After a secrets-key rotation, keep the previous key (`CLIPMUX_SECRETS_KEY_PREVIOUS`)
until the oldest backup made under it has expired: backups are encrypted to
the key that was current when they were taken.
## In the dashboard [#in-the-dashboard]
**Settings**, **Security**, **Backups** shows the newest backup, whether one
has been proved restorable, whether the backups are off this server and out of
its reach, how many sources are waiting to be copied, and a restore fence if
one is up. **Back up now** asks serve for a backup, which it takes within a
minute. The same facts are on
[the management API](/docs/reference/management-api#backups), and as
[metrics and alerts](/docs/self-host/operate/monitoring).
## Back up by hand [#back-up-by-hand]
Automatic backups cover the database and the sources. If you turn them off
(`CLIPMUX_BACKUP_INTERVAL=0`), or want a copy of your own, dump the database
yourself and keep the secrets key:
```bash
cd /opt/clipmux
docker compose exec -T postgres pg_dump -U clipmux -Fc clipmux > clipmux.dump
```
Copy `clipmux.dump` off the server, and copy the `CLIPMUX_SECRETS_KEY=v1:…`
line from `/opt/clipmux/.env` to a password manager. Do it again whenever you
[rotate the key](/docs/self-host/operate/rotate-secrets). A dump restores with
`clipmux admin restore --file`.
The dump carries analytics and share links too. Viewer counts stay
comparable after a restore, because the analytics key is sealed with the
secrets key. With Cloudflare edge analytics, a restored install pulls only
the last 13 days of edge counts again.
## Restore [#restore]
`clipmux admin restore` replaces the database with a backup from the target.
Stop the app first: it refuses while a serve is running.
```bash
cd /opt/clipmux
docker compose exec app clipmux admin restore --list # what the target holds
docker compose stop app
docker compose run --rm -T --no-deps app admin restore --latest --yes # or --id ID, or --file PATH
docker compose up -d --wait
```
Without `--yes` it only names the backup it would restore. Before it changes
anything it checks that the backup is whole (its size and SHA-256 match the
manifest), that this install's secrets key opens it, that it was taken by a
ClipMux no newer than this one, and that it is of the schema `DATABASE_URL`
uses. It then backs up the database it is about to replace, as a `pre_restore`
backup, so a restore can itself be undone with `restore --id`. It loads the dump
into an emptied schema in one transaction, migrates the result to this version,
and raises the restore fence below.
The database backup holds no videos. Stored files on this server's disk
come back with the `data` volume; files in R2 or S3 buckets are still there, and
the restored database points at them.
`--file PATH` restores a dump you hold: a `.dump.age` copied off the target, or
a plain `pg_dump -Fc` file.
### On a new server [#on-a-new-server]
With only Docker and the `.env` you saved, the installer does all of it:
```bash
mkdir -p /opt/clipmux && cp .env /opt/clipmux/
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --restore
```
The `.env` must hold `POSTGRES_PASSWORD`, `CLIPMUX_SECRETS_KEY` and
`CLIPMUX_BACKUP_URL` (with its access keys, for a bucket). The installer starts
Postgres, restores the latest backup in a one-off container, starts ClipMux and
prints the report below. Then point DNS at the new server. Behind your own
reverse proxy, run the [steps by hand](/docs/self-host/install-options/reverse-proxy#restore-from-a-backup).
Restoring replaces everything in ClipMux's schema, and the decrypted dump
sits in a private directory under the data volume while it loads. Without
ClipMux, `pg_restore --clean --if-exists --no-owner -d clipmux clipmux.dump`
loads a dump you opened with `age`, though it won't clear tables a newer
version added.
## After a restore: the fence [#after-a-restore-the-fence]
Restoring an older database leaves storage holding what the database no
longer knows: videos uploaded since the dump. ClipMux's cleanups would
delete exactly that, so every store carries a marker, `_clipmux/epoch.json`,
with the install's ID and a counter that goes up every five minutes. A store
whose marker belongs to another install, or is ahead of the database's
counter, raises the **restore fence**: until you lift it, serve deletes
nothing from storage and never removes a route record or a signing key it
doesn't know. Playback of what the database does know carries on.
A restored database always fences, even from last night's dump. A new
install pointed at a bucket that another install used is fenced too.
```bash
docker compose exec app clipmux admin restore report
```
The report lists the route records, output prefixes and sources in storage
that the database has no row for. Read it, then lift the fence:
```bash
docker compose exec app clipmux admin restore finish --yes
```
Finishing stamps every store as this install's. After it, serve deletes the
output prefixes and route records the report listed. Nothing else lifts the
fence.
## Check it works [#check-it-works]
At boot, the server checks that its secrets key opens every sealed value in
the database, and that every encoded video's content key version exists. If
either check fails, it refuses to start and its last log line says why:
```bash
docker compose logs --tail 20 app
```
- A secrets key that opens nothing, naming a column: `.env` holds a
different key from the one the dump was sealed with. Put the right one
back.
- A missing content key version: an encoded video uses a content key
secret version the database doesn't hold, so it could never play again.
Check that the dump and the secrets key are the pair you meant.
Once it starts, run the setup test, which uploads, encodes and plays a
sample:
```bash
docker compose exec app clipmux admin setup-test --wait
```
Then play an older video from the dashboard.
## Next [#next]
- [Disaster recovery](/docs/self-host/operate/disaster-recovery)
- [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)
- [Upgrade and uninstall](/docs/self-host/install-options/upgrade-and-uninstall)
- [Security checklist](/docs/self-host/operate/security-checklist)
---
# Disaster recovery
What to do, how long it should take and how to check it worked, for each way a ClipMux server can fail.
Source: https://clipmux.com/docs/self-host/operate/disaster-recovery
Most failures need nothing from you: a crashed process restarts and loses
nothing that was committed. What ClipMux can't survive by itself is losing
state, such as a disk, a bucket or the secrets key. This page is a runbook,
one section per failure. Each says what you will see, what to run, how long it
should take, and how to check it worked.
The times are the ones ClipMux is built to meet, with a 2 vCPU server and a
library of the size a single server runs. Your own depend on the size of your
database and your network, so time a restore on a spare server before you need
one.
Everything below that restores needs the [recovery kit](/docs/self-host/operate/backups#recovery-kit):
your `.env`, with the secrets key, and the backup target's read key. Make it
now, off the server.
## What to expect [#what-to-expect]
| What happens | What you lose | Back in |
| --- | --- | --- |
| [serve crashes or is killed](#serve-crashes) | Nothing | Under 30 seconds, jobs requeue in about 2 minutes |
| [Postgres crashes](#postgres-crashes) | Nothing committed | Under a minute |
| [Reboot or patching](#reboot) | Nothing | About 2 minutes |
| [A bad upgrade or migration](#bad-upgrade) | Whatever happened after the upgrade | 15 minutes or less |
| [The disk or the server is lost](#server-lost) | Changes since the latest usable backup | 30 minutes or less, then DNS |
| [An older database comes back](#older-database) | Nothing: the fence stops deletes | As long as it takes you to read the report |
| [A new install on a used bucket](#used-bucket) | Nothing: the install is fenced | As above |
| [Bucket objects deleted, or the bucket lost](#bucket-lost) | Encoded files, which are made again | Hours, depending on the library |
| [The secrets key is lost](#key-lost) | Everything that depends on it | Only from the recovery kit |
| [The server is down](#server-down) | Nothing | R2 videos keep playing meanwhile |
## serve crashes or is killed [#serve-crashes]
Docker restarts the container within 30 seconds. A job that was running
loses its lease and returns to the queue within about 2 minutes (a 90 second
lease and a 15 second sweep), and the encode starts again. Nothing you
committed is lost: uploads resume, and outputs are only ever added, never
changed.
Check: `docker compose ps` shows `app` as `healthy`, and
`curl https://video.example.com/readyz` answers `ok`.
In the drill, the replacement process became ready in 104 milliseconds and
the interrupted encode was requeued after 90 seconds.
## Postgres crashes [#postgres-crashes]
Postgres restarts and replays its log, in under a minute. serve answers
`503` on `/readyz` until the database does, then carries on. Nothing that
was committed is lost.
Check: `docker compose ps` shows `postgres` as `healthy`, and `/readyz` answers
`ok`. If Postgres keeps failing to start, look at
`docker compose logs --tail 50 postgres`; a full disk is a common reason, and
`clipmux_data_free_bytes` in [metrics](/docs/self-host/operate/monitoring) warns
before it happens.
In the drill, PostgreSQL 18 restarted in 1.6 seconds and the committed test
row was intact.
## A reboot, or patching the host [#reboot]
Reboot in a quiet window. Every container comes back by itself, in about
2 minutes. With [Cloudflare delivery](/docs/self-host/delivery/cloudflare),
playback of videos in R2 is unaffected throughout, because the Worker serves
them. With built-in delivery, playback pauses with the server.
Check: `docker compose ps`, then play a video.
The disposable VM was ready from an off-host probe 36 seconds after reboot.
## A bad upgrade or migration [#bad-upgrade]
Before any migration runs, serve backs the database up as it is, as a
`pre_migrate` backup, and doesn't migrate if it can't. That backup is your way
back. Stop the app, put the older release in `.env`, and restore it with that
release:
```bash
cd /opt/clipmux
docker compose stop app
docker compose run --rm -T --no-deps app admin backup list # find the pre_migrate backup before the upgrade
sed -i 's/^CLIPMUX_VERSION=.*/CLIPMUX_VERSION=v1.0.0/' .env # the release you came from
docker compose pull app
docker compose run --rm -T --no-deps app admin restore --id bak_… --yes
docker compose up -d --wait
```
The target is 15 minutes or less. Anything uploaded between the upgrade and the
rollback is not in the backup, but its files are still in storage, and the
restore's report lists them. If the upgrade only added a migration and you
would rather keep the data, [roll the database back](/docs/self-host/install-options/upgrade-and-uninstall#roll-back-past-a-migration)
instead.
Check: `docker compose exec app clipmux admin migrate status` shows the older
release's migration as the newest, and the setup test passes:
```bash
docker compose exec app clipmux admin setup-test --wait
```
## The disk or the server is lost [#server-lost]
You need a new server with Docker, and your recovery kit. On the new server,
with the saved `.env`:
```bash
mkdir -p /opt/clipmux && cp .env /opt/clipmux/
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --restore
```
The installer starts Postgres, restores the latest backup, starts ClipMux and
prints the restore report. Then point DNS at the new server. The target is
30 minutes through first playback, including pulling the images. The amount
of data lost depends on the age of the newest successful backup. For an
off-site target, ClipMux schedules backups hourly by default. Allow time
for the dump and upload when choosing an interval for your recovery point.
The 24 November 2026 drill on a 2 vCPU amd64 VM reached decrypted playback
in 72 seconds from installer start. Pulling the images took 34 seconds and
restoring the database from Backblaze B2 took 3 seconds. The restore fence
preserved the route record, source and output of a newer R2 video.
In the production drill, a 14-minute backup schedule produced a maximum
recovery-point age of 14 minutes and 2 seconds across two verified backups.
The restore reads only from the backup target, so the read key is enough. The
server then tries to back up with the same key and can't write; put the
write key back in `.env` and run `docker compose up -d`.
To rehearse with a live install's backup, use `--restore-only` on a spare
server with an empty Postgres and a copy of the recovery kit that uses the
read-only backup key. The installer stops after restoring the database and
raising the fence. With `serve` stopped, the copy cannot run pending jobs,
send webhooks or publish routes. Run the checks with one-off containers
and keep the original server online.
```bash
curl -fsSL https://clipmux.com/install.sh | sudo sh -s -- --restore-only
cd /opt/clipmux
docker compose run --rm --no-deps app admin restore report
docker compose run --rm --no-deps app admin backup verify --id bak_…
```
Use the backup ID printed by the installer. Run the full playback rehearsal
with a disposable install and media bucket.
Check:
1. `docker compose ps` shows everything `healthy`, and `/readyz` answers `ok`.
2. `docker compose exec app clipmux admin restore report` lists what storage
holds that the backup doesn't know, such as videos uploaded after it. Read
it, then `docker compose exec app clipmux admin restore finish --yes`.
3. Play a video uploaded before the backup.
4. `docker compose exec app clipmux admin backup verify` passes.
Videos that were on the lost server's own disk are gone with it, and come
back as in [a lost bucket](#bucket-lost). Videos in R2 or S3 are still there.
## An older database comes back [#older-database]
Restoring an older dump, or rolling a server snapshot back, leaves storage
holding videos the database has never heard of, and the cleanups that keep
storage tidy would delete exactly those. ClipMux notices: every store carries
a marker with the install's ID and a counter, and a database that is behind
its stores raises the **restore fence**. While it is up, nothing is deleted
from storage and no route record or signing key is removed. Playback of what
the database does know carries on.
```bash
docker compose exec app clipmux admin restore report # what storage holds that the database doesn't
docker compose exec app clipmux admin restore finish --yes
```
Check: the dashboard's Backups card, and `clipmux_restore_fenced` in
[metrics](/docs/self-host/operate/monitoring), show the fence while it is up
and clear once you finish. `finish` lets the cleanups run again, so read the
report first: what it lists, they then delete.
## A new install on a used bucket [#used-bucket]
A fresh install pointed at a bucket another install used finds a marker with
another install's ID, and is fenced at once. Without that, its first cleanup
would take everything there for orphans.
Check `clipmux admin restore report`. If the bucket is meant to belong to
the install it came from, point this one at that install's database, with
`--restore`. If you really mean to start over in this bucket, only then run
`restore finish --yes`, knowing it lets the cleanups delete what is listed.
## Bucket objects deleted, or the bucket lost [#bucket-lost]
Encoded videos can be made again; the originals are on the backup target. If
the files are gone but the bucket is still yours:
1. Make the bucket again under the same name, in the same account, in your
provider's console.
2. If the keys went with it, give the storage new keys on the **Storage**
page, or with `PUT /v1/storage/{id}/credentials`.
3. Copy the originals back and queue the re-encodes:
```bash
docker compose exec app clipmux admin backup restore-sources --all
```
4. Watch the **Jobs** page. Route records come back by themselves, within
about 15 minutes of serve's next reconcile.
Playback returns video by video as the encodes finish. Expect hours for a
large library, not minutes. A source that was never copied, such as one on a PC
agent, or encoded with the source not kept, can't come back: the command lists
them.
Check: `restore-sources` prints how many sources it restored and how many
re-encodes it queued, and running it again prints zero of each. Play a video
once its job succeeds.
In the drill, a source restored from B2 in 2 seconds with the original
SHA-256 hash. The replacement output played after 39 seconds, and a second
run restored and queued zero files.
A lost Cloudflare or cloud account is harder: a store's endpoint names the
account, and a store's endpoint and bucket can't be changed once it is added, so
recovering into a different account isn't supported yet. The sources are safe
on the backup target meanwhile.
## The secrets key is lost [#key-lost]
This can't be recovered, by design: every secret in Postgres is sealed with
it, every backup is encrypted to a key derived from it, and without it the
database's secrets and the stored videos can't be opened by anyone. Only a
copy from your recovery kit helps. Put it back as `CLIPMUX_SECRETS_KEY` and
run the restore as above.
If a [rotation](/docs/self-host/operate/rotate-secrets) came after the backup
you are restoring, you need the key that was current then too, as
`CLIPMUX_SECRETS_KEY_PREVIOUS`. The `.json` manifest beside each backup on the
target names the key version it was encrypted to. If you set `CLIPMUX_BACKUP_RECIPIENTS`, your own age
key opens the backups without it, though the secrets inside Postgres still
need the secrets key.
## The server is down [#server-down]
With [Cloudflare delivery](/docs/self-host/delivery/cloudflare), the Worker
serves videos from R2 on its own, so playback continues while the server is
down. Uploads, the dashboard, the API and new encodes stop, and jobs wait.
Signing new playback tokens needs your backend, not ClipMux, so players with a
valid token keep working until it expires.
Check from outside the server, since a monitor on the same host can't report
the host going down. Probe `https://video.example.com/readyz`, and one
segment of a known public video on the media hostname, which should play
without the origin. See [Monitoring](/docs/self-host/operate/monitoring).
Off-host probes decoded audio and video during a 66-second origin outage
in the drill.
## Practise [#practise]
A restore you have never run is a hope too. On a spare server, run
`install.sh --restore` with a copy of your `.env` and the read key, check that
a video plays, and note how long it took. Do it after changing the target or
the secrets key, and once a quarter.
## Next [#next]
- [Back up and restore](/docs/self-host/operate/backups)
- [Monitoring](/docs/self-host/operate/monitoring)
- [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)
---
# Monitoring
Watch a ClipMux server with its health checks, Prometheus metrics, ready-made alerts and structured logs.
Source: https://clipmux.com/docs/self-host/operate/monitoring
A ClipMux server tells you how it's doing in three ways: two health checks
for a load balancer or uptime monitor, Prometheus metrics on a listener of
their own, and one structured log line per request. The repository ships
alert rules for the metrics.
## Before you start [#before-you-start]
- A running server. The one-line install already turns on metrics and JSON
logs.
- For metrics: Prometheus, or anything that scrapes the Prometheus text
format, on a network that can reach the metrics listener.
## Health checks [#health-checks]
| Path | Answers `200 ok` when |
| --- | --- |
| `/healthz` | The process is up. |
| `/readyz` | Postgres answers within 2 seconds and the server isn't shutting down. Otherwise `503`, with `database unavailable` or `draining`. |
Both are on the main listener, so `https://video.example.com/readyz` works
through Caddy. The compose files declare the Docker health check, which runs
`clipmux healthcheck`; the image has none, because the same image runs the
cloud GPU workers.
## Metrics [#metrics]
Set `CLIPMUX_METRICS_ADDR` to a `host:port` and the server serves `/metrics`
there, on a listener of its own with no authentication. Keep it off the
internet.
The one-line install sets it to `:9090` and only exposes the port inside the
Compose network; it's never published on the host. Run Prometheus on that
network and scrape `app:9090` with the job name `clipmux`. Setting
`CLIPMUX_PPROF=true` adds Go's profiler on the same listener.
### What it reports [#what-it-reports]
**Requests and delivery**
- `clipmux_http_requests_total` by `route` and `code`
- `clipmux_http_request_duration_seconds` by `route`, long-polls left out
- `clipmux_http_in_flight`
- `clipmux_delivery_bytes_total` by playback policy
- `clipmux_delivery_cache_lookups_total` by `table` and `result` (`hit` or
`miss`)
**Jobs and workers**
- `clipmux_jobs`: queued and running jobs, by `kind`, `status`, `routed_to`
and `route_reason`
- `clipmux_job_queue_oldest_seconds` by `kind`
- `clipmux_attempts_finished_total` by `executor`, `result` and `error_code`
- `clipmux_workers_online` by `kind`: PC agents and the built-in worker seen
in the last minute
- `clipmux_dispatches`: Modal and RunPod machines, by `provider` and `status`
**Background loops and the outbox**
- `clipmux_leader`: 1 on the replica that runs the background loops
- `clipmux_sweeper_pass_seconds`, `clipmux_sweeper_errors_total`,
`clipmux_sweeper_panics_total` and
`clipmux_sweeper_last_success_timestamp_seconds`, by loop
- `clipmux_outbox_pending` and `clipmux_outbox_oldest_pending_seconds` by
`kind`: route publications, webhooks, wakes and stops not yet done
- `clipmux_webhook_deliveries` by `status`
**Analytics and speech**
- `clipmux_analytics_flush_rows_total`: rows the analytics flushes wrote
- `clipmux_analytics_dropped_total`: viewer keys dropped because more than
100,000 piled up between flushes
- `clipmux_speech_api_audio_seconds_total`: seconds of audio sent to a
[speech API](/docs/self-host/captions-and-ai/speech-apis)
**Backups and recovery**
- `clipmux_backup_last_success_timestamp_seconds`: when the newest backup
was written, `0` if none
- `clipmux_backup_last_verified_timestamp_seconds`: when a backup last passed
its [restore check](/docs/self-host/operate/backups), `0` if none has
- `clipmux_backup_verify_failed`: `1` if the newest check failed
- `clipmux_backup_interval_seconds`: how often backups are taken, `0` when
they are off
- `clipmux_backup_last_bytes`: size of the newest backup, as stored
- `clipmux_backup_sources_pending`: committed sources not yet copied to the
backup target
- `clipmux_restore_fenced`: `1` while the restore fence stops storage deletes
- `clipmux_db_size_bytes`: size of the Postgres database
- `clipmux_data_free_bytes` and `clipmux_data_total_bytes`: the disk holding
the data directory
**Database pool and process**
- `clipmux_db_pool_acquired_conns`, `clipmux_db_pool_idle_conns`,
`clipmux_db_pool_max_conns`, `clipmux_db_pool_acquire_wait_seconds_total`
and `clipmux_db_pool_empty_acquires_total`
- `clipmux_build_info` by `version`, `clipmux_process_start_time_seconds`,
`clipmux_go_goroutines` and `clipmux_go_heap_bytes`
### Alerts [#alerts]
Load
[`deploy/prometheus/alerts.yml`](https://github.com/visheshgubrani/clipmux/blob/main/deploy/prometheus/alerts.yml)
from the repository into Prometheus. It alerts when:
- the server stops answering its metrics listener;
- no replica runs the background loops;
- more than 2% of requests answer 5xx;
- a background loop keeps failing, or panics;
- outbox rows other than webhooks have been pending for over an hour;
- a job has waited over 30 minutes;
- jobs are queued and no worker has been seen in the last minute;
- webhook deliveries gave up;
- the Postgres pool is more than 90% used;
- no backup has been written for twice the backup interval;
- the newest backup failed its restore check, or none has passed one in
8 days;
- the restore fence is up;
- under 10% of the disk holding the data directory is free.
The same file records the install's service levels as series, in a group
named `clipmux-slo`: `clipmux:http_availability:ratio_rate5m` and
`…ratio_rate1h` (the share of requests that didn't answer 5xx), and
`clipmux:http_request_duration_seconds:p95_rate5m` and `…p95_rate1h` (the 95th
percentile of request time). Chart them, or alert on a burn rate of your own.
## Logs [#logs]
The server logs to standard output.
- `CLIPMUX_LOG_FORMAT` is `text` (the default) or `json`, one object per
line. The one-line install uses `json`, and Docker rotates the log at 5
files of 50 MB.
- `CLIPMUX_LOG_LEVEL` is `debug`, `info` (the default), `warn` or `error`.
Every request logs one `http request` line with its method, route pattern,
path, status, bytes, duration and client address. Successful playback,
storage, worker and health-check requests log at `debug`, so they stay out
of the way at `info`; any 4xx logs at `info` and any 5xx at `warn`.
Each request has an ID, logged as `request_id` and sent back in the
`X-Request-Id` header. When someone reports an error with that ID, it finds
the request's line and any error logged for it. The server takes an incoming
`X-Request-Id` only from a proxy named in `CLIPMUX_TRUSTED_PROXIES`.
Credentials are redacted before anything is written, whatever logged them:
API, agent and dispatch keys, webhook secrets, any JWT, the playback token
in a `/v/{token}/` path, a share link's secret, pairing codes, and URL query
strings, which may carry signatures. Request lines never include the query,
the `Referer` or the `Authorization` header.
```bash
cd /opt/clipmux
docker compose logs app | grep req_…
```
## Check it works [#check-it-works]
```bash
curl -s https://video.example.com/readyz
```
- `ok`: the server and Postgres are up.
- `database unavailable`: the server can't reach Postgres.
- `draining`: the server is shutting down.
For metrics, Prometheus's targets page shows the `clipmux` job as up. If
it's down, check that `CLIPMUX_METRICS_ADDR` is set and that Prometheus runs
on the Compose network.
## Next [#next]
- [Troubleshooting](/docs/self-host/operate/troubleshooting)
- [Retention](/docs/self-host/operate/retention)
- [Security checklist](/docs/self-host/operate/security-checklist)
---
# Retention
What ClipMux keeps, for how long, and how to prune it by hand.
Source: https://clipmux.com/docs/self-host/operate/retention
Every hour, the server deletes what nothing can use any more: old rows in
Postgres, and stored files no video plays from. Each window follows from
another rule, such as how far back `clipmux listen --since` reaches, so they
are fixed rather than settings. Nothing here deletes a video you haven't
deleted.
## What's kept, and for how long [#whats-kept-and-for-how-long]
| What | Kept for |
| --- | --- |
| Retired outputs, after a re-encode | The longer of 7 days and the maximum token lifetime, plus an hour, so a viewer mid-session finishes first |
| Files of a failed or replaced encoding attempt | 30 minutes |
| Stored files under an output that its manifest doesn't list | Checked 16 minutes after the output is committed, then deleted |
| Output folders no record accounts for | Swept continuously, 500 videos an hour |
| This server's disk: staging files and abandoned multipart uploads | 24 hours and 7 days |
| Idempotency keys | 24 hours |
| Dashboard sessions | Until they expire, or after 7 days idle |
| Pairing codes, expired or used | 24 hours |
| Webhook deliveries and events, which `GET /v1/events` and `clipmux listen --since` read | 30 days after they finish |
| Other finished outbox rows | 7 days |
| Setup tests | The newest 20 |
| Analytics, hourly, for the 24-hour range | 14 days |
| Analytics, daily, and viewer keys | 180 days. There are no lifetime totals. |
| Share links | Kept, with their state. An expired link's playback ID is revoked within a minute. |
| Jobs, attempts and dispatches | Kept, as history and spend |
Route publications, key publications and machine stops are never given up
on, because giving up would leave a revocation unpublished or a paid machine
running.
On R2 or S3, a multipart upload whose abort failed is left to a lifecycle
rule on the bucket. Connecting a bucket doesn't set one; add it at your
provider.
## Prune by hand [#prune-by-hand]
`clipmux admin prune` runs the same deletion now and prints what went.
```bash
cd /opt/clipmux
docker compose exec app clipmux admin prune --dry-run
```
| Flag | What it does |
| --- | --- |
| `--dry-run` | Counts what would go, inside a transaction it rolls back, so the counts are exact and nothing changes. |
| `--files` | Also deletes stored files past their windows: retired outputs, replaced attempts' files, orphaned output folders, and this server's disk's leftovers. |
`clipmux admin outbox` lists route publications, wakes and stops still
pending after an hour. `clipmux admin outbox --retry ID` makes one due at
once.
## Check it works [#check-it-works]
`clipmux admin prune --dry-run` counts what the next hourly pass would
delete. On a server that has run for a while, the counts stay small. If they
keep growing, the passes are failing: the `retention` and `file_retention`
loops report errors in the log and in `clipmux_sweeper_errors_total` (see
[Monitoring](/docs/self-host/operate/monitoring)).
## Next [#next]
- [Back up and restore](/docs/self-host/operate/backups)
- [Limits and defaults](/docs/reference/limits)
- [Monitoring](/docs/self-host/operate/monitoring)
---
# Rotate keys and secrets
Replace each key and secret ClipMux uses without stopping playback, and what to do when one leaks.
Source: https://clipmux.com/docs/self-host/operate/rotate-secrets
Every key ClipMux issues or holds can be replaced while the server keeps
running, and in most cases while viewers keep watching. This page covers
each one, in the order you're likely to need them.
The commands below are for the one-line install, run from `/opt/clipmux`,
where `clipmux admin` runs inside the app container:
```bash
cd /opt/clipmux
docker compose exec app clipmux admin list-keys --app my-app
```
## Before you start [#before-you-start]
- The owner's dashboard sign-in, and shell access to the server.
- Somewhere to put each new secret: your app's environment, your webhook
receiver, or your offline backup.
## API keys [#api-keys]
1. Create a new key: in the dashboard, open **Apps & API**, choose the app,
and on **API keys** choose **Create key**. It's shown once.
2. Put it in your app's backend as `CLIPMUX_API_KEY` and deploy.
3. Revoke the old one: **Revoke** next to it, or
`clipmux admin revoke-key cmx_…`. It stops working at once.
## Signing keys [#signing-keys]
```bash
docker compose exec app clipmux admin rotate-signing-key --app my-app
```
This creates a new signing key and prints it once. The app's other keys are
retired when the longest token they may have signed runs out, so viewers
mid-session finish. Meanwhile, switch your backend's `CLIPMUX_SIGNING_KID`
and `CLIPMUX_SIGNING_KEY` to the new key.
**Revoke** on the app's **Signing keys** tab, or `clipmux admin revoke-key`
with the key's `kid`, ends a key at once: every token it signed stops
playing. Use that for a leaked key, not a routine rotation.
## Webhook secrets [#webhook-secrets]
Rotating takes two steps, so your receiver never sees a delivery it can't
verify:
1. On the app's **Webhooks** tab, choose **Rotate secret**. The new secret is
shown once, and deliveries stay signed with the old one.
2. Give your receiver the new secret and deploy it.
3. Choose **Activate new secret**. Deliveries are signed with it from the
next try.
Over the API, the steps are `POST /v1/webhook-endpoints/{id}/secret` and
`POST /v1/webhook-endpoints/{id}/secret/activate`. See
[Retries, redelivery and secret rotation](/docs/build/webhooks/retries).
## The content key secret [#the-content-key-secret]
The content key secret is what every video's encryption key is derived
from. In the dashboard, open **Settings**, and under
**Content encryption key** choose **Rotate key**. Or call
`POST /v1/content-keys/rotate` as the owner.
- New encodes use the new version. Existing videos keep theirs and keep
playing. To move a video to the new version, re-encode it.
- With [Cloudflare delivery](/docs/self-host/delivery/cloudflare), the
rotation needs a Cloudflare token, the same kind Connect uses. ClipMux
redeploys the Worker with the new version before any video uses it. If
the redeploy fails, the call answers `502` with the steps, and the new
version stays unused; rotating again retries. Without a token, it answers
`409 cloudflare_token_required`.
## The secrets key [#the-secrets-key]
The secrets key seals every secret ClipMux keeps in Postgres. It's
`CLIPMUX_SECRETS_KEY`, written as `v1:` and 64 hex digits; the one-line
install keeps it in `/opt/clipmux/.env`.
### Make a new key with the next version [#make-a-new-key-with-the-next-version]
```bash
echo "v2:$(openssl rand -hex 32)"
```
### Give serve both keys [#give-serve-both-keys]
In `.env`, move the old value to `CLIPMUX_SECRETS_KEY_PREVIOUS` and put the
new one in `CLIPMUX_SECRETS_KEY`. Then restart: `docker compose up -d --wait`.
### Reseal [#reseal]
```bash
docker compose exec app clipmux admin reseal-secrets
```
It reseals every stored secret with the new key, and ends by saying
`CLIPMUX_SECRETS_KEY_PREVIOUS` can go.
### Drop the previous key [#drop-the-previous-key]
Remove `CLIPMUX_SECRETS_KEY_PREVIOUS` from `.env` and restart again. Then
[back up](/docs/self-host/operate/backups) the new key.
Keep the old key too, in your [recovery kit](/docs/self-host/operate/backups#recovery-kit),
until the oldest backup made under it has expired: each backup is encrypted to
the key that was current when it was taken, and the old key is the only thing
that opens it.
serve refuses to start if a sealed value opens with neither key, and names
its column, so a mistake here stops the server rather than losing data.
## Provider credentials [#provider-credentials]
| Credential | How to replace it |
| --- | --- |
| Cloudflare delivery token | **Delivery**, **Connect again**, with a new token. R2's credentials derive from the token, so revoking the old one cuts off storage until you do. |
| Edge analytics token | **Replace token** in the **Edge analytics** card. |
| An R2 bucket added with a token | **Storage**, **Add R2 bucket** with the same bucket and a new token renews its keys. |
| S3 storage keys | **Rotate keys** on the bucket in **Storage**, or `PUT /v1/storage/{id}/credentials`. The old keys work until the new ones pass the checks. |
| Modal or RunPod | Connect the provider again on **Encoding**; it replaces the key. |
| Speech API or chapters LLM key | Connect again on **Captions & AI**. A failed connect keeps the old connection. |
## When a key leaks [#when-a-key-leaks]
1. Revoke it at once: `clipmux admin revoke-key ID` for an API key or a
signing key, or the dashboard's **Revoke**.
2. Rotate whatever it could reach.
3. For a leaked content key secret, rotate it and re-encode the affected
videos.
4. For a stolen Cloudflare token, revoke it in Cloudflare and rotate the
content key secret: a token that can deploy a Worker can read Worker
secrets.
## Check it works [#check-it-works]
- `clipmux admin list-keys --app my-app` shows the app's API and signing
keys, with which are retired or revoked.
- After a webhook rotation, the endpoint's deliveries on the **Webhooks**
tab keep succeeding.
- After rotating the secrets key, the server starts without the previous
key, and `clipmux admin setup-test --wait` passes.
## Next [#next]
- [Back up and restore](/docs/self-host/operate/backups)
- [Security checklist](/docs/self-host/operate/security-checklist)
- [Security model](/docs/self-host/security-model)
---
# Security checklist
The settings to check before a ClipMux server faces real users and real videos.
Source: https://clipmux.com/docs/self-host/operate/security-checklist
Run through this list before you put a ClipMux server in front of real users,
and again after a major change. Each item links to where it's explained.
## Before you start [#before-you-start]
- A running server, with the owner account created.
- Shell access to the server.
## The checklist [#the-checklist]
- [ ] **Playback is on its own domain.** The media URL is on a different
registrable domain from the public URL, so a hostile stored file
can't reach dashboard cookies. See
[Built-in delivery](/docs/self-host/delivery/built-in).
- [ ] **Only your proxy is trusted.** `CLIPMUX_TRUSTED_PROXIES` names only
Caddy's network. The one-line install's default covers Docker's
private ranges. Rate limits, sign-in limits and request IDs depend
on it.
- [ ] **The metrics port isn't public.** The one-line install only exposes
it inside the Compose network. See
[Monitoring](/docs/self-host/operate/monitoring).
- [ ] **Two-factor sign-in is on.** Turn it on under **Settings**, in
**Two-factor sign-in**, and store the recovery codes offline. A
locked-out owner runs `clipmux admin reset-password` and
`clipmux admin reset-totp` on the server.
- [ ] **Backups are off this server, and you hold the recovery kit.**
`CLIPMUX_BACKUP_URL` points at a bucket at another provider, with a
key that can't delete, and the secrets key and `.env` are stored
somewhere other than the server. The dashboard's Backups card shows
each. See [Back up and restore](/docs/self-host/operate/backups) and
[Disaster recovery](/docs/self-host/operate/disaster-recovery).
- [ ] **PC agents run sandboxed.** `clipmux worker doctor` on each PC shows
the sandbox, and `GET /v1/agents` reports `sandboxed` for each agent.
An unsandboxed agent takes only its own jobs and the owner's uploads.
- [ ] **One server, behind Caddy.** Rate limits are kept per process, so run
one serve replica.
- [ ] **Share links go one per person or group,** so one can be revoked
without the others. Anyone holding a link can watch until it expires
or is revoked. See [Share links](/docs/build/play/share-links).
- [ ] **Owner-set URLs point where you mean.** Webhook endpoints, the speech
API and the chapters LLM aren't filtered for private addresses, by
design. Only the owner can set them.
## Check it works [#check-it-works]
Run the setup test after you change any of the above:
```bash
cd /opt/clipmux
docker compose exec app clipmux admin setup-test --wait
```
It exits 1 unless every check passes, and prints each one.
## Next [#next]
- [Security model](/docs/self-host/security-model)
- [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)
- [Limitations](/docs/self-host/limitations)
---
# Troubleshoot the server
What to look at when a ClipMux server misbehaves, from a server that won't start to playback that fails at the edge.
Source: https://clipmux.com/docs/self-host/operate/troubleshooting
This page is for the person running the server. If you're building an app
against ClipMux and an API call fails, start with
[Troubleshooting for apps](/docs/build/going-live/troubleshooting) instead.
The commands below are for the one-line install, run from `/opt/clipmux`.
## Before you start [#before-you-start]
- Shell access to the server, and the owner's dashboard sign-in.
- The request ID, if someone reports an error: it's in the `X-Request-Id`
response header, and every log line for that request carries it as
`request_id`.
## Three commands to start with [#three-commands-to-start-with]
```bash
cd /opt/clipmux
docker compose logs --tail 50 app # the server's last lines
docker compose exec app clipmux admin setup-test --wait # the whole path, end to end
docker compose exec app clipmux admin outbox # side effects stuck for over an hour
```
- `setup-test --wait` puts a sample through upload, encoding, encryption and
playback on the configured path, prints each check, and exits 1 unless
they all pass.
- `outbox` lists route publications, key publications, wakes and stops
still pending after an hour. They're retried forever;
`clipmux admin outbox --retry ID` makes one due at once.
- On a PC agent, `clipmux worker doctor` checks the connection to the
server and its key, then ffmpeg and Shaka Packager, the sandbox, the
encoders, the scratch disk and speech, in that order. The first ✗ is the
one to fix.
## Symptoms [#symptoms]
| Symptom | Look at |
| --- | --- |
| The server won't start | The last log line: `schema_newer` (the database was migrated by a newer ClipMux), a secrets key that opens nothing, a missing content key version, or a variable that doesn't parse, named. |
| Uploads stay processing | **Jobs** in the dashboard shows where each job was routed and why. `clipmux_workers_online` says whether any worker has been seen in the last minute. The built-in worker's lines are in the server's log. |
| A job waits with `no_fallback` or `fallback_offline` | The primary executor is offline and no fallback can take it. See [Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits). |
| A job waits with `fallback_refused` | An earlier attempt failed in a way that may be the file's fault, so the job waits for the primary rather than reach a paid machine. |
| Subtitles never appear | Whether a worker can transcribe: its log says which speech backend it chose, or why it won't. See [Transcribe with whisper.cpp](/docs/self-host/captions-and-ai/whisper). |
| Chapters end `llm_not_connected` | No LLM was connected when they were made. See [Choose an LLM for chapters](/docs/self-host/captions-and-ai/chapters-llm). |
| An app gets `429` | The `Retry-After` header; the limits are in [Limits and defaults](/docs/reference/limits). |
| A webhook stopped arriving | The endpoint's deliveries, on the app's **Webhooks** tab or `GET /v1/webhook-endpoints/{id}/deliveries`. After 5 failures in a row the endpoint is skipped for a minute, doubling up to an hour. A delivery that gave up can be redelivered. |
| Playback `404`s at the edge after a change | `clipmux admin outbox`: a route publication that keeps failing. |
| Delivery says "R2 refuses the stored credentials" | The Cloudflare token was revoked or rolled. **Connect again** with a new one. |
| Analytics misses Cloudflare playback | The **Edge analytics** card on **Delivery**: whether a token is connected, the last pull and its error. `collecting.edge` in `GET /v1/analytics`. |
| Analytics shows no unique viewers | Your app's tokens carry no `vid`. Previews and posters never count. |
| A share link doesn't work | The link was revoked or expired, its video deleted, or its app disabled. The **Sharing** tab on the video's page shows each link's state. |
| The dashboard shows a 5xx | The log line with the same `request_id`, and any error logged for it. |
## Get more detail [#get-more-detail]
Set `CLIPMUX_LOG_LEVEL=debug` to log successful playback, storage and worker
requests too. With the one-line install, the app's environment is set in
`compose.yml`; add the variable through a `compose.override.yml` beside it,
restart, and remove it when you're done, since debug is verbose.
## Check it works [#check-it-works]
After a fix, run `clipmux admin setup-test --wait` again. Exit code `0` and
every check passing means upload, encoding, encryption and playback work on
the configured path.
## Next [#next]
- [Monitoring](/docs/self-host/operate/monitoring)
- [Retention](/docs/self-host/operate/retention)
- [Limitations](/docs/self-host/limitations)
---
# Security model
The threats ClipMux is built against and the controls that answer each one.
Source: https://clipmux.com/docs/self-host/security-model
ClipMux treats every uploaded file as hostile and assumes any single secret
can leak. ffmpeg parses untrusted input, and in ClipMux it can run beside the
database or on someone's PC, so the design keeps credentials away from the
machines that touch media, checks every playback request, and keeps keys out
of storage.
This page summarizes the threats and the controls. The full table, with the
reasoning behind each control, is in the
[architecture document](https://github.com/visheshgubrani/clipmux/blob/main/docs/architecture.md)
on GitHub.
## Workers hold no storage credentials [#workers-hold-no-storage-credentials]
A worker, whether the built-in one, a PC or a Modal or RunPod machine, never
gets storage keys or database access. For each attempt it gets an attempt
token and signed URLs: it downloads the source from one URL and uploads each
encoded file to a URL signed for that path. The server checks the file names
against a path grammar when it signs, and checks the playlists when the
worker commits. A stolen worker key reaches only the jobs that worker could
claim, and the owner can revoke it at once.
## Media tools run sandboxed [#media-tools-run-sandboxed]
Every ffmpeg, ffprobe, Shaka Packager and whisper.cpp process runs inside a
sandbox:
- **No network.** A seccomp filter makes `socket()` fail, and also refuses
ptrace, bpf, io_uring and the calls that make new namespaces.
- **Landlock**, where the kernel has it: read-only system paths, and write
access to one work directory only. The built-in worker refuses to start
without Landlock unless you set `CLIPMUX_UNSANDBOXED_WORKER`.
- **Resource limits** on memory, CPU seconds, file size and open files, and
no core dumps.
- **An empty environment**, with no secrets. The packager gets the one
output's content key it needs, in a file.
- **An allowlist of input formats** that excludes HLS playlists and concat
files, which could otherwise pull local files into an output.
- **`no_new_privs`**, so nothing it runs can gain privileges.
The tools run at `SCHED_IDLE` priority, so encoding gets only the CPU the API
leaves. That's a priority, not a quota: to cap the CPU, set a limit on the
container. On macOS and Windows, where the Linux sandbox doesn't apply, a PC
agent runs in Docker, WSL2 or a VM; an agent without a sandbox takes only its
own jobs and the owner's uploads.
## Playback needs a token, and routes default to deny [#playback-needs-a-token-and-routes-default-to-deny]
A private video plays only with a short ES256 JWT that your app signs. On
every request, delivery checks the signature, the key's app, the playback
ID, the audience and the lifetime. A playback ID with no route is refused,
and a signed ID never plays without its token. Delivery serves only the
files an output's manifest lists, with a `Content-Type` from an extension
allowlist and `nosniff`. See [Built-in delivery](/docs/self-host/delivery/built-in).
## Keys are derived at delivery [#keys-are-derived-at-delivery]
Every output is encrypted with AES-128. Its key is derived when a player asks
for it, from the content key secret, the video and the output, and handed
only to a request that passes the same checks as its segments. No key is
written to storage, so a leaked bucket or a copied disk exposes no playable
video. Encryption is deterrence, not DRM: anyone with a valid token can
fetch the key. See [What encryption does and doesn't do](/docs/build/concepts/encryption).
## The owner signs in with two factors [#the-owner-signs-in-with-two-factors]
The dashboard supports two-factor sign-in with an authenticator app and ten
single-use recovery codes. Sign-in failures are limited per address. On first
boot, creating the owner account needs a setup token printed to the server's
log, so nobody else can claim the server first.
## Secrets are sealed with a key outside Postgres [#secrets-are-sealed-with-a-key-outside-postgres]
API keys are stored as hashes. Everything ClipMux must be able to read back,
such as provider credentials, the content key secret, the internal signing
key, webhook secrets and speech and LLM keys, is encrypted in Postgres with
the secrets key, which lives outside the database. A copy of the database
alone opens none of them. The server checks at boot that its key opens every
sealed value.
## Webhooks are signed, and their URLs are the owner's choice [#webhooks-are-signed-and-their-urls-are-the-owners-choice]
Every delivery carries an HMAC-SHA256 signature over its timestamp and body,
which also blocks replays. An endpoint URL must be an absolute `http` or
`https` URL of at most 2,048 characters, with no credentials or fragment.
Redirects aren't followed, and a receiver has 10 seconds to start answering.
Endpoint URLs are not filtered for private addresses. The same goes for the
speech API and the chapters LLM, so a server on your own network works. Only
the owner can set them. Importing a video from a URL is different: it
blocks private, loopback and link-local addresses, after DNS and on every
redirect.
## Viewers are counted without being identified [#viewers-are-counted-without-being-identified]
A token may carry a viewer ID, `vid`, to count unique viewers. ClipMux
stores only a keyed hash of it, per day, for 180 days. No IP address,
User-Agent, referrer or token is stored for analytics, on your server or at
Cloudflare's edge.
## What leaves your servers [#what-leaves-your-servers]
Nothing, until you connect something. Each connection says what it sends:
encoded files and keys to [Cloudflare](/docs/self-host/delivery/cloudflare),
source videos to Modal or RunPod, audio to a
[speech API](/docs/self-host/captions-and-ai/speech-apis), and transcript
text to a [chapters LLM](/docs/self-host/captions-and-ai/chapters-llm).
## Next [#next]
- [Security checklist](/docs/self-host/operate/security-checklist)
- [Limitations](/docs/self-host/limitations)
- [Security policy](/docs/resources/security-policy), to report a
vulnerability
---
# Limitations
What ClipMux doesn't do, so you can decide before you build on it.
Source: https://clipmux.com/docs/self-host/limitations
ClipMux is deliberately small: one Go binary and Postgres. This page lists
what it doesn't do today, plainly, so nothing here surprises you in
production.
## Playback and protection [#playback-and-protection]
- **No DRM.** Videos are encrypted with AES-128 and keys are handed only to
valid tokens, but anyone with a valid token can fetch the key, and common
download tools do. It's deterrence, not Widevine or FairPlay. See
[What encryption does and doesn't do](/docs/build/concepts/encryption).
- **Playback shares the dashboard's origin by default.** Until you set a
media URL on another domain, videos play from the same origin as the
dashboard. See [Built-in delivery](/docs/self-host/delivery/built-in).
## Scale [#scale]
- **One server.** One serve replica is the supported shape. Rate limits,
the route cache, the speech and chapters runners and the shutdown drain
live in one process. There's no high-availability setup.
- **No audit log.** Owner actions and key operations are logged with their
request IDs, but nothing durable records who did what.
- **No OpenTelemetry tracing.** There are Prometheus metrics and structured
logs. See [Monitoring](/docs/self-host/operate/monitoring).
## Subtitles and chapters [#subtitles-and-chapters]
- **One caption language per video.** whisper.cpp detects the language, and
a video gets one subtitles track. There's no translation and no language
hint.
- **No uploaded captions.** Subtitles are generated. You can't upload your
own caption file, or edit a transcript.
- **No spend cap on speech APIs.** Every transcription sent to a speech API
is billed by the provider. ClipMux neither estimates nor caps it.
- **No spend estimate for chapters.** Each video's chapters are billed by
the LLM provider, and ClipMux doesn't estimate the cost.
## Encoding [#encoding]
- **Provider spend is an estimate.** For Modal, it's Modal's bill up to its
last reported hour plus an estimate since; for RunPod, an estimate from
the hourly rate set in Connect. A machine that runs past its reservation
isn't stopped at the limit, so a month can overshoot by that much.
- **RunPod may download the worker image for a video.** Each video gets a
new pod, and a host that has never run ClipMux pulls the 1.7 GB image
first. A host that ran an earlier release downloads only what changed,
usually ClipMux itself (about 17 MB). That time counts toward the monthly
limit. Modal converts the image once per release and starts every later
machine from its copy.
- **The PC agent is command-line only.** The dashboard doesn't list PCs,
create pairing codes or revoke them. A PC is paired with
`clipmux worker --server` and approved in the dashboard, or with a code
from `clipmux admin create-pairing`; the rest is the API.
## Webhooks and outside services [#webhooks-and-outside-services]
- **Owner-set URLs aren't filtered for private addresses.** That's by
design for webhook endpoints, the speech API and the chapters LLM, so
servers on your own network work. Only the owner can set them.
## Cloudflare [#cloudflare]
- **Edge analytics are sampled.** Cloudflare's Analytics Engine samples data
points, so edge views, watch time and bytes are close estimates, and edge
unique viewers can read low. See
[Edge analytics](/docs/self-host/delivery/edge-analytics).
- **Disconnect leaves the Worker behind.** Disconnecting Cloudflare stops
the Worker serving your videos, but the Worker, its custom domain and the
token stay in your Cloudflare account, since ClipMux keeps no token to
remove them. Delete them in Cloudflare.
## Packages [#packages]
- **ESM only.** `@clipmux/node`, `@clipmux/player` and `@clipmux/uploader`
are ES modules. A CommonJS app needs Node 20.19 or later (or 22.12) to
`require()` them, and TypeScript's `moduleResolution: node` can't resolve
their subpath exports.
## Next [#next]
- [Security model](/docs/self-host/security-model)
- [FAQ](/docs/resources/faq)
- [Requirements and sizing](/docs/self-host/requirements)
---
# Reference
The integration API, webhook events, errors, limits, settings, the command line and the SDKs.
Source: https://clipmux.com/docs/reference
Every route of the integration API, with its parameters, an example and
its errors.
The events your endpoints receive, their headers, and how to verify them.
Every error code, and what to do.
Rate limits, sizes and token lifetimes.
## The server [#the-server]
- [Environment variables](/docs/reference/configuration): every setting of
the server, the worker, the CLI and your app's backend.
- [Command line](/docs/reference/cli): `clipmux` and `npx @clipmux/node`.
- [Management API](/docs/reference/management-api): the routes the dashboard
uses, for scripting a server. They may change between releases.
## The packages [#the-packages]
- [@clipmux/node](/docs/reference/sdks/node): the server SDK, route handlers
and CLI.
- [@clipmux/player](/docs/reference/sdks/player): the ``
element.
- [@clipmux/uploader](/docs/reference/sdks/uploader): the
`` element and the headless uploader.
## Releases [#releases]
[Changelog](/docs/reference/changelog): what changed in each release.
The integration API is also described as OpenAPI 3.1, which every ClipMux
server serves at `/openapi.json` without a credential. This site's copy is
at [/openapi.json](/openapi.json).
---
# API reference
Every route of the integration API, with its parameters, an example and its errors.
Source: https://clipmux.com/docs/reference/api
The routes an app's backend, its browser uploader and its player use, and the webhooks the app receives. Requests and responses are JSON, with bodies up to 64 KiB. Every POST takes an `Idempotency-Key`. Errors are `{"error": {"code", "message", ...details}}`; a `429 rate_limited` carries `Retry-After`. The management API, which the dashboard uses with the owner's session, is not described here.
Every instance serves this description as OpenAPI 3.1 at `https://video.example.com/openapi.json`, with no credential, so a code generator or an agent reads the version the instance runs. The copy on this site is at [/openapi.json](/openapi.json).
## Authentication [#authentication]
- **API key** (`Authorization: Bearer …`): An app's API key (cmx_…), from your backend only. Scopes: uploads:write, assets:read, assets:write, analytics:read.
- **Upload token** (`Authorization: Bearer …`): An upload's upload_token: safe for the browser, reaches only that upload.
## Idempotency [#idempotency]
A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused.
## Errors [#errors]
Every error is JSON: `{"error": {"code": "snake_case", "message": "…", …details}}`. The [errors reference](/docs/reference/errors) lists every code and what to do about it.
## Videos [#videos]
- [Uploads](/docs/reference/api/uploads): Resumable browser uploads.
- [Videos](/docs/reference/api/videos): A video is an asset in the API: its status, playback IDs, tracks and renditions.
- [Subtitles and chapters](/docs/reference/api/subtitles-and-chapters): Tracks made after a video is ready: subtitles from speech, and chapters from an LLM.
- [Playback IDs](/docs/reference/api/playback-ids): Each video has one or more playback IDs, public or signed, each revocable on its own.
- [Share links](/docs/reference/api/share-links): A share link plays one video for anyone holding its URL, until it expires or is revoked.
## Your app [#your-app]
- [App](/docs/reference/api/app): The API key's own app: its URLs, scopes, token lifetime and signing keys.
- [Events](/docs/reference/api/events): The same events your webhook endpoints receive, read by long-polling.
- [Analytics](/docs/reference/api/analytics): Views, watch time, unique viewers and bytes delivered, counted at delivery.
- [App pairing](/docs/reference/api/app-pairing): How `npx @clipmux/node init` gets an app's credentials without anyone copying a secret.
## Playback [#playback]
- [Delivery](/docs/reference/api/delivery): Playback, from the media URL (`base_url`): HLS playlists, posters and subtitle files.
- [Share page](/docs/reference/api/share-page): The token endpoint behind a share link's page.
---
# Uploads API
Resumable browser uploads.
Source: https://clipmux.com/docs/reference/api/uploads
Your backend creates the upload; the browser sends S3 multipart parts straight to storage with the upload token, then completes it.
## Create an upload [#create-an-upload]
`POST /v1/uploads`
Call from your backend, then hand the body to the browser uploader. The asset exists at once in `waiting_upload`, with its playback IDs, so you can store them before the file arrives. `generate` asks for subtitles and chapters once the video is ready; `renditions` limits the ladder.
**Authentication:** An API key with `uploads:write`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `size` | integer | yes | The file size in bytes. |
| `playback_policy` | "signed", "public" | no | The policy of the playback ID made with the asset. Default signed. |
| `passthrough` | string | no | Your own reference; it comes back on the asset and its webhooks. |
| `title` | string | no | One line, up to 200 characters. |
| `generate` | Generate | no | Ask for subtitles and chapters once the video is ready; chapters imply subtitles. |
| `renditions` | Renditions | no | The ladder rungs to encode, e.g. ["1080p", "480p"]. Rungs above the source are skipped; if none chosen fits, the largest rung that fits is encoded. Leave it out for every rung up to the source. Shown largest first. |
```json
{
"size": 734003200,
"playback_policy": "signed",
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"generate": {
"subtitles": true,
"chapters": true
}
}
```
### Response 201 [#response-201]
Created
```json
{
"upload_id": "upl_01jx169zxgft4kq0ydjct7r5y4",
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"part_size": 33554432,
"part_count": 22,
"upload_token": "M4XQ7R2VK6WT5ZJYBNC3D4F7GH",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
]
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 413 | [`too_large`](/docs/reference/errors#too_large) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Sign part URLs [#sign-part-urls]
`POST /v1/uploads/{id}/parts`
Up to 100 part numbers at a time. PUT each part's bytes to its URL before `expires_at`, and keep the `ETag` storage returns for each.
**Authentication:** The upload's `upload_token`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Request body [#request-body-1]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `part_numbers` | array of integer | yes | |
```json
{
"part_numbers": [
1,
2,
3
]
}
```
### Response 200 [#response-200]
Signed URLs; PUT each part and keep its ETag
```json
{
"parts": [
{
"part_number": 1,
"url": "https://storage.example.com/...&partNumber=1&..."
}
],
"expires_at": "2026-11-18T10:30:00Z"
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 403 | [`upload_mismatch`](/docs/reference/errors#upload_mismatch) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`upload_not_active`](/docs/reference/errors#upload_not_active) |
| 409 | [`upload_expired`](/docs/reference/errors#upload_expired) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## List stored parts, for resuming [#list-stored-parts-for-resuming]
`GET /v1/uploads/{id}/parts`
The parts storage already holds, so an upload can resume after a dropped connection or a closed tab.
**Authentication:** The upload's `upload_token`.
### Parameters [#parameters-2]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Response 200 [#response-200-1]
Parts storage holds
```json
{
"parts": [
{
"part_number": 1,
"etag": "\"9b2cf535f27731c974343645a3985328\"",
"size": 33554432
}
]
}
```
### Errors [#errors-2]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Complete an upload [#complete-an-upload]
`POST /v1/uploads/{id}/complete`
Send every part's number and `ETag`. The asset moves to `processing`, and encoding starts.
**Authentication:** The upload's `upload_token`.
### Parameters [#parameters-3]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Request body [#request-body-2]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `parts` | array of object | yes | |
```json
{
"parts": [
{
"part_number": 1,
"etag": "\"9b2cf535f27731c974343645a3985328\""
}
]
}
```
### Response 200 [#response-200-2]
The asset, processing
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "processing",
"version": 2,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": null,
"tracks": [],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:30:00Z"
}
```
### Errors [#errors-3]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 400 | [`invalid_parts`](/docs/reference/errors#invalid_parts) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 403 | [`upload_mismatch`](/docs/reference/errors#upload_mismatch) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`upload_not_active`](/docs/reference/errors#upload_not_active) |
| 409 | [`upload_expired`](/docs/reference/errors#upload_expired) |
| 409 | [`upload_missing`](/docs/reference/errors#upload_missing) |
| 409 | [`size_mismatch`](/docs/reference/errors#size_mismatch) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Cancel an upload [#cancel-an-upload]
`POST /v1/uploads/{id}/cancel`
Stops the upload. The asset becomes `errored` with `error_code` `upload_cancelled`. Takes the upload token or an API key with `uploads:write`.
**Authentication:** The upload's `upload_token`, or An API key with `uploads:write`.
### Parameters [#parameters-4]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Response 200 [#response-200-3]
The asset, errored with upload_cancelled
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "errored",
"version": 2,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": null,
"tracks": [],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:30:00Z",
"error_code": "upload_cancelled"
}
```
### Errors [#errors-4]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Videos API
A video is an asset in the API: its status, playback IDs, tracks and renditions.
Source: https://clipmux.com/docs/reference/api/videos
Find one by your own `passthrough`, page through changes, rename, re-encode or delete it.
## Import from a URL, or attach a PC agent's local file [#import-from-a-url-or-attach-a-pc-agents-local-file]
`POST /v1/assets`
Two ways to make an asset without an upload. With `url`, the server fetches a public http(s) URL and encodes it; a non-public or credentialed URL is `400 import_url_refused`, and a fetch that fails ends `errored` with `import_url_refused`, `import_failed` or `import_too_large`. With `agent_source_id`, it attaches a file a PC agent registered for `clipmux push --local`, and its jobs run only on that agent.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body]
One of these, **ImportURL**:
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `url` | string (uri) | yes | |
| `playback_policy` | "signed", "public" | no | |
| `passthrough` | string | no | |
| `title` | string | no | |
| `generate` | Generate | no | |
| `renditions` | Renditions | no | The ladder rungs to encode, e.g. ["1080p", "480p"]. Rungs above the source are skipped; if none chosen fits, the largest rung that fits is encoded. Leave it out for every rung up to the source. Shown largest first. |
One of these, **AttachAgentSource**:
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `agent_source_id` | string | yes | |
| `playback_policy` | "signed", "public" | no | |
| `passthrough` | string | no | |
| `title` | string | no | |
| `generate` | Generate | no | |
| `renditions` | Renditions | no | The ladder rungs to encode, e.g. ["1080p", "480p"]. Rungs above the source are skipped; if none chosen fits, the largest rung that fits is encoded. Leave it out for every rung up to the source. Shown largest first. |
```json
{
"url": "https://files.example.com/lesson-42.mp4",
"playback_policy": "signed",
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting"
}
```
### Response 201 [#response-201]
The asset, processing
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "processing",
"version": 2,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": null,
"tracks": [],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:30:00Z"
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 400 | [`import_url_refused`](/docs/reference/errors#import_url_refused) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`agent_source_not_found`](/docs/reference/errors#agent_source_not_found) |
| 409 | [`source_unavailable`](/docs/reference/errors#source_unavailable) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Find by passthrough, or page through changes [#find-by-passthrough-or-page-through-changes]
`GET /v1/assets`
With `passthrough`, the app's assets with that reference, newest first. With `updated_since`, every change since an RFC 3339 time, oldest first, deleted assets included, up to 100 a page with `next_cursor`: the way to catch up after missed webhooks.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `passthrough` | query | string | no | Your reference; newest first. |
| `updated_since` | query | string (date-time) | no | Every change since this time, oldest first, deleted included. |
| `cursor` | query | string | no | |
| `limit` | query | integer | no | |
### Response 200 [#response-200]
Assets
```json
{
"data": [
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
]
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 400 | [`invalid_cursor`](/docs/reference/errors#invalid_cursor) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Get an asset [#get-an-asset]
`GET /v1/assets/{id}`
The asset, as it is now. Keep the highest `version` you have seen.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters-2]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
### Response 200 [#response-200-1]
The asset
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Errors [#errors-2]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Change an asset's title [#change-an-assets-title]
`PATCH /v1/assets/{id}`
Sets the title; `""` or `null` clears it. A change raises `version` and sends `video.asset.updated`; the same title changes nothing.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-3]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
### Request body [#request-body-1]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string or null | yes | |
```json
{
"title": "Lesson 42: Sorting algorithms"
}
```
### Response 200 [#response-200-2]
The asset
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 5,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting algorithms",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Errors [#errors-3]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`asset_deleted`](/docs/reference/errors#asset_deleted) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Delete an asset [#delete-an-asset]
`DELETE /v1/assets/{id}`
Playback stops at once. `200` once the files are gone, `202` while the delete job runs.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-4]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
### Response 200 [#response-200-3]
Files are gone
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "deleted",
"version": 5,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": false,
"status": "revoked"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Response 202 [#response-202]
The delete job runs
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "deleted",
"version": 5,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": false,
"status": "revoking"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Errors [#errors-4]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Re-encode an asset [#re-encode-an-asset]
`POST /v1/assets/{id}/reencode`
Encodes the source again, for example with other `renditions`. The current output keeps playing until the new one is ready. `409 job_active` (with `job_id`) while another job changes the asset; `supersede` cancels it.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-5]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body-2]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `supersede` | boolean | no | |
| `renditions` | Renditions | no | Replaces the asset's choice for this output and the ones after it; leave it out to keep it. |
```json
{
"renditions": [
"1080p",
"720p",
"480p"
]
}
```
### Response 202 [#response-202-1]
Queued
```json
{
"id": "job_01jq68ea3qk8sxe3rv83fez7sf",
"kind": "reencode",
"status": "queued"
}
```
### Errors [#errors-5]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`job_active`](/docs/reference/errors#job_active) |
| 409 | [`source_missing`](/docs/reference/errors#source_missing) |
| 409 | [`asset_not_ready`](/docs/reference/errors#asset_not_ready) |
| 409 | [`asset_deleted`](/docs/reference/errors#asset_deleted) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Subtitles and chapters API
Tracks made after a video is ready: subtitles from speech, and chapters from an LLM.
Source: https://clipmux.com/docs/reference/api/subtitles-and-chapters
A new track replaces the old one only once it is ready.
## Make subtitles or chapters [#make-subtitles-or-chapters]
`POST /v1/assets/{id}/tracks`
Makes a new subtitles or chapters track. The old one keeps playing until the new one is ready. Chapters need ready subtitles and a connected LLM.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `kind` | "subtitles", "chapters" | yes | |
| `supersede` | boolean | no | |
```json
{
"kind": "subtitles"
}
```
### Response 202 [#response-202]
Queued
```json
{
"track": {
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "preparing"
},
"job": {
"id": "job_01jq68ea3qk8sxe3rv83fez7sf",
"kind": "transcribe",
"status": "queued"
}
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`asset_not_ready`](/docs/reference/errors#asset_not_ready) |
| 409 | [`no_audio`](/docs/reference/errors#no_audio) |
| 409 | [`subtitles_not_ready`](/docs/reference/errors#subtitles_not_ready) |
| 409 | [`chapters_not_connected`](/docs/reference/errors#chapters_not_connected) |
| 409 | [`job_active`](/docs/reference/errors#job_active) |
| 409 | [`asset_deleted`](/docs/reference/errors#asset_deleted) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Get a track [#get-a-track]
`GET /v1/assets/{id}/tracks/{track_id}`
A track, with its chapters once a chapters track is ready.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `track_id` | path | string | yes | |
### Response 200 [#response-200]
The track; chapters once a chapters track is ready
```json
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready",
"duration_ms": 1830400,
"chapters": [
{
"start_ms": 0,
"end_ms": 412000,
"title": "Why sorting matters"
},
{
"start_ms": 412000,
"end_ms": 1830400,
"title": "Merge sort"
}
]
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Delete a track [#delete-a-track]
`DELETE /v1/assets/{id}/tracks/{track_id}`
Removes a track: its file and transcript go at once. `200` once no playlist lists it, `202` while it is unpublished.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-2]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `track_id` | path | string | yes | |
### Response 200 [#response-200-1]
No route lists it
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 6,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Response 202 [#response-202-1]
Being unpublished
```json
{
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 5,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
```
### Errors [#errors-2]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Get a subtitles track's transcript [#get-a-subtitles-tracks-transcript]
`GET /v1/assets/{id}/tracks/{track_id}/transcript`
A subtitles track's transcript, from the moment the track reads `ready`; `409 track_not_ready` before. Add `words=true` for word timings.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters-3]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `track_id` | path | string | yes | |
| `words` | query | boolean | no | Include word timings. |
### Response 200 [#response-200-2]
The transcript
```json
{
"track_id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"language": "en",
"duration_ms": 1830400,
"text": "Today we look at three ways to sort a list.",
"segments": [
{
"id": "s0",
"start_ms": 0,
"end_ms": 4200,
"text": "Today we look at three ways to sort a list."
}
]
}
```
### Errors [#errors-3]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`track_not_ready`](/docs/reference/errors#track_not_ready) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Playback IDs API
Each video has one or more playback IDs, public or signed, each revocable on its own.
Source: https://clipmux.com/docs/reference/api/playback-ids
## Add a playback ID [#add-a-playback-id]
`POST /v1/assets/{id}/playback-ids`
Adds a playback ID. A `signed` one plays only with a token your backend signs; a `public` one plays for anyone with the URL.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `policy` | "signed", "public" | yes | |
```json
{
"policy": "public"
}
```
### Response 201 [#response-201]
Created
```json
{
"id": "pid_01jmgkyp0c3ct46ees12paekfv",
"policy": "public",
"playable": true,
"status": "active"
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`asset_deleted`](/docs/reference/errors#asset_deleted) |
| 409 | [`too_many_playback_ids`](/docs/reference/errors#too_many_playback_ids) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Revoke a playback ID [#revoke-a-playback-id]
`DELETE /v1/assets/{id}/playback-ids/{pid}`
Revokes a playback ID: `200 revoked` once it is unpublished, `202 revoking` before. Its playback stops; the asset's other IDs keep playing.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `pid` | path | string | yes | |
### Response 200 [#response-200]
Revoked
```json
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": false,
"status": "revoked"
}
```
### Response 202 [#response-202]
Revoking
```json
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": false,
"status": "revoking"
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Share links API
A share link plays one video for anyone holding its URL, until it expires or is revoked.
Source: https://clipmux.com/docs/reference/api/share-links
## Create a share link [#create-a-share-link]
`POST /v1/assets/{id}/shares`
Makes a share link and its own signed playback ID. `url` is the page to send. `name` is one line of up to 100 characters; `expires_at` must be in the future and can't be changed later. Allowed while the asset is processing.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `Idempotency-Key` | header | string | no | A retry with the same key and request returns the first response; a different request is 422 idempotency_key_reused. |
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | no | |
| `expires_at` | string (date-time) | no | |
```json
{
"name": "For the review",
"expires_at": "2026-12-01T00:00:00Z"
}
```
### Response 201 [#response-201]
Created
```json
{
"id": "shr_01jepn315k8tfeyh86qtbhnna7",
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"name": "For the review",
"url": "https://video.example.com/s/QR2V7M4K5X3T6WAY5ZEB2CND4F",
"playback_id": "pid_01jmgkyp0c3ct46ees12paekfv",
"expires_at": "2026-12-01T00:00:00Z",
"status": "active",
"created_at": "2026-11-18T09:30:00Z"
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`asset_deleted`](/docs/reference/errors#asset_deleted) |
| 409 | [`too_many_playback_ids`](/docs/reference/errors#too_many_playback_ids) |
| 409 | [`idempotency_in_progress`](/docs/reference/errors#idempotency_in_progress) |
| 422 | [`idempotency_key_reused`](/docs/reference/errors#idempotency_key_reused) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## List an asset's share links [#list-an-assets-share-links]
`GET /v1/assets/{id}/shares`
The asset's share links, newest first, each with `views_30d`: its views over the last 30 UTC days.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
### Response 200 [#response-200]
Newest first
```json
{
"data": [
{
"id": "shr_01jepn315k8tfeyh86qtbhnna7",
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"name": "For the review",
"url": "https://video.example.com/s/QR2V7M4K5X3T6WAY5ZEB2CND4F",
"playback_id": "pid_01jmgkyp0c3ct46ees12paekfv",
"expires_at": "2026-12-01T00:00:00Z",
"status": "active",
"created_at": "2026-11-18T09:30:00Z",
"views_30d": 27
}
]
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Revoke a share link [#revoke-a-share-link]
`DELETE /v1/shares/{id}`
Revokes the link's playback ID: `200` once unpublished, `202` while revoking. Revoking again changes nothing.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-2]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Response 200 [#response-200-1]
Unpublished
```json
{
"id": "shr_01jepn315k8tfeyh86qtbhnna7",
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"name": "For the review",
"url": "https://video.example.com/s/QR2V7M4K5X3T6WAY5ZEB2CND4F",
"playback_id": "pid_01jmgkyp0c3ct46ees12paekfv",
"expires_at": "2026-12-01T00:00:00Z",
"status": "revoked",
"created_at": "2026-11-18T09:30:00Z"
}
```
### Response 202 [#response-202]
Revoking
```json
{
"id": "shr_01jepn315k8tfeyh86qtbhnna7",
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"name": "For the review",
"url": "https://video.example.com/s/QR2V7M4K5X3T6WAY5ZEB2CND4F",
"playback_id": "pid_01jmgkyp0c3ct46ees12paekfv",
"expires_at": "2026-12-01T00:00:00Z",
"status": "revoked",
"created_at": "2026-11-18T09:30:00Z"
}
```
### Errors [#errors-2]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## A signed master.m3u8 URL for a share link [#a-signed-masterm3u8-url-for-a-share-link]
`POST /v1/shares/{id}/stream-url`
A signed `master.m3u8` URL for players that can't open the share page. It can't refresh: it lasts until the link's expiry or the longest token lifetime, whichever is first, and stops when the link is revoked.
**Authentication:** An API key with `assets:write`.
### Parameters [#parameters-3]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | |
### Response 200 [#response-200-2]
The URL
```json
{
"url": "https://media.example.com/v/eyJhbGciOiJFUzI1NiIs.../pid_01jmgkyp0c3ct46ees12paekfv/master.m3u8",
"expires_at": "2026-11-25T09:30:00Z"
}
```
### Errors [#errors-3]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 409 | [`share_expired`](/docs/reference/errors#share_expired) |
| 409 | [`share_revoked`](/docs/reference/errors#share_revoked) |
| 409 | [`asset_not_ready`](/docs/reference/errors#asset_not_ready) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# App API
The API key's own app: its URLs, scopes, token lifetime and signing keys.
Source: https://clipmux.com/docs/reference/api/app
## The key's own app [#the-keys-own-app]
`GET /v1/app`
The key's own app. `base_url` is the media origin playback URLs start with; `upload_origins` are where a browser sends parts. With `base_url`, they are what a page's Content-Security-Policy must allow. A token's `exp - iat` may not exceed `max_token_lifetime_seconds`; `signing_keys` are the keys that still verify tokens, newest first.
**Authentication:** An API key.
### Response 200 [#response-200]
The app
```json
{
"id": "app_01j6hrm8vmt8f27hd13py42rdc",
"name": "Course site",
"scopes": [
"uploads:write",
"assets:read",
"assets:write"
],
"public_url": "https://video.example.com",
"base_url": "https://media.example.com",
"max_token_lifetime_seconds": 604800,
"upload_origins": [
"https://video.example.com"
],
"signing_keys": [
{
"kid": "kid_01jsxwyx7223sqpr1we59kgw33",
"public_key_pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...\n-----END PUBLIC KEY-----\n",
"created_at": "2026-11-18T09:30:00Z"
}
]
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Events API
The same events your webhook endpoints receive, read by long-polling.
Source: https://clipmux.com/docs/reference/api/events
`npx @clipmux/node listen` uses it.
## Long-poll the app's webhook events [#long-poll-the-apps-webhook-events]
`GET /v1/events`
The app's webhook events created at or after `since` (default now), oldest first, up to 100. `body` is exactly what an endpoint receives. Long-polls up to `wait` seconds (at most 25) until an event is newer than `after`, the `created_at` of the newest event you have.
**Authentication:** An API key with `assets:read`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `since` | query | string (date-time) | no | |
| `after` | query | string (date-time) | no | The created_at (RFC 3339) of the newest event you have; the poll waits for a newer one. |
| `wait` | query | integer | no | |
### Response 200 [#response-200]
Oldest first, at most 100
```json
{
"data": [
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"created_at": "2026-11-18T09:34:12Z",
"body": {
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.ready",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
}
}
]
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Analytics API
Views, watch time, unique viewers and bytes delivered, counted at delivery.
Source: https://clipmux.com/docs/reference/api/analytics
Needs the `analytics:read` scope.
## The app's analytics [#the-apps-analytics]
`GET /v1/analytics`
Totals, the same number of whole buckets just before (`previous`), a zero-filled series (hourly for `24h`, daily otherwise; the last bucket is partial), storage bytes currently held (`storage`), and the top 10 live videos by views (`top_assets`). `unique_viewers` counts distinct `vid` claims in tokens (by hour for `24h`, by UTC day otherwise, excluding poster fetches) and is `null` when no view carried one.
**Authentication:** An API key with `analytics:read`.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `range` | query | "24h", "7d", "30d", "90d" | yes | |
### Response 200 [#response-200]
Totals and series
```json
{
"totals": {
"views": 1840,
"watch_seconds": 302400,
"unique_viewers": 412,
"bytes_delivered": 98123456789
},
"previous": {
"views": 1502,
"watch_seconds": 251000,
"unique_viewers": null,
"bytes_delivered": 80211000000
},
"series": [
{
"t": "2026-11-17T00:00:00Z",
"views": 260,
"watch_seconds": 43100,
"bytes_delivered": 14000000000
}
],
"top_assets": [
{
"asset_id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"title": "Lesson 42: Sorting",
"views": 310,
"watch_seconds": 61000,
"bytes_delivered": 17000000000
}
],
"storage": {
"source_bytes": 524288000,
"media_bytes": 2147483648,
"total_bytes": 2671771648
},
"collecting": {
"builtin": true,
"edge": "not_used"
}
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## One asset's analytics [#one-assets-analytics]
`GET /v1/analytics/assets/{id}`
The same for one video, without `top_assets`. A deleted video keeps its history.
**Authentication:** An API key with `analytics:read`.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `id` | path | string | yes | Asset ID (ast_…). |
| `range` | query | "24h", "7d", "30d", "90d" | yes | |
### Response 200 [#response-200-1]
Totals and series, without top_assets
```json
{
"totals": {
"views": 1840,
"watch_seconds": 302400,
"unique_viewers": 412,
"bytes_delivered": 98123456789
},
"previous": {
"views": 1502,
"watch_seconds": 251000,
"unique_viewers": null,
"bytes_delivered": 80211000000
},
"series": [
{
"t": "2026-11-17T00:00:00Z",
"views": 260,
"watch_seconds": 43100,
"bytes_delivered": 14000000000
}
],
"storage": {
"source_bytes": 52428800,
"media_bytes": 214748364,
"total_bytes": 267177164
},
"collecting": {
"builtin": true,
"edge": "not_used"
}
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 401 | [`unauthorized`](/docs/reference/errors#unauthorized) |
| 403 | [`insufficient_scope`](/docs/reference/errors#insufficient_scope) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# App pairing API
How `npx @clipmux/node init` gets an app's credentials without anyone copying a secret.
Source: https://clipmux.com/docs/reference/api/app-pairing
None of these routes needs a key.
## Start an app pairing (npx @clipmux/node init) [#start-an-app-pairing-npx-clipmuxnode-init]
`POST /v1/app-pairings`
Starts a pairing: show the `code` and open `verify_url`, where the owner checks the code and approves. The code works for 10 minutes. `429 too_many_pairings` while 10 wait for the owner.
**Authentication:** None.
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | no | |
| `hostname` | string | no | |
| `client` | string | no | |
```json
{
"name": "Course site",
"hostname": "laptop.local",
"client": "@clipmux/node 0.1.0"
}
```
### Response 201 [#response-201]
Show code; open verify_url; poll
```json
{
"code": "KXFT-9M2Q",
"poll_token": "K4M2QX7R3VZ6W5TYBJ2C3DNF7G",
"verify_url": "https://video.example.com/connect?code=KXFT-9M2Q",
"expires_at": "2026-11-18T09:40:00Z",
"interval_seconds": 2
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
| 429 | [`too_many_pairings`](/docs/reference/errors#too_many_pairings) |
## Poll an app pairing [#poll-an-app-pairing]
`POST /v1/app-pairings/poll`
Poll every `interval_seconds`. The first poll after approval carries `credentials`, and is the only one that ever does: they are deleted as they are returned, so a later poll is `404 pairing_not_found`.
**Authentication:** None.
### Request body [#request-body-1]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `poll_token` | string | yes | |
```json
{
"poll_token": "K4M2QX7R3VZ6W5TYBJ2C3DNF7G"
}
```
### Response 200 [#response-200]
The first poll after approval carries credentials, once
```json
{
"status": "pending"
}
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 404 | [`pairing_not_found`](/docs/reference/errors#pairing_not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Delivery API
Playback, from the media URL (`base_url`): HLS playlists, posters and subtitle files.
Source: https://clipmux.com/docs/reference/api/delivery
Signed playback IDs take an ES256 token your backend signs; public ones take none.
## Signed HLS master playlist [#signed-hls-master-playlist]
`GET /v/{token}/{pid}/master.m3u8`
401 token_expired: fetch a new token. 403 denied: stop.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `token` | path | string | yes | ES256 JWT signed with the app's key: header kid; claims sub (playback ID), aud (v, or t for posters only), iat, exp, optional vid. |
| `pid` | path | string | yes | Playback ID |
### Response 200 [#response-200]
OK
```text
#EXTM3U
#EXT-X-MEDIA:TYPE=AUDIO,URI="out_01jwmgegachysgyeayn62q1gdp/audio/index.m3u8",GROUP-ID="a",NAME="audio"
#EXT-X-STREAM-INF:BANDWIDTH=5400000,RESOLUTION=1920x1080,AUDIO="a"
out_01jwmgegachysgyeayn62q1gdp/1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1200000,RESOLUTION=854x480,AUDIO="a"
out_01jwmgegachysgyeayn62q1gdp/480p/index.m3u8
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 401 | [`token_expired`](/docs/reference/errors#token_expired) |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Public HLS master playlist [#public-hls-master-playlist]
`GET /p/{pid}/master.m3u8`
Only for a public playback ID.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters-1]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `pid` | path | string | yes | Playback ID |
### Response 200 [#response-200-1]
OK
```text
#EXTM3U
#EXT-X-MEDIA:TYPE=AUDIO,URI="out_01jwmgegachysgyeayn62q1gdp/audio/index.m3u8",GROUP-ID="a",NAME="audio"
#EXT-X-STREAM-INF:BANDWIDTH=5400000,RESOLUTION=1920x1080,AUDIO="a"
out_01jwmgegachysgyeayn62q1gdp/1080p/index.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=1200000,RESOLUTION=854x480,AUDIO="a"
out_01jwmgegachysgyeayn62q1gdp/480p/index.m3u8
```
### Errors [#errors-1]
| Status | Code |
| --- | --- |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Signed poster [#signed-poster]
`GET /v/{token}/{pid}/poster.jpg`
A t token is enough.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters-2]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `token` | path | string | yes | ES256 JWT signed with the app's key: header kid; claims sub (playback ID), aud (v, or t for posters only), iat, exp, optional vid. |
| `pid` | path | string | yes | Playback ID |
### Response 200 [#response-200-2]
OK
### Errors [#errors-2]
| Status | Code |
| --- | --- |
| 401 | [`token_expired`](/docs/reference/errors#token_expired) |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## Public poster [#public-poster]
`GET /p/{pid}/poster.jpg`
A public playback ID's poster, a JPEG of a frame near the start.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters-3]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `pid` | path | string | yes | Playback ID |
### Response 200 [#response-200-3]
OK
### Errors [#errors-3]
| Status | Code |
| --- | --- |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## A track's sidecar VTT [#a-tracks-sidecar-vtt]
`GET /v/{token}/{pid}/tracks/{track_id}.vtt`
A ready track's WebVTT file, for players that show subtitles from a sidecar file rather than the playlist. A chapters track's file is at the same path.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters-4]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `token` | path | string | yes | ES256 JWT signed with the app's key: header kid; claims sub (playback ID), aud (v, or t for posters only), iat, exp, optional vid. |
| `pid` | path | string | yes | Playback ID |
| `track_id` | path | string | yes | |
### Response 200 [#response-200-4]
OK
```text
WEBVTT
00:00:00.000 --> 00:00:04.200
Today we look at three ways to sort a list.
```
### Errors [#errors-4]
| Status | Code |
| --- | --- |
| 401 | [`token_expired`](/docs/reference/errors#token_expired) |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
## A public track's sidecar VTT [#a-public-tracks-sidecar-vtt]
`GET /p/{pid}/tracks/{track_id}.vtt`
A public playback ID's track as WebVTT.
**Authentication:** None.
Served from the media URL (`base_url`), not the public URL.
### Parameters [#parameters-5]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `pid` | path | string | yes | Playback ID |
| `track_id` | path | string | yes | |
### Response 200 [#response-200-5]
OK
```text
WEBVTT
00:00:00.000 --> 00:00:04.200
Today we look at three ways to sort a list.
```
### Errors [#errors-5]
| Status | Code |
| --- | --- |
| 403 | [`denied`](/docs/reference/errors#denied) |
| 404 | [`not_found`](/docs/reference/errors#not_found) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Share page API
The token endpoint behind a share link's page.
Source: https://clipmux.com/docs/reference/api/share-page
It needs no session or key.
## A share link's playback session [#a-share-links-playback-session]
`POST /s/{secret}/playback`
What the share page's script asks for: a `v` token for the link's playback ID, valid until the earliest of the link's expiry, max(2 x duration, 4 h) and the longest token lifetime. A `viewer_id` of 16 to 64 `[A-Za-z0-9_-]` characters counts as a unique viewer.
**Authentication:** None.
### Parameters [#parameters]
| Name | In | Type | Required | Description |
| --- | --- | --- | --- | --- |
| `secret` | path | string | yes | |
### Request body [#request-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `viewer_id` | string | no | |
```json
{
"viewer_id": "b7f3k9q2m4x8r1v6t0w5"
}
```
### Response 200 [#response-200]
A token for the link's playback ID
```json
{
"title": "Lesson 42: Sorting",
"duration_seconds": 1830.4,
"base_url": "https://media.example.com",
"playback_id": "pid_01jmgkyp0c3ct46ees12paekfv",
"token": "eyJhbGciOiJFUzI1NiIs...",
"expires_at": "2026-11-18T13:30:00Z",
"poster_url": "https://media.example.com/v/eyJhbGciOiJFUzI1NiIs.../pid_01jmgkyp0c3ct46ees12paekfv/poster.jpg",
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
}
]
}
```
### Errors [#errors]
| Status | Code |
| --- | --- |
| 400 | [`invalid_request`](/docs/reference/errors#invalid_request) |
| 404 | [`share_not_found`](/docs/reference/errors#share_not_found) |
| 409 | [`asset_not_ready`](/docs/reference/errors#asset_not_ready) |
| 410 | [`share_expired`](/docs/reference/errors#share_expired) |
| 429 | [`rate_limited`](/docs/reference/errors#rate_limited) |
---
# Webhook events
Every event your app's webhook endpoints receive, with its headers and an example body.
Source: https://clipmux.com/docs/reference/webhooks
Each app's endpoints receive its videos' events as a `POST` with a JSON body. Any 2xx is success; redirects are not followed. Delivery is at least once and unordered, and retries back off for 24 hours; after that, catch up with `GET /v1/assets?updated_since=`.
## Headers [#headers]
| Header | Description |
| --- | --- |
| `X-Webhook-Event` | string |
| `X-Webhook-Id` | string |
| `X-Webhook-Timestamp` | string |
| `X-Webhook-Signature` | sha256= and the hex HMAC-SHA256 of "\{timestamp\}.\{raw body\}", keyed with the endpoint secret (whsec_…, prefix included). |
## Verify a delivery [#verify-a-delivery]
1. Read the raw body before any JSON parsing.
2. Compute HMAC-SHA256 of `{X-Webhook-Timestamp}.{raw body}` with the endpoint secret (`whsec_…`, prefix included) as the key, and compare its hex with `X-Webhook-Signature` after `sha256=`, in constant time.
3. Reject a timestamp more than 300 seconds from your clock.
4. Dedupe on `X-Webhook-Id`, then re-fetch the asset before acting on it.
With the Node SDK, `clipmux.webhooks.verify` does all four. A receiver in any language can test itself against the [webhook test vectors](https://github.com/visheshgubrani/clipmux/blob/main/internal/webhooks/testdata/vectors.json): the same secret, clock, body and headers must give each case its `valid` and `reason`.
## The event body [#the-event-body]
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | string | yes | The event ID (evt_...), the same as X-Webhook-Id. Dedupe on it. |
| `type` | "video.asset.ready", "video.asset.updated", "video.asset.errored", "video.asset.reencode_failed", "video.asset.deleted", "video.asset.track.ready", "video.asset.track.errored", "video.asset.track.deleted" | yes | |
| `created_at` | string (date-time) | yes | |
| `data` | Asset | yes | The asset when the event was made. Re-fetch it before acting. |
| `job` | object | no | The job behind the event, for re-encodes. |
| `track` | object | no | The track, for track events. |
## `video.asset.ready` [#videoassetready]
The video is ready to play: its first encode is done and published. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.ready",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
}
```
## `video.asset.updated` [#videoassetupdated]
The asset changed after it was ready: a re-encode finished, its title changed, a playback ID was published, or it moved storage. Re-fetch and keep the highest `version`. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.updated",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
}
```
## `video.asset.errored` [#videoasseterrored]
The video can't be played: the upload, import or first encode failed. `data.error_code` says why. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.errored",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "errored",
"version": 2,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": null,
"tracks": [],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:30:00Z",
"error_code": "unsupported_source"
}
}
```
## `video.asset.reencode_failed` [#videoassetreencode_failed]
A re-encode failed. The video keeps playing its previous output; `job.error_code` says why. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.reencode_failed",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
},
"job": {
"id": "job_01jq68ea3qk8sxe3rv83fez7sf",
"kind": "reencode",
"error_code": "transcode_failed"
}
}
```
## `video.asset.deleted` [#videoassetdeleted]
The video was deleted, and its playback has stopped. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.deleted",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "deleted",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
}
}
```
## `video.asset.track.ready` [#videoassettrackready]
A subtitles or chapters track is ready. `track` names it. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.track.ready",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
},
"track": {
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles"
}
}
```
## `video.asset.track.errored` [#videoassettrackerrored]
A track couldn't be made. `track.error_code` says why, for example `no_audio`. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.track.errored",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
},
"track": {
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"error_code": "no_audio"
}
}
```
## `video.asset.track.deleted` [#videoassettrackdeleted]
A track was deleted. Delivery is at least once and unordered: verify `X-Webhook-Signature` over the raw body, reject a timestamp more than 300 s off, dedupe on `X-Webhook-Id`, and re-fetch the asset before acting on it. Retries back off for 24 hours.
```json
{
"id": "evt_01j2ef9545dh466aggzfdgtejb",
"type": "video.asset.track.deleted",
"created_at": "2026-11-18T09:34:12Z",
"data": {
"id": "ast_01jhsze3w2mhtbzr5qv1w5xy68",
"app_id": "app_01j6hrm8vmt8f27hd13py42rdc",
"status": "ready",
"version": 4,
"passthrough": "lesson_42",
"title": "Lesson 42: Sorting",
"base_url": "https://media.example.com",
"playback_ids": [
{
"id": "pid_01j88d4vyy93fwe7p3aqr8kcqz",
"policy": "signed",
"playable": true,
"status": "active"
}
],
"duration_seconds": 1830.4,
"tracks": [
{
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles",
"source": "generated",
"status": "ready",
"language": "en",
"name": "English"
},
{
"id": "trk_01jbz1ke29rzfnpwz5grhd401k",
"kind": "chapters",
"source": "generated",
"status": "ready"
}
],
"created_at": "2026-11-18T09:30:00Z",
"updated_at": "2026-11-18T09:34:12Z"
},
"track": {
"id": "trk_01j0qtsj1vyp4dyn7fsdkb9t8q",
"kind": "subtitles"
}
}
```
---
# Errors
Every error code the API returns, what it means and what to do.
Source: https://clipmux.com/docs/reference/errors
Every error is JSON, `{"error": {"code": "snake_case", "message": "…", …details}}`. Act on `code`; `message` is for people and may change. Retry only what says to: a 4xx other than 409 `idempotency_in_progress` and 429 fails the same way again.
## 400 Bad Request [#400-bad-request]
### `import_url_refused` [#import_url_refused]
The URL is not a public http(s) URL, or it carries credentials. Use a public URL, or upload the file instead.
Returned by: `POST /v1/assets`.
### `invalid_cursor` [#invalid_cursor]
The `cursor` is not one this API returned. Start again without it, or pass the `next_cursor` you were given.
Returned by: `GET /v1/assets`.
### `invalid_parts` [#invalid_parts]
Some parts are missing or their ETags don't match what storage holds. List the stored parts, upload the rest, and complete again.
Returned by: `POST /v1/uploads/{id}/complete`.
### `invalid_request` [#invalid_request]
The body or a parameter is malformed or out of range; `message` names it. Fix the request; retrying the same one fails again.
Returned by: `POST /v1/uploads`, `POST /v1/uploads/{id}/parts`, `GET /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`, `POST /v1/uploads/{id}/cancel`, `POST /v1/assets`, `GET /v1/assets`, `GET /v1/assets/{id}`, `PATCH /v1/assets/{id}`, `DELETE /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `GET /v1/assets/{id}/tracks/{track_id}`, `DELETE /v1/assets/{id}/tracks/{track_id}`, `GET /v1/assets/{id}/tracks/{track_id}/transcript`, `POST /v1/assets/{id}/playback-ids`, `DELETE /v1/assets/{id}/playback-ids/{pid}`, `POST /v1/assets/{id}/shares`, `GET /v1/assets/{id}/shares`, `DELETE /v1/shares/{id}`, `POST /v1/shares/{id}/stream-url`, `GET /v1/events`, `GET /v1/app`, `GET /v1/analytics`, `GET /v1/analytics/assets/{id}`, `POST /v1/app-pairings`, `POST /v1/app-pairings/poll`, `POST /s/{secret}/playback`.
## 401 Unauthorized [#401-unauthorized]
### `token_expired` [#token_expired]
The playback token's `exp` has passed. Fetch a new token and retry; `` does this by itself.
Returned by: `GET /v/{token}/{pid}/master.m3u8`, `GET /v/{token}/{pid}/poster.jpg`, `GET /v/{token}/{pid}/tracks/{track_id}.vtt`.
### `unauthorized` [#unauthorized]
No credential, or a wrong or revoked one. Check the API key or upload token; `npx @clipmux/node doctor` checks an app's key.
Returned by: `POST /v1/uploads`, `POST /v1/uploads/{id}/parts`, `GET /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`, `POST /v1/uploads/{id}/cancel`, `POST /v1/assets`, `GET /v1/assets`, `GET /v1/assets/{id}`, `PATCH /v1/assets/{id}`, `DELETE /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `GET /v1/assets/{id}/tracks/{track_id}`, `DELETE /v1/assets/{id}/tracks/{track_id}`, `GET /v1/assets/{id}/tracks/{track_id}/transcript`, `POST /v1/assets/{id}/playback-ids`, `DELETE /v1/assets/{id}/playback-ids/{pid}`, `POST /v1/assets/{id}/shares`, `GET /v1/assets/{id}/shares`, `DELETE /v1/shares/{id}`, `POST /v1/shares/{id}/stream-url`, `GET /v1/events`, `GET /v1/app`, `GET /v1/analytics`, `GET /v1/analytics/assets/{id}`.
## 403 Forbidden [#403-forbidden]
### `denied` [#denied]
The token is valid but doesn't cover this request: another playback ID or app, a poster-only token, or a revoked signing key. Stop; don't retry.
Returned by: `GET /v/{token}/{pid}/master.m3u8`, `GET /p/{pid}/master.m3u8`, `GET /v/{token}/{pid}/poster.jpg`, `GET /p/{pid}/poster.jpg`, `GET /v/{token}/{pid}/tracks/{track_id}.vtt`, `GET /p/{pid}/tracks/{track_id}.vtt`.
### `insufficient_scope` [#insufficient_scope]
The API key lacks the scope this route needs. Create a key with it: `uploads:write`, `assets:read` and `assets:write` are the defaults, `analytics:read` is asked for.
Returned by: `POST /v1/uploads`, `POST /v1/uploads/{id}/parts`, `GET /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`, `POST /v1/uploads/{id}/cancel`, `POST /v1/assets`, `GET /v1/assets`, `GET /v1/assets/{id}`, `PATCH /v1/assets/{id}`, `DELETE /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `GET /v1/assets/{id}/tracks/{track_id}`, `DELETE /v1/assets/{id}/tracks/{track_id}`, `GET /v1/assets/{id}/tracks/{track_id}/transcript`, `POST /v1/assets/{id}/playback-ids`, `DELETE /v1/assets/{id}/playback-ids/{pid}`, `POST /v1/assets/{id}/shares`, `GET /v1/assets/{id}/shares`, `DELETE /v1/shares/{id}`, `POST /v1/shares/{id}/stream-url`, `GET /v1/events`, `GET /v1/app`, `GET /v1/analytics`, `GET /v1/analytics/assets/{id}`.
### `upload_mismatch` [#upload_mismatch]
The upload token belongs to another upload. Use the token returned with this upload.
Returned by: `POST /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`.
## 404 Not Found [#404-not-found]
### `agent_source_not_found` [#agent_source_not_found]
The PC agent's file is unknown, or was already attached. Push it again with `clipmux push --local`.
Returned by: `POST /v1/assets`.
### `not_found` [#not_found]
No such object in this app, or it was revoked. For playback, the ID is unknown or revoked.
Returned by: `POST /v1/uploads/{id}/parts`, `GET /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`, `POST /v1/uploads/{id}/cancel`, `GET /v1/assets/{id}`, `PATCH /v1/assets/{id}`, `DELETE /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `GET /v1/assets/{id}/tracks/{track_id}`, `DELETE /v1/assets/{id}/tracks/{track_id}`, `GET /v1/assets/{id}/tracks/{track_id}/transcript`, `POST /v1/assets/{id}/playback-ids`, `DELETE /v1/assets/{id}/playback-ids/{pid}`, `POST /v1/assets/{id}/shares`, `GET /v1/assets/{id}/shares`, `DELETE /v1/shares/{id}`, `POST /v1/shares/{id}/stream-url`, `GET /v1/analytics/assets/{id}`, `GET /v/{token}/{pid}/master.m3u8`, `GET /p/{pid}/master.m3u8`, `GET /v/{token}/{pid}/poster.jpg`, `GET /p/{pid}/poster.jpg`, `GET /v/{token}/{pid}/tracks/{track_id}.vtt`, `GET /p/{pid}/tracks/{track_id}.vtt`.
### `pairing_not_found` [#pairing_not_found]
The pairing is unknown, or its credentials were already collected. Start a new pairing.
Returned by: `POST /v1/app-pairings/poll`.
### `share_not_found` [#share_not_found]
The share link is unknown or revoked, its video was deleted, or its app is disabled.
Returned by: `POST /s/{secret}/playback`.
## 409 Conflict [#409-conflict]
### `asset_deleted` [#asset_deleted]
The video was deleted. Nothing more can change it.
Returned by: `PATCH /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `POST /v1/assets/{id}/playback-ids`, `POST /v1/assets/{id}/shares`.
### `asset_not_ready` [#asset_not_ready]
The video isn't ready yet. Wait for `video.asset.ready`, then retry.
Returned by: `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `POST /v1/shares/{id}/stream-url`, `POST /s/{secret}/playback`.
### `chapters_not_connected` [#chapters_not_connected]
No LLM is connected for chapters. Connect one under Captions and AI in the dashboard.
Returned by: `POST /v1/assets/{id}/tracks`.
### `idempotency_in_progress` [#idempotency_in_progress]
A request with this Idempotency-Key is still running. Wait a moment and retry with the same key.
Returned by: `POST /v1/uploads`, `POST /v1/assets`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `POST /v1/assets/{id}/playback-ids`, `POST /v1/assets/{id}/shares`.
### `job_active` [#job_active]
Another job is changing this video; `job_id` names it. Wait for it, or pass `supersede: true` to cancel it.
Returned by: `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`.
### `no_audio` [#no_audio]
The video has no audio track, so there is nothing to transcribe.
Returned by: `POST /v1/assets/{id}/tracks`.
### `share_expired` [#share_expired]
The share link has expired. Make a new one. Also returned as 410.
Returned by: `POST /v1/shares/{id}/stream-url`, `POST /s/{secret}/playback`.
### `share_revoked` [#share_revoked]
The share link was revoked. Make a new one.
Returned by: `POST /v1/shares/{id}/stream-url`.
### `size_mismatch` [#size_mismatch]
The stored file's size differs from the `size` the upload declared. Create a new upload with the right size.
Returned by: `POST /v1/uploads/{id}/complete`.
### `source_missing` [#source_missing]
The video's source file was not kept, so it can't be re-encoded.
Returned by: `POST /v1/assets/{id}/reencode`.
### `source_unavailable` [#source_unavailable]
The source stays on a PC agent that was revoked. Push it again from a connected PC.
Returned by: `POST /v1/assets`.
### `subtitles_not_ready` [#subtitles_not_ready]
Chapters are made from subtitles, which aren't ready. Make subtitles first, or wait for them.
Returned by: `POST /v1/assets/{id}/tracks`.
### `too_many_playback_ids` [#too_many_playback_ids]
A video has at most 1000 playback IDs. Revoke some first.
Returned by: `POST /v1/assets/{id}/playback-ids`, `POST /v1/assets/{id}/shares`.
### `track_not_ready` [#track_not_ready]
The track isn't ready yet. Wait for `video.asset.track.ready`.
Returned by: `GET /v1/assets/{id}/tracks/{track_id}/transcript`.
### `upload_expired` [#upload_expired]
The upload wasn't completed in time. Create a new upload.
Returned by: `POST /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`.
### `upload_missing` [#upload_missing]
Storage no longer has this upload's parts. Create a new upload.
Returned by: `POST /v1/uploads/{id}/complete`.
### `upload_not_active` [#upload_not_active]
The upload has already completed, been cancelled or expired. Create a new upload, with a new Idempotency-Key.
Returned by: `POST /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`.
## 413 Content Too Large [#413-content-too-large]
### `too_large` [#too_large]
The file is larger than this instance or its storage allows, or a request body is larger than its route accepts.
Returned by: `POST /v1/uploads`.
## 422 Unprocessable Content [#422-unprocessable-content]
### `idempotency_key_reused` [#idempotency_key_reused]
The Idempotency-Key was used with a different request. Use a new key for a new request.
Returned by: `POST /v1/uploads`, `POST /v1/assets`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `POST /v1/assets/{id}/playback-ids`, `POST /v1/assets/{id}/shares`.
## 429 Too Many Requests [#429-too-many-requests]
### `rate_limited` [#rate_limited]
Too many requests. Wait `Retry-After` seconds (also `retry_after` in the details), then retry.
Returned by: `POST /v1/uploads`, `POST /v1/uploads/{id}/parts`, `GET /v1/uploads/{id}/parts`, `POST /v1/uploads/{id}/complete`, `POST /v1/uploads/{id}/cancel`, `POST /v1/assets`, `GET /v1/assets`, `GET /v1/assets/{id}`, `PATCH /v1/assets/{id}`, `DELETE /v1/assets/{id}`, `POST /v1/assets/{id}/reencode`, `POST /v1/assets/{id}/tracks`, `GET /v1/assets/{id}/tracks/{track_id}`, `DELETE /v1/assets/{id}/tracks/{track_id}`, `GET /v1/assets/{id}/tracks/{track_id}/transcript`, `POST /v1/assets/{id}/playback-ids`, `DELETE /v1/assets/{id}/playback-ids/{pid}`, `POST /v1/assets/{id}/shares`, `GET /v1/assets/{id}/shares`, `DELETE /v1/shares/{id}`, `POST /v1/shares/{id}/stream-url`, `GET /v1/events`, `GET /v1/app`, `GET /v1/analytics`, `GET /v1/analytics/assets/{id}`, `POST /v1/app-pairings`, `POST /v1/app-pairings/poll`, `POST /s/{secret}/playback`, `GET /v/{token}/{pid}/master.m3u8`, `GET /p/{pid}/master.m3u8`, `GET /v/{token}/{pid}/poster.jpg`, `GET /p/{pid}/poster.jpg`, `GET /v/{token}/{pid}/tracks/{track_id}.vtt`, `GET /p/{pid}/tracks/{track_id}.vtt`.
### `too_many_pairings` [#too_many_pairings]
Ten pairings are already waiting for the owner. Wait for one to be approved or to expire.
Returned by: `POST /v1/app-pairings`.
## A video's error_code [#a-videos-error_code]
When a video's `status` is `errored`, its `error_code` says why. A failed re-encode leaves the video playing and puts the code on the `video.asset.reencode_failed` event's `job`.
| Code | What happened |
| --- | --- |
| `upload_expired` | The upload wasn't completed in time. |
| `upload_cancelled` | The upload was cancelled. |
| `import_failed` | Fetching the URL failed. |
| `import_too_large` | The file at the URL is larger than this instance allows. |
| `import_url_refused` | The URL, or a redirect it followed, is not public. |
| `unsupported_source` | The file is not a video ffmpeg can read. |
| `transcode_failed` | Encoding failed after every retry. |
| `processing_failed` | Processing failed for another reason; the job's logs say why. |
| `source_download_failed` | The worker couldn't download the source from storage. |
| `source_changed` | The source in storage changed while it was being processed. |
| `source_missing` | The source is no longer in storage. |
| `scratch_full` | The worker didn't have the disk for the job: it saw before encoding that the ladder wouldn't fit, or the disk filled during the download or encode. The job may move to a fallback. |
| `job_timeout` | The job ran past its time limit. |
| `worker_lost` | The worker stopped answering mid-job, after every retry. |
| `worker_stopped` | The worker was stopped mid-job, after every retry. |
| `commit_failed` | The finished output couldn't be committed. |
| `upload_failed` | The worker couldn't upload the output to storage. |
| `agent_unavailable` | The PC agent holding the source is no longer connected. |
| `app_disabled` | The video's app was disabled. |
## A track's error_code [#a-tracks-error_code]
When a subtitles or chapters track's `status` is `errored`, its `error_code` says why.
| Code | What happened |
| --- | --- |
| `no_audio` | The video has no audio. |
| `transcribe_failed` | Speech recognition failed. |
| `transcribe_unavailable` | No worker or speech API can transcribe now. |
| `transcript_invalid` | The transcript that came back was not valid. |
| `speech_api_rejected` | The speech API refused the request; check its key and model. |
| `speech_api_unavailable` | The speech API kept failing. |
| `subtitles_failed` | Chapters need subtitles, which failed. |
| `llm_not_connected` | No LLM is connected for chapters. |
| `llm_unavailable` | The model kept failing, through three tries. |
| `model_rejected` | The model's provider refused the request; check its key and model. |
| `model_refused` | The model declined to write chapters for this transcript. |
| `invalid_model_output` | The model's chapters were still invalid after one corrective re-prompt. |
| `transcript_too_large` | The transcript makes a prompt over 512 KB, which is never truncated. |
---
# Limits and defaults
Rate limits, sizes and the defaults a ClipMux instance enforces.
Source: https://clipmux.com/docs/reference/limits
## Rate limits [#rate-limits]
A refused request is `429 rate_limited` with `Retry-After` (seconds), and
`retry_after` in the error details. Wait that long, then retry. Limits are
per server process.
| Surface | Counted by | Limit |
| --- | --- | --- |
| Integration API (an API key, or the owner's session acting as an app) | key | 20 requests a second, bursts of 200. Of those, writes (`POST`, `DELETE`) 2 a second, bursts of 60. |
| `GET /v1/events` | key | 4 long-polls at once. |
| `/v1/uploads/{id}/*` with an upload token | upload | 10 requests a second, bursts of 50. |
| `POST /v1/app-pairings` | address | 20 an hour, and at most 10 waiting at once (`too_many_pairings`). |
| `POST /v1/app-pairings/poll` | address | 2 a second, bursts of 4. |
| `POST /s/{secret}/playback` | address | 2 successes a second, bursts of 20. |
| Playback (`/v/`, `/p/`) | address | Only refusals count: after 300 answers of 401, 403 or 404 in 5 minutes, every playback request from that address gets 429 until they age out. Successful playback is never limited. |
| Owner sign-in | address, and overall | 5 failed sign-ins per address and 20 overall in 15 minutes. A browser the owner has signed in from before skips the overall limit. |
An address is the client's as the trusted proxy reports it
(`CLIPMUX_TRUSTED_PROXIES`); IPv6 addresses are grouped by their /64.
## Uploads and videos [#uploads-and-videos]
| What | Limit |
| --- | --- |
| Upload size | 312.5 GiB (10,000 parts of 32 MiB), or `CLIPMUX_MAX_UPLOAD_BYTES` if lower. |
| Part size | 32 MiB, the last part smaller. |
| Part URLs per request | 100, each valid for an hour. |
| An upload left idle | Expires after 24 hours, as `upload_expired`. |
| `title` | One line, up to 200 characters. |
| `passthrough` | Up to 255 bytes. |
| Playback IDs per video | 1000. |
| Renditions | `2160p`, `1440p`, `1080p`, `720p`, `480p` and `360p`, never above the source. |
| Share link `name` | One line, up to 100 characters. |
## Requests [#requests]
| What | Limit |
| --- | --- |
| Request body | JSON, up to 64 KiB. |
| `Idempotency-Key` | Up to 255 bytes. |
| Page size | Up to 100 items, with `next_cursor`. |
| `GET /v1/events` long-poll | Up to 25 seconds. |
## Playback tokens [#playback-tokens]
| What | Default |
| --- | --- |
| Longest token lifetime (`exp - iat`) | 7 days. `GET /v1/app` returns the instance's value as `max_token_lifetime_seconds`. |
| Signing | ES256, with the app's signing key; the `kid` header names it. |
| Audiences | `v` plays everything, including the content key; `t` fetches only the poster. |
## Webhooks [#webhooks]
| What | Default |
| --- | --- |
| Timestamp tolerance | 300 seconds. |
| Retries | Back off for 24 hours; then catch up with `GET /v1/assets?updated_since=`. |
| Success | Any 2xx. Redirects are not followed. |
## Analytics [#analytics]
| What | Default |
| --- | --- |
| Ranges | `24h`, `7d`, `30d` and `90d`. |
| History kept | 180 days. |
---
# Environment variables
Every setting of the server, the worker, the CLI and your app's backend.
Source: https://clipmux.com/docs/reference/configuration
Every setting is an environment variable; nothing is read from a file except
the keys serve keeps under `CLIPMUX_DATA_DIR`. The repository's `.env.example`
lists each variable with an example. A test fails when the server reads a
variable this page doesn't name, so the list is complete.
A value that doesn't parse stops the command at start, naming the variable.
## clipmux serve [#clipmux-serve]
| Variable | Default | What it does |
| --- | --- | --- |
| `DATABASE_URL` | required | Postgres. pgxpool options go in the URL (`pool_max_conns=20`); session settings too (`statement_timeout=30s`). Unset, every session gets `statement_timeout=60s` and `idle_in_transaction_session_timeout=5min`. serve waits up to a minute for Postgres at boot. |
| `CLIPMUX_LISTEN` | `:8080` | Where serve listens. Behind Caddy, keep it off the public interface. |
| `CLIPMUX_DATA_DIR` | `./data` | Filesystem storage, the storage signing key, and the secrets key when `CLIPMUX_SECRETS_KEY` is unset. Back it up. |
| `CLIPMUX_SECRETS_KEY` | `{data_dir}/secrets.key` | `v1:` and 64 hex digits; seals every secret kept in Postgres. Losing it makes every stored secret, and every output, unusable. |
| `CLIPMUX_SECRETS_KEY_PREVIOUS` | unset | The key being rotated away from, only until `clipmux admin reseal-secrets` has run. |
| `CLIPMUX_BACKUP_URL` | `file://{data_dir}/backups` | Where backups go: `s3://bucket/prefix?endpoint=https://…®ion=…` for an S3-compatible bucket (Backblaze B2, R2, S3), or `file:///absolute/path`. The default is the server's own disk. |
| `CLIPMUX_BACKUP_ACCESS_KEY_ID`, `CLIPMUX_BACKUP_SECRET_ACCESS_KEY` | unset | The bucket's credentials; required for an `s3://` target. Use a key that can write and list but not delete. |
| `CLIPMUX_BACKUP_INTERVAL` | `1h`; `24h` for the default directory | Time between scheduled backups, a duration of at least `1m`. `0` turns scheduled backups off; `clipmux admin backup now` still works. |
| `CLIPMUX_BACKUP_RECIPIENTS` | none | More age recipients (`age1…`, comma-separated) every backup is encrypted to, such as a key you keep offline. |
| `CLIPMUX_BACKUP_PING_URL` | unset | A URL fetched after each successful scheduled backup, for a dead man's switch such as healthchecks.io or an Uptime Kuma push monitor. |
| `CLIPMUX_BACKUP_BEFORE_MIGRATE` | `true` | Back the database up (kind `pre_migrate`) before applying pending migrations, at boot and in `clipmux admin` commands, and refuse to migrate if the backup fails. `false` migrates without one. A new database has nothing to back up. |
| `CLIPMUX_PG_DUMP` | `pg_dump` on `PATH` | The PostgreSQL 18 `pg_dump` backups run. The image has it. |
| `CLIPMUX_PUBLIC_URL` | chosen at first boot | The origin browsers and workers reach serve at. Set, it pins both URLs and the first-boot URL step is read-only. |
| `CLIPMUX_MEDIA_URL` | `CLIPMUX_PUBLIC_URL` | The origin playback is served from (`base_url`); ideally another registrable domain. Needs `CLIPMUX_PUBLIC_URL`. |
| `CLIPMUX_TRUSTED_PROXIES` | none | Addresses or CIDR ranges (Caddy's) whose `X-Forwarded-For`, `X-Forwarded-Proto` and `X-Request-Id` are believed. Rate limits, sign-in limits, request IDs and the https redirect all depend on it. |
| `CLIPMUX_MAX_UPLOAD_BYTES` | the storage limit (~312 GiB) | The largest declared upload. |
| `CLIPMUX_BUILTIN_WORKER` | `true` | Start `clipmux worker` as serve's child. |
| `CLIPMUX_UNSANDBOXED_WORKER` | `false` | Run the built-in worker where the media tool sandbox or Landlock doesn't hold. Only if the host isolates it another way. Where only Landlock is missing, the tools keep seccomp and the limits. |
| `CLIPMUX_TOOL_MEMORY_MB` | `8192` | Memory limit for each media tool. Passed to the built-in worker. |
| `CLIPMUX_FFMPEG`, `CLIPMUX_FFPROBE`, `CLIPMUX_PACKAGER`, `CLIPMUX_WHISPER` | found on `PATH` | The media tools. Shaka Packager must be 3.9.1 or later; `whisper-cli` is the pinned whisper.cpp from `toolchain/build_whisper.sh`, used only to transcribe. |
| `CLIPMUX_LOG_FORMAT` | `text` | `text` or `json`. Passed to the built-in worker. |
| `CLIPMUX_LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error`. Successful playback, storage and worker requests log at debug. |
| `CLIPMUX_METRICS_ADDR` | unset (off) | `host:port` for `/metrics`, a listener of its own with no auth: keep it off the internet. |
| `CLIPMUX_PPROF` | `false` | Add Go's `/debug/pprof/` to the metrics listener. Needs `CLIPMUX_METRICS_ADDR`. |
| `CLIPMUX_SELF_DIAL` | unset | Where the setup test connects for every URL it checks, keeping each URL's hostname (compose: `caddy`). |
| `CLIPMUX_CLOUDFLARE_API` | Cloudflare's v4 API | Cloudflare's API base, for a proxy or a test double. |
| `CLIPMUX_R2_ENDPOINT` | `https://{account_id}.r2.cloudflarestorage.com` | R2's S3 endpoint, e.g. the EU jurisdiction's. |
| `CLIPMUX_RUNPOD_API` | RunPod's v2 REST API | RunPod's API base, for a test double. |
| `CLIPMUX_RUNPOD_CATALOG` | RunPod's v2 API | Where RunPod's GPU prices come from, for a test double. |
| `CLIPMUX_WORKER_IMAGE` | the image this build names | The image RunPod and Modal machines run. |
| `CLIPMUX_EXECUTORS_ALLOW_PRIVATE_URL` | `false` | Connect RunPod or Modal while the public URL is private: development only. |
## clipmux worker [#clipmux-worker]
A PC agent paired with `--pair` keeps its server and key in `agent.json` and
needs none of these; the built-in worker gets its own from serve.
| Variable | Default | What it does |
| --- | --- | --- |
| `CLIPMUX_SERVER` | from `agent.json` | The server's public URL. |
| `CLIPMUX_WORKER_KEY` | from `agent.json` | The worker's key. Never in argv. |
| `CLIPMUX_AGENT_DIR` | the user's config directory | Where `agent.json`, `sources.json` and `agent.sock` live. |
| `CLIPMUX_ENCODER` | `auto` | The first encoder to try: `auto`, `nvenc`, `vaapi`, `cuda-decode` or `cpu`. |
| `CLIPMUX_VAAPI_DEVICE` | every `/dev/dri/renderD*` | The VAAPI render node. |
| `CLIPMUX_SPEECH` | `auto` | Whether the worker transcribes subtitles: `auto` (on a GPU whose probe passes, CUDA first and then Vulkan, else on a CPU with at least 4 cores and 6 GiB), `off`, `cpu`, `vulkan` or `cuda`. serve passes it to the built-in worker. |
| `CLIPMUX_FOLLOW_ON_SPEECH` | unset | Set by serve on a serverless machine woken for an encode, never by hand: the speech mode (`auto`) it proves speech in if serve hands it the asset's transcription after the encode. `off` or unset: it takes no transcription. |
| `CLIPMUX_BAKED_MODELS_DIR` | `/usr/share/clipmux/models` in the image; unset elsewhere | The speech models baked into the image. A worker uses them when they are there, and downloads nothing. serve passes it to the built-in worker. |
| `CLIPMUX_MODELS_DIR` | `models/` in `CLIPMUX_AGENT_DIR`; the built-in worker's is `models/` in serve's data directory | Where a worker without baked models keeps the speech models it downloads by digest (about 0.9 GB), across restarts. |
| `CLIPMUX_TOOL_MEMORY_MB`, `CLIPMUX_FFMPEG`, `CLIPMUX_FFPROBE`, `CLIPMUX_PACKAGER`, `CLIPMUX_WHISPER`, `CLIPMUX_LOG_FORMAT`, `CLIPMUX_LOG_LEVEL` | as for serve | |
## clipmux push and clipmux listen [#clipmux-push-and-clipmux-listen]
| Variable | Default | What it does |
| --- | --- | --- |
| `CLIPMUX_API_KEY` | required | The app's API key. Never in argv. |
| `CLIPMUX_PUSH_STATE_DIR` | the user's cache directory | Where unfinished pushes keep their upload tokens (0600). |
| `CLIPMUX_LISTEN_SECRET` | generated once, kept beside `agent.json` | The `whsec_` secret `listen` signs forwarded events with. |
## clipmux admin [#clipmux-admin]
`clipmux admin` reads `DATABASE_URL`, and where it needs secrets
`CLIPMUX_DATA_DIR`, `CLIPMUX_SECRETS_KEY` and `CLIPMUX_SECRETS_KEY_PREVIOUS`,
the same as serve. `clipmux admin` with no arguments lists its commands.
## The installer and Compose [#the-installer-and-compose]
These live in `/opt/clipmux/.env` (or are set when you run the installer).
Docker Compose and the installers read them; `clipmux` itself doesn't.
| Variable | Default | What it does |
| --- | --- | --- |
| `CLIPMUX_VERSION` | the release installed | The image tag Compose runs. The installer changes only this line on an upgrade. |
| `CLIPMUX_IMAGE` | `ghcr.io/visheshgubrani/clipmux` | The image, without its tag. |
| `CLIPMUX_HTTP_PORT` | `80` | The host port Caddy listens on for HTTP. |
| `CLIPMUX_HTTPS_PORT` | `443` | The host port Caddy listens on for HTTPS. |
| `CLIPMUX_ADMIN_PORT` | `8080` | The loopback port the app is published on, `127.0.0.1` only. |
| `CLIPMUX_RELEASE_URL` | the release on GitHub | Installers only: where to download the release's files from. |
## Your app's backend [#your-apps-backend]
These are not read by ClipMux: they are what an app's backend reads, as
`npx @clipmux/node init`, `clipmux admin create-integration` and the
dashboard's "Create credentials" write them. Keep them on the
server; none belongs in a browser bundle.
| Variable | What it holds |
| --- | --- |
| `CLIPMUX_URL` | The server's public URL, which the backend calls. |
| `CLIPMUX_API_KEY` | The app's `cmx_` API key, with `uploads:write`, `assets:read` and `assets:write`. |
| `CLIPMUX_SIGNING_KID` | The kid of the app's signing key, the `kid` header of every playback token. |
| `CLIPMUX_SIGNING_KEY` | The ES256 private key (PKCS #8 PEM) as one double-quoted line with `\n` escapes, which dotenv, Next.js and `node --env-file` expand. |
| `CLIPMUX_WEBHOOK_SECRET` | The `whsec_` secret webhook deliveries are signed with; only when a webhook URL was given. |
---
# Command line
The clipmux binary and the npx @clipmux/node commands, with every flag.
Source: https://clipmux.com/docs/reference/cli
There are two command lines. `clipmux` is the server's own binary: it runs
the server and workers, and administers an instance from its host.
`npx @clipmux/node` runs inside your app's project, against a server.
## clipmux [#clipmux]
```text
clipmux serve API, dashboard, scheduler and built-in delivery
clipmux worker run a worker (agent mode; --once for serverless)
clipmux push upload files through the API
clipmux listen forward webhooks to a local URL
clipmux admin host-side administration (keys, webhooks, reset-password)
clipmux version print the version
```
Every setting is an environment variable; see
[Environment variables](/docs/reference/configuration).
### clipmux serve [#clipmux-serve]
Runs the API, the dashboard, the scheduler and built-in delivery, and starts
a worker as its child unless `CLIPMUX_BUILTIN_WORKER=false`. It takes no
flags. It migrates the database on start, prints a setup token on first
boot, and on a stop signal drains requests and waits for its loops before it
exits.
### clipmux worker [#clipmux-worker]
Claims and runs media jobs: a PC agent, the built-in worker, or a serverless
machine.
```text
clipmux worker --server URL connect this PC (approve it in the dashboard)
clipmux worker --server URL --pair CODE connect with a code from clipmux admin create-pairing
clipmux worker run, once this PC is connected
clipmux worker doctor [--offline] check everything this PC needs (--offline: before pairing)
CLIPMUX_WORKER_KEY=KEY clipmux worker --server URL [--once]
```
| Flag | Default | What it does |
| --- | --- | --- |
| `--server URL` | `CLIPMUX_SERVER`, else `http://127.0.0.1:8080` | The server's public URL. |
| `--pair CODE` | | Connect this PC with a pairing code from `clipmux admin create-pairing`. |
| `--name NAME` | the hostname | What to call this PC. |
| `--once` | `false` | Run at most one job, then exit (serverless). |
| `--work-dir DIR` | a `clipmux-worker` temporary directory | Scratch space for attempts. |
| `--encoder MODE` | `CLIPMUX_ENCODER`, else `auto` | The first encoder to try: `auto`, `nvenc`, `vaapi`, `cuda-decode` or `cpu`. The CPU always backs it up. |
| `--speech MODE` | `CLIPMUX_SPEECH`, else `auto` | Transcribe subtitles: `auto` (a GPU, or a CPU with 4+ cores and 6 GiB), `off`, `cpu`, `vulkan` or `cuda`. |
| `--sandbox` | `false` | Confine ffmpeg and the packager (Linux). Agents always do, unless `--unsandboxed`. |
| `--unsandboxed` | `false` | Run an agent's tools unconfined. It then gets only its own local jobs and the owner's uploads. |
| `--storage-via-server` | `false` | Fetch and upload signed storage URLs through `--server`, as the built-in worker does. |
A connected PC keeps its server and key in `agent.json` under
`CLIPMUX_AGENT_DIR`, so the key never shows in a process listing.
### clipmux push [#clipmux-push]
Uploads files through the API, resuming an interrupted upload. It reads the
app's API key from `CLIPMUX_API_KEY`, never from a flag.
```bash
CLIPMUX_API_KEY=cmx_… clipmux push --server https://video.example.com lesson-42.mp4
```
| Flag | Default | What it does |
| --- | --- | --- |
| `--server URL` | `CLIPMUX_SERVER` | The server's public URL. |
| `--policy POLICY` | `signed` | The playback policy: `signed` or `public`. |
| `--passthrough REF` | | Your own reference, returned in webhooks (one file only). |
| `--renditions LIST` | every rung up to the source | Rungs to encode, comma separated, e.g. `1080p,480p`. |
| `--wait` | `false` | Wait until each video is ready to play. |
| `--quiet` | `false` | Print only the asset and playback IDs. |
| `--local` | `false` | Keep the files on this PC: its agent encodes them and uploads only the outputs. |
| `--upload-source` | `false` | With `--local`: once encoded, also upload each file, so any worker can re-encode it. |
### clipmux listen [#clipmux-listen]
Forwards the app's webhook events to a local URL while you build, signed so
your handler verifies them unchanged. It reads `CLIPMUX_API_KEY`.
| Flag | Default | What it does |
| --- | --- | --- |
| `--server URL` | `CLIPMUX_SERVER`, else `CLIPMUX_URL` | The server's public URL. |
| `--forward-to URL` | | The local webhook URL, e.g. `localhost:3000/webhooks`. |
| `--events LIST` | every event | The event types to forward, comma separated. |
| `--since DURATION` | | Also replay events from this long ago, e.g. `10m`. |
### clipmux admin [#clipmux-admin]
Host-side administration, alongside the dashboard. It reads `DATABASE_URL`,
and where it needs secrets `CLIPMUX_DATA_DIR` or `CLIPMUX_SECRETS_KEY`, the
same as serve. Each command that makes a secret prints it once.
| Command | What it does |
| --- | --- |
| `clipmux admin create-key --app NAME [--name KEY_NAME] [--scopes …] [--allow-loopback]` | Create an API key for the app (and the app, if it doesn't exist). |
| `clipmux admin create-signing-key --app NAME` | Create a signing key and print its private key; only the public key is kept. |
| `clipmux admin create-webhook --app NAME --url URL` | Add a webhook endpoint and print its secret. |
| `clipmux admin create-integration --app NAME [--webhook-url URL] [--allow-loopback]` | All three at once, printed as a `.env` block to append to the backend's env file. |
| `clipmux admin create-pairing [--app PC-NAME]` | Make a code for `clipmux worker --pair`. |
| `clipmux admin rotate-signing-key --app NAME` | Create a new signing key and retire the others once the longest token they may have signed has expired. |
| `clipmux admin list-keys --app NAME` | List the app's API and signing keys. |
| `clipmux admin revoke-key ID` | End an API key (`cmx_…` ID) or a signing key (`kid_…`) at once. |
| `clipmux admin setup-test [--wait] [--timeout 20m]` | Put the sample through the configured path; with `--wait`, print the checks and exit 1 unless they all pass. |
| `clipmux admin reset-password < new-password.txt` | Set the owner's password from stdin and end every dashboard session. |
| `clipmux admin reset-totp` | Turn off the owner's second factor, for an owner who lost the authenticator and the recovery codes. |
| `clipmux admin migrate status \| up \| down-to VERSION --yes` | Show, apply or roll back database migrations. |
| `clipmux admin prune [--dry-run] [--files]` | Delete rows past their retention windows now; `--files` also deletes stored files past theirs. |
| `clipmux admin reseal-secrets` | Seal every stored secret with the current secrets key, when rotating it. |
| `clipmux admin outbox [--retry ID]` | List side effects still pending after an hour; `--retry` makes one due at once. |
| `clipmux admin restore [--list] [--latest \| --id ID \| --file PATH] --yes` | Replace the database with a backup: the newest, one by ID, or a dump file on this host. Refuses while a serve runs, and a backup that is damaged, newer than this binary or that this install's secrets key doesn't open. Backs up the database it replaces first (kind `pre_restore`), migrates the restored one and raises the restore fence. Without `--yes` it only names the backup; `--list` shows what the target holds. |
| `clipmux admin restore report` | List what storage holds that the database doesn't know (route records, output prefixes, sources), and whether the restore fence is up. |
| `clipmux admin restore finish --yes` | Lift the restore fence and stamp every store as this install's. Serve then deletes what the database doesn't know. Read the report first. |
| `clipmux admin backup now` | Back up the database now, without migrating it first. Prints the backup's ID, where it went and its SHA-256. |
| `clipmux admin backup list` | List the backups on the target, read from their manifests, so it works on a host with no database. |
| `clipmux admin backup check` | Prove the target can be written, read and listed, say whether it refuses deletes, and show the latest backup. Exits 1 when the target doesn't work. |
| `clipmux admin backup verify [--id ID]` | Verify the newest backup by default or select one by ID. Checks its hash, decrypts it, restores it into a scratch database, and checks the secrets key, content keys and row counts. Records the result and exits 1 if the backup fails. |
| `clipmux admin backup restore-sources --asset ID \| --all` | After a store lost files: copy mirrored sources back to the stores they belong on and queue a re-encode for each asset whose source was restored or whose encoded files are gone, through the usual job path. Skips assets deleted after the backup (they have a tombstone); running it again restores nothing twice. |
| `clipmux admin backup prune-sources [--older-than DURATION]` | Delete the mirrored copies of assets deleted at least that long ago (default 720h), and their tombstones. Needs a backup key that may delete; on an immutable target the bucket's lifecycle rules do this. |
| `clipmux admin backup identity` | Print the age identities that open the backups, derived from the secrets key. They are secret: `age -d -i <(clipmux admin backup identity) FILE` opens a backup without ClipMux. |
`create-key` and `create-integration` refuse while the public URL is
loopback, because signed upload URLs and `base_url` would point at the
server's own machine; `--allow-loopback` is for local development.
## npx @clipmux/node [#npx-clipmuxnode]
The SDK's command line, run in your app's project. Every command takes
`--env-file FILE`.
| Command | What it does |
| --- | --- |
| `npx @clipmux/node init` | Connect this app to a server: the owner approves it in the dashboard, and the credentials go to an env file without being printed. |
| `npx @clipmux/node doctor` | Check the env file: the server, the API key, the signing key and the webhook secret. |
| `npx @clipmux/node listen` | Forward this app's webhook events to a local URL, signed with `CLIPMUX_WEBHOOK_SECRET`. |
| `npx @clipmux/node upload FILE` | Upload a file. |
| Flag | Command | What it does |
| --- | --- | --- |
| `--server URL` | `init` | The server's public URL (default `CLIPMUX_URL`). |
| `--env-file FILE` | every command | Where to read and write (default `.env.local`, or `.env` if it exists). |
| `--name NAME` | `init` | The name the owner sees (default `package.json`'s name). |
| `--no-open` | `init` | Print the approval URL instead of opening a browser. |
| `--forward-to URL` | `listen` | The local URL, e.g. `localhost:3000/api/clipmux/webhook`. |
| `--events LIST` | `listen` | Only these event types, comma separated. |
| `--since DURATION` | `listen` | Also replay events from this long ago, e.g. `10m`. |
| `--passthrough REF` | `upload` | Your own reference. |
| `--title TITLE` | `upload` | The video's title. |
| `--renditions LIST` | `upload` | Rungs to encode, e.g. `1080p,480p`. |
| `--public` | `upload` | Make a public playback ID instead of a signed one. |
| `--wait` | `upload` | Wait until the video is ready. |
---
# Management API
The owner routes the dashboard calls to set up the server, manage apps and keys, and run the library.
Source: https://clipmux.com/docs/reference/management-api
These are the routes the dashboard uses. They need the owner's session
cookie, no API key can reach them, and they may change between releases.
To integrate an app, use the [integration API](/docs/reference/api)
instead.
The dashboard is a client of these routes, with no private path into the
server. This page lists every one, so you can see what the dashboard can do
and script your own server from a signed-in browser if you need to.
## Authentication [#authentication]
- **The session cookie.** Signing in (`POST /v1/session`) sets
`__Host-clipmux_session` when the public URL is `https`, or
`clipmux_session` when it isn't. The cookie is `HttpOnly` and
`SameSite=Strict`. A session lasts 30 days, and ends after 7 days without
use.
- **No cookie, or an ended session**, is `401 unauthorized`.
- **Cross-site requests.** A request that changes state and comes from
another site is `403 cross_origin`.
- **The integration API as one app.** The same session also reaches the
integration API, acting as one app: the app the `ClipMux-App: app_…`
header names, or the built-in Dashboard app without it. An unknown app is
`404 not_found`.
- **Requests and errors** are JSON, as in the integration API; see
[Errors](/docs/reference/errors). A route for a feature this server
doesn't run answers `404`.
## Setup and session [#setup-and-session]
### Setup state [#setup-state]
`GET /v1/setup`
Needs no session: the first-boot wizard calls it before an owner exists.
Returns `{owner_exists, urls: {public_url, media_url, confirmed, pinned}, keys_allowed, setup_test}`.
`setup_test` is `{id, status}` of the latest setup test, or `null`.
### Create the owner [#create-the-owner]
`POST /v1/setup/owner`
Body `{setup_token, email, password}`. The setup token is printed in the
server log on first boot. Returns `201 {email}` and signs the owner in.
- `403 invalid_setup_token`: the token is wrong. Five wrong tokens from one
address are `429` with `Retry-After`.
- `400 weak_password`: a password is 12 to 1024 characters.
- `400 invalid_request`: the email isn't an address.
- `409 registration_closed`: an owner already exists.
### Sign in, check the session, sign out [#sign-in-check-the-session-sign-out]
`POST /v1/session` · `GET /v1/session` · `DELETE /v1/session`
- `POST /v1/session`: body `{email, password}`, plus `code` (from the
authenticator) or `recovery_code` once two-factor sign-in is on. Returns
`{email}` and sets the cookie.
- `GET /v1/session`: `{email, totp_enabled}`.
- `DELETE /v1/session`: `204`, and the cookie is cleared.
Errors on sign-in:
- `401 invalid_credentials`: wrong email or password.
- `401 totp_required`: two-factor sign-in is on and no code was sent.
- `401 invalid_code`: the code is wrong or was already used. It counts as a
failed sign-in.
- `429 too_many_attempts`, with `Retry-After`: 5 failed sign-ins from one
address, or 20 overall, in 15 minutes. A browser the owner has signed in
from before skips the overall limit.
### Change the password [#change-the-password]
`PUT /v1/session/password`
Body `{current_password, new_password}`. Returns `204`. Every other session
ends; this one stays signed in.
- `400 weak_password`: the new password isn't 12 to 1024 characters.
- `401 invalid_credentials`: the current password is wrong. It counts as a
failed sign-in.
### Two-factor sign-in [#two-factor-sign-in]
`POST /v1/session/totp` · `POST /v1/session/totp/enable` · `POST /v1/session/totp/disable`
- `POST /v1/session/totp`: body `{password}`. Returns
`201 {secret, otpauth_url}`, a new authenticator secret waiting for a code.
- `POST /v1/session/totp/enable`: body `{code}`. Returns
`{enabled: true, recovery_codes}`, ten recovery codes shown only here.
Every other session ends. `409 totp_not_started` without the step above.
- `POST /v1/session/totp/disable`: body `{password}`. Returns
`{enabled: false}`.
An owner locked out of their authenticator runs `clipmux admin reset-totp`
on the host; see [Command line](/docs/reference/cli).
## Settings [#settings]
### URLs [#urls]
`PUT /v1/settings/urls`
Body `{public_url, media_url?}`. Returns `{urls, keys_allowed}`.
`409 pinned` when `CLIPMUX_PUBLIC_URL` sets them; `400 invalid_request` for
a URL the server refuses.
### Routing [#routing]
`GET /v1/settings/routing` · `PUT /v1/settings/routing`
`GET` returns
`{primary_executor, fallback_executor, queue_age_fallback_minutes, builtin_worker: {last_seen_at, online}, providers_ready}`.
`providers_ready` lists the providers (`modal`, `runpod`) that are connected
and have passed a setup test.
`PUT` takes `{primary_executor, fallback_executor?, queue_age_fallback_minutes?}`
and returns the routing as `GET` does.
- `primary_executor`: `workers`, `agents`, `builtin`, `modal` or `runpod`.
- `fallback_executor`: `null`, `builtin`, `modal` or `runpod`. `builtin`
can't back up `builtin` or `workers`, which already include it, and a
provider can't back up itself.
- `queue_age_fallback_minutes`: 1 to 1440, and only with a fallback.
- `400 invalid_request` for a choice outside these rules.
- `409 executor_not_connected` for a provider that isn't connected or hasn't
passed its setup test.
A provider's passing connect test sets routing itself: that provider as
primary, and `builtin` as fallback when the server runs the built-in worker.
### Backups [#backups]
`GET /v1/settings/backups` · `POST /v1/settings/backups/run` · `PUT /v1/settings/backups/recovery-kit`
`GET` returns what the dashboard's Backups card shows:
```json
{
"enabled": true,
"target": "s3://bucket/clipmux/",
"interval_seconds": 3600,
"off_site": true,
"immutable": true,
"last": {"id": "bak_…", "kind": "scheduled", "created_at": "…", "size_bytes": 1048576},
"verified": {"backup_id": "bak_…", "at": "…", "mode": "restore", "error": ""},
"error": null,
"requested": false,
"sources_pending": 0,
"fence": null,
"recovery_kit_confirmed_at": null
}
```
- `enabled` is false when `CLIPMUX_BACKUP_INTERVAL` is `0`. The target, the
interval and the schedule are environment settings, so they are shown and
not edited here.
- `off_site` is false for a directory on this server's own disk.
- `immutable` is true when the target's key can't delete, false when it can,
and `null` until a backup has found out since serve started.
- `last` is the newest backup. `verified` is the newest check of one,
failed or not: `mode` is `restore` (loaded into a scratch database) or
`integrity` (the file only, for a database role that can't create
databases), and `error` says what failed.
- `error` is why the newest attempt failed, until a backup succeeds
(`{at, message}`).
- `requested` is true while a `POST …/run` waits for serve.
- `sources_pending` counts committed sources not yet copied to the target.
- `fence` is `{reason, detail, detected_at}` while the restore fence is up
and storage deletes are stopped.
- `recovery_kit_confirmed_at` is when the owner said the secrets key and
`DATABASE_URL` are stored off this server.
`POST …/run` asks for a backup now and returns `202 {requested: true}`. serve
takes it on its next pass, within a minute, since only it runs `pg_dump`.
`409 backups_off` when backups are off.
`PUT …/recovery-kit` takes `{confirmed}` and returns
`{recovery_kit_confirmed_at}`: the time, or `null` once withdrawn.
### Speech [#speech]
`GET /v1/settings/speech` · `PUT /v1/settings/speech`
`GET` returns `{mode, connection: {base_url, model, has_key, verified_at} | null}`.
The key is never returned. `mode` is where transcriptions run:
- `local`: whisper.cpp on the server's own workers.
- `api`: every transcription goes to the connected speech API.
- `local_then_api`: the speech API, when no worker that can transcribe is
online or after the queue-age setting.
`PUT` takes `{mode}` and returns the speech settings. `api` and
`local_then_api` are `409 speech_not_connected` until a speech API is
connected. Queued transcriptions move to match.
### Connect a speech API [#connect-a-speech-api]
`POST /v1/settings/speech/connect` · `DELETE /v1/settings/speech/connect`
Once a mode uses the connected speech API, each video's audio goes to
that API's server.
`POST` takes `{base_url, model, api_key?}`, for any OpenAI-compatible
`/audio/transcriptions` API with `verbose_json` timestamps. The key may be
empty for a server that needs none. Returns `{connected, steps}`, each step
`{name, ok, detail?}`: `credentials` (`GET {base_url}/models`),
`transcription` (a short sample of speech, sent as transcriptions send
audio), and `saved`.
`DELETE` forgets the connection, returns the mode to `local`, and returns the
speech settings. `404` when none is connected.
### List a speech API's models [#list-a-speech-apis-models]
`POST /v1/settings/speech/models`
Body `{base_url, api_key?}`. Returns `{listed, data: [{id}]}`: the models the
API lists at `GET {base_url}/models`, sorted. `listed` is `false` for an API
without that route. Nothing is saved. `400 key_rejected` when the API refuses
the key; `502 models_unavailable` for any other failure.
### Chapters LLM [#chapters-llm]
`GET /v1/settings/chapters`
Returns `{connection: {provider, base_url?, model, response_format?, has_key, verified_at} | null}`.
The key is never returned.
### Connect a chapters LLM [#connect-a-chapters-llm]
`POST /v1/settings/chapters/connect` · `DELETE /v1/settings/chapters/connect`
Whenever chapters are made, the video's transcript text goes to the
connected provider.
`POST` takes `{provider, base_url?, model?, api_key?}`:
- `openai_compatible`: any `/chat/completions` API. Needs `base_url` and
`model`; the key may be empty for a server that needs none.
- `anthropic`: Claude through Anthropic's API. Needs `api_key`; `model`
defaults to `claude-opus-5-5`.
Returns `{connected, steps}`: `credentials`, `structured_output` (chapters of
a fixed sample transcript), and `saved`.
`DELETE` forgets the connection and returns the chapters settings. Chapters
already queued end `llm_not_connected`; ready ones keep playing. `404` when
none is connected.
### List a chapters LLM's models [#list-a-chapters-llms-models]
`POST /v1/settings/chapters/models`
Body `{provider, base_url?, api_key?}`. Returns `{listed, data: [{id, name?}]}`.
`openai_compatible` needs `base_url`; `anthropic` needs `api_key`. Errors as
for speech models.
### Rotate the content key secret [#rotate-the-content-key-secret]
`POST /v1/content-keys/rotate`
Body `{cloudflare_token?}`. Adds a content key secret version that new
outputs use; existing outputs keep theirs, so nothing stops playing. Returns
`{version, usable, current, steps}`.
With Cloudflare delivery the token is required (`409 cloudflare_token_required`):
the Worker is redeployed with the new version before any output uses it. If
that fails, the response is `502` with the steps, and the new version stays
unused until you rotate again.
## Executors [#executors]
### List providers [#list-providers]
`GET /v1/executors`
Returns `{data: [{kind, connected, verified, verified_at?, config, max_concurrent, monthly_limit_cents, rate_cents_per_hour, disk_bytes, month_cents, billed_cents?, billed_through?, machines, backoff_until?}]}`:
every provider ever connected, with this month's spend. `month_cents` is the
provider's own bill up to `billed_through` plus an estimate since, or the
estimate alone where there is no bill.
### Connect RunPod [#connect-runpod]
`POST /v1/executors/runpod/connect`
For each encode on RunPod, the job's source video goes to a RunPod
machine, which uploads the encoded files back to your storage.
Body
`{api_key, image?, registry_username?, registry_password?, gpu_type_ids?, disk_gb?, max_concurrent?, monthly_limit_cents?, rate_cents_per_hour?}`.
A monthly limit left out is 5000 cents ($50), and `max_concurrent` left out
is 10 machines at once. Returns
`{connected, steps: [{name, ok, detail?}]}`, stopping at the first failed
step. Connecting again replaces the key. `400 invalid_request` for a setting
it refuses.
### Connect Modal [#connect-modal]
`POST /v1/executors/modal/connect`
For each encode on Modal, the job's source video goes to a Modal
sandbox, which uploads the encoded files back to your storage.
Body
`{token_id, token_secret, environment?, image?, registry_username?, registry_password?, gpu?, cpu?, memory_mib?, disk_gb?, max_concurrent?, monthly_limit_cents?, rate_cents_per_hour?}`.
`gpu` is a comma-separated list such as `L4,T4`. Defaults and the response
are as for RunPod.
### Approve in the browser instead of pasting a key [#approve-in-the-browser-instead-of-pasting-a-key]
`POST /v1/executors/runpod/authorize` · `POST /v1/executors/modal/authorize`
Body: the matching `connect` body without `api_key` or `token_id` and
`token_secret`. Returns `201 {id, url, code?, expires_at, status: "pending"}`.
Open `url`, the provider's own page (Modal shows `code`).
- `400 invalid_request`: the settings are checked before the approval starts.
- `429 too_many_approvals`: three approvals are already waiting.
- `502 approval_unavailable`: the provider won't start one; paste a key
instead.
Waiting approvals are kept in memory, so a server restart means starting
again.
### Poll an approval [#poll-an-approval]
`GET /v1/executors/{kind}/authorize/{id}`
Checks the approval once. Returns
`{id, expires_at, status, result?}`, where `status` is `pending`, `approved`,
`denied`, `expired` or `shown`. `shown` means the provider put the key on
its own page for you to paste instead. Once approved, the provider's
`connect` runs with the credentials it issued, which never reach the
browser, and `result` is its `{connected, steps}`. A settled approval gives
every later poll the same answer. `404 not_found` once it has expired.
### List GPUs [#list-gpus]
`POST /v1/executors/runpod/gpus` · `GET /v1/executors/modal/gpus`
Both return `{data: [{id, name, memory_gb, cents_per_hour, recommended?}]}`.
RunPod's takes `{api_key}`, lists the Secure Cloud GPUs whose NVENC the
worker can use, from RunPod's catalog, and doesn't keep the key
(`400 key_rejected`). Modal's lists its NVENC GPUs at Modal's published
prices for a default sandbox, with the ones chosen by default marked
`default`.
### Disconnect a provider [#disconnect-a-provider]
`DELETE /v1/executors/{kind}`
`204`. Routing that named the provider moves back to `builtin` as primary,
or to no fallback. `404` when it isn't connected; `409 machines_running`
while one of its machines may still run.
## Apps and keys [#apps-and-keys]
### Apps [#apps]
`GET /v1/apps` · `POST /v1/apps`
`GET` returns `{data: [{id, name, builtin, disabled, created_at}]}`. `POST`
takes `{name}` (1 to 100 characters) and returns `201` the app.
`409 name_taken` when another app has the name.
### Disable or enable an app [#disable-or-enable-an-app]
`POST /v1/apps/{id}/disable` · `POST /v1/apps/{id}/enable`
Returns the app. A disabled app's API keys, upload tokens and playback stop.
`409 builtin_app`: the Dashboard app can't be disabled.
### API keys [#api-keys]
`GET /v1/apps/{id}/api-keys` · `POST /v1/apps/{id}/api-keys` · `DELETE /v1/api-keys/{id}`
- `GET`: `{data: [{id, name, scopes, created_at, last_used_at?, revoked_at?}]}`.
- `POST`: body `{name?, scopes?, local?}`. Returns
`201 {id, name, scopes, created_at, key}`; `key`, the secret, is in this
response only. `name` is at most 100 characters, `default` when blank.
`scopes` default to `uploads:write`, `assets:read` and `assets:write`;
`analytics:read` is given only when asked for.
- `DELETE`: `204`, and the key stops working.
Errors on create:
- `400 invalid_request`: an unknown scope, or a name over 100 characters.
- `409 public_url_required`: the public URL is loopback. Send `local: true`
to confirm the key is for apps on the same machine.
- `409 builtin_app`: the Dashboard app takes no keys.
### Credentials in one step [#credentials-in-one-step]
`POST /v1/apps/{id}/credentials`
Body `{webhook_url?, local?}`. Returns `201` the app's credentials, made
together and shown once:
`{url, app_id, app_name, api_key_id, api_key, signing_kid, signing_key, webhook_endpoint_id?, webhook_secret?, env}`.
That is a new API key, a new signing key (`signing_key` is its PKCS #8 PEM),
and with `webhook_url` a new webhook endpoint and its secret. `env` is the
same values as a `.env` block.
- `400 invalid_request`: the webhook URL is refused, and nothing is created.
- `409 public_url_required`: as for API keys.
- `409 builtin_app`: the Dashboard app.
### Signing keys [#signing-keys]
`GET /v1/apps/{id}/signing-keys` · `POST /v1/apps/{id}/signing-keys` · `DELETE /v1/signing-keys/{id}`
- `GET`: `{data: [{kid, created_at, retired_at?, revoked_at?}]}`.
- `POST`: `201 {kid, private_key_pem}`. The private key is in this response
only.
- `DELETE`: `204`. Tokens signed with the key stop playing.
## App pairings [#app-pairings]
These are the owner's side of `npx @clipmux/node init`, which the
`/connect` page shows. The routes the CLI calls are in the
[App pairing API](/docs/reference/api/app-pairing).
### Read a pairing [#read-a-pairing]
`GET /v1/app-pairings/{code}`
Returns `{status, name, hostname, client, ip?, app_id?, expires_at}`.
`status` is `pending`, `approved`, `denied`, `consumed` or `expired`.
`404 pairing_not_found`.
### Approve or deny a pairing [#approve-or-deny-a-pairing]
`POST /v1/app-pairings/{code}/approve` · `POST /v1/app-pairings/{code}/deny`
Approve takes `{app_id | new_app_name, webhook_url?, local?}` and returns the
pairing, `approved`. Its credentials wait, sealed, for the CLI's next poll.
- `400 invalid_request`: send exactly one of `app_id` and `new_app_name`.
- `404 not_found`: an unknown app.
- `409 name_taken`, `409 public_url_required`, `409 builtin_app`: as above.
Deny returns the pairing, `denied`, and the CLI stops. A pairing already
decided or expired is returned as it is.
## Webhook endpoints and deliveries [#webhook-endpoints-and-deliveries]
### Endpoints [#endpoints]
`GET /v1/apps/{id}/webhook-endpoints` · `POST /v1/apps/{id}/webhook-endpoints` · `DELETE /v1/webhook-endpoints/{id}`
- `GET`:
`{data: [{id, url, created_at, disabled_at?, consecutive_failures, skipped_until?, pending_secret_since?}]}`.
After 5 failed tries in a row an endpoint is skipped for a minute,
doubling up to an hour, without spending its deliveries' tries.
- `POST`: body `{url}`. Returns `201 {id, url, created_at, secret}`; the
`whsec_…` secret is in this response only. `400 invalid_request` for a
refused URL.
- `DELETE`: `204`, and the endpoint gets no more deliveries.
### Rotate an endpoint's secret [#rotate-an-endpoints-secret]
`POST /v1/webhook-endpoints/{id}/secret` · `POST /v1/webhook-endpoints/{id}/secret/activate`
- The first returns `201 {secret, active: false}`: a new secret, shown once.
Deliveries stay signed with the old one until you activate it.
- `activate` returns `{active: true}`: deliveries are signed with the new
secret from the next try. `409 no_pending_secret` without a new secret.
See [Retries, redelivery and secret rotation](/docs/build/webhooks/retries).
### Deliveries [#deliveries]
`GET /v1/webhook-endpoints/{id}/deliveries`
The latest 100:
`{data: [{id, event_id, event_type, status, attempts, last_status?, last_error?, created_at, finished_at?, next_attempt_at?}]}`.
### Redeliver [#redeliver]
`POST /v1/webhook-deliveries/{id}/redeliver`
Returns `202 {id, endpoint_id, status: "pending"}`: a delivery that gave up
(`failed`) is tried again for a fresh 24 hours. `409 not_redeliverable`
otherwise.
## Library and jobs [#library-and-jobs]
### Library [#library]
`GET /v1/library` · `GET /v1/library/counts`
`GET /v1/library` takes `app_id`, `status`, `q`, `include_deleted`, `cursor`
and `limit` (1 to 100, default 50). It lists every app's videos, newest
first: `{data: [asset + poster_url], next_cursor?}`.
- Deleted videos appear only with `include_deleted=true` or `status=deleted`.
- `q` (at most 255 bytes) is an exact asset ID, or text a title or
passthrough contains, ignoring case.
- `poster_url` is a ready-to-use poster URL, signed for one hour when the
playback ID is signed, or `null` until a playback ID is playable.
- `400 invalid_cursor`, `400 invalid_request`.
`GET /v1/library/counts` takes `app_id` and returns
`{ready, processing, errored, waiting_upload}`.
### Preview a video [#preview-a-video]
`POST /v1/assets/{id}/preview-token`
Returns `{playback_id, token, url, expires_at}`: a one-hour `v` token signed
with the server's internal key, and the `master.m3u8` URL it plays. Plays
with it don't count in analytics. `409 no_playback_id` when the video has no
active playback ID.
### Setup test [#setup-test]
`POST /v1/setup-test` · `GET /v1/setup-test/latest`
A setup test sends a sample clip through the configured path as an app's
video would go: uploaded through the public URL, encoded by a worker, and
played through the media URL, checking that private playback and encryption
work.
- `POST` queues one, or returns the one already queued: `202` the test.
- `GET …/latest` returns the latest test, or `404` before the first.
A test is
`{id, status, trigger, executor?, asset_id?, checks: [{name, ok, detail?}], created_at, finished_at?}`,
with `status` `queued`, `running`, `passed` or `failed`.
### Jobs [#jobs]
`GET /v1/jobs` · `GET /v1/jobs/{id}`
`GET /v1/jobs` takes `status`, `asset_id`, `agent_id`, `cursor` and `limit`
(1 to 100, default 50), and lists jobs across the library, newest first:
`{data: [job], next_cursor?}`. `GET /v1/jobs/{id}` returns one job.
A job is
`{id, asset_id, app_id, passthrough?, kind, status, phase?, progress?, pinned_agent_id?, lost_count, failed_count, error_code?, routed_to?, route_reason?, created_at, started_at?, finished_at?, attempts}`.
- `routed_to` is where a media job is routed: `workers`, `agents`,
`builtin`, `modal` or `runpod`.
- `route_reason` is why: `pinned`, `primary`, `primary_offline`,
`queue_age`, `no_fallback`, `fallback_refused`, `fallback_offline`,
`fallback_limit`, `primary_limit` or `setup_test`.
- Each attempt is
`{id, number, executor, route_reason?, agent_id?, agent_name?, status, failure_kind?, error_code?, error_message?, phase?, progress?, encoder?, started_at, finished_at?, last_heartbeat_at?}`,
and keeps the reason it ran where it did. A failed attempt's
`error_message` is what its worker said went wrong, such as ffmpeg's first
error lines: at most 1000 characters, with any URL's query string removed.
## Cloudflare [#cloudflare]
Connecting Cloudflare sends your Cloudflare API token to Cloudflare's API
from your server. With Cloudflare delivery, viewers fetch encoded files
and content keys from your Worker, in your Cloudflare account, and the
encoded files are stored in your R2 bucket.
### Status [#status]
`GET /v1/cloudflare`
Returns
`{connected, hostname?, bucket?, account_id?, worker_version?, current_version, needs_redeploy, storage_ok, token_url, r2_token_url, analytics_token_url}`.
The `*_url` fields open Cloudflare's create-token form with the permissions
Connect, R2 storage and edge analytics need already chosen.
### Inspect a token [#inspect-a-token]
`POST /v1/cloudflare/inspect`
Body `{token, account_id?}`. Returns
`{accounts: [{id, name}], account_id?, zones?, buckets?, workers_paid, unreadable?}`:
what the token reaches. With several accounts and none named, only
`accounts` is filled. `unreadable` names what it couldn't list. Changes
nothing and keeps nothing. `400 token_rejected`.
### Connect and disconnect [#connect-and-disconnect]
`POST /v1/cloudflare/connect` · `DELETE /v1/cloudflare`
- `POST` takes `{token, hostname, bucket?, account_id?}` and returns
`{connected, steps: [{name, ok, detail?}]}`, stopping at the first failed
step. Each step is safe to repeat. The bucket is created if it's missing,
and new videos' encoded files go to it. The token is used for this
request only.
- `DELETE` moves delivery back to built-in and returns
`{disconnected, steps}`: `media_url`, `delivery`, `routes`, `forgotten`
and `setup_test`. The R2 bucket stays a storage config; the Worker and its
domain stay in your Cloudflare account. `404 not_connected`;
`409 pinned` while `CLIPMUX_MEDIA_URL` names the Worker.
See [Cloudflare edge delivery](/docs/self-host/delivery/cloudflare).
### Edge analytics [#edge-analytics]
`GET /v1/cloudflare/analytics` · `POST /v1/cloudflare/analytics` · `DELETE /v1/cloudflare/analytics`
- `GET`: `{connected, account_id?, pulled_through?, last_pull_at?, last_error?}`.
`pulled_through` is how far the server has pulled the Worker's counts.
- `POST`: body `{token}`, a second Cloudflare token with only
**Account Analytics: Read**. Returns the status. `409 not_connected`
without Cloudflare delivery; `400 token_rejected`.
- `DELETE`: `204`. The token is forgotten; counts already pulled stay.
`404 not_connected`.
See [Edge analytics](/docs/self-host/delivery/edge-analytics).
## Storage [#storage]
Credentials are never returned.
### List and add storage [#list-and-add-storage]
`GET /v1/storage` · `POST /v1/storage`
- `GET`:
`{data: [{id, kind, bucket?, endpoint?, public_endpoint?, region?, default, asset_count, source_bytes, media_bytes, total_bytes, cloudflare_delivery, created_at}]}`.
`kind` is `fs`, `r2` or `s3`. `asset_count` counts videos whose source or
encoded files are on it, deleted ones aside; `source_bytes`, `media_bytes`
and `total_bytes` sum the live sources, outputs and tracks currently stored
there. `cloudflare_delivery` marks the bucket the Worker reads.
- `POST`: body
`{endpoint, bucket, access_key_id, secret_access_key, region?, public_endpoint?}`.
Returns `201` the config, `kind: "s3"`, not the default. It's saved only
after a test write, read, list and delete pass and CORS for browser
uploads is set: otherwise `400 storage_check_failed` with the store's
reason. `public_endpoint` is where browsers send upload parts, when it
differs from `endpoint`.
### Add an R2 bucket [#add-an-r2-bucket]
`POST /v1/storage/r2`
Body `{token, bucket?, account_id?, default?}`. Returns `{connected, steps}`:
`token`, `account`, `bucket` (created if missing), `storage` (keys made from
the token and checked as above), and `default` when asked. Delivery doesn't
change. The token needs only **Workers R2 Storage: Edit**.
### Rotate a bucket's credentials [#rotate-a-buckets-credentials]
`PUT /v1/storage/{id}/credentials`
Body `{access_key_id, secret_access_key}`. Returns `204` once the new keys
pass the same checks; the old ones work until then. `400 storage_check_failed`;
`409 builtin_storage` for this server's disk.
### Choose the default [#choose-the-default]
`POST /v1/storage/{id}/default`
New uploads go to this storage, this server's disk included. Returns the
storage list. Existing videos stay where they are until moved.
### Remove storage [#remove-storage]
`DELETE /v1/storage/{id}`
`204`; the config is no longer listed and its credentials are dropped.
- `409 builtin_storage`: this server's disk can't be removed.
- `409 storage_default`: make another storage the default first.
- `409 cloudflare_delivery`: disconnect Cloudflare first.
- `409 storage_in_use`, with `asset_count` and `active_moves`: videos still
have files here; move the library first.
### Move the library [#move-the-library]
`GET /v1/storage/moves` · `POST /v1/storage/moves`
- `GET`:
`{default_storage_id, default_kind, media_storage_id, uploads_elsewhere, media_elsewhere, active, moved, failed}`.
`uploads_elsewhere` counts videos whose source isn't on the default
storage; `media_elsewhere` those whose encoded files aren't on
`media_storage_id`.
- `POST`: queues a move job for every video with files away from where they
belong and no active job. Returns `202 {queued}`.
See [Where videos are stored](/docs/self-host/storage).
## PC agents [#pc-agents]
### Agents [#agents]
`GET /v1/agents` · `PATCH /v1/agents/{id}` · `DELETE /v1/agents/{id}`
- `GET`:
`{data: [{id, name, status, scope, online, sandboxed, hostname, platform, last_ip?, last_seen_at, capabilities, created_at, revoked_at?}]}`.
- `PATCH`: body `{name?, scope?}`, `scope` being `all` or `local`. Returns the
agent. `400 invalid_name`, `400 invalid_scope`.
- `DELETE`: revokes the agent. Its key stops working and its running
attempts are stopped and queued again. Returns
`{agent, fenced_attempts, current_outputs}`. Revoking twice is harmless.
### Re-encode an agent's outputs [#re-encode-an-agents-outputs]
`POST /v1/agents/{id}/reencode`
Queues a re-encode of every ready video whose current output the agent
encoded, for after you revoke a PC you no longer trust. Returns
`202 {queued: [asset_id], skipped: {asset_id: error_code}}`; a video whose
source stays on that PC can't be re-encoded elsewhere and is skipped.
### Pair an agent [#pair-an-agent]
`POST /v1/agents/pairings` · `GET /v1/agents/pairings/{code}`
- `POST`: body `{name?}` (at most 100 characters). Returns
`201 {code, expires_at, server, command, docker_command, install_command}`:
a one-time code the owner has already approved, valid for 15 minutes,
and the commands that use it.
- `GET`:
`{status, agent_started, name, hostname, platform, ip?, agent_id?, expires_at}`.
`status` is `pending`, `approved`, `denied`, `consumed` (an agent holds
its key) or `expired`.
### Approve or deny an agent's code [#approve-or-deny-an-agents-code]
`POST /v1/agents/pairings/{code}/approve` · `POST /v1/agents/pairings/{code}/deny`
Decides a code that `clipmux worker --server URL` is showing on a PC.
Returns the pairing.
See [Encode on a PC you own](/docs/self-host/encoding/your-pc).
## Next [#next]
- [API reference](/docs/reference/api), the routes your app calls
- [A tour of the dashboard](/docs/self-host/dashboard)
- [Command line](/docs/reference/cli), for the host-side `clipmux admin` commands
---
# @clipmux/node
The server SDK, with its client, route handlers, token signing, webhook verification and CLI.
Source: https://clipmux.com/docs/reference/sdks/node
`@clipmux/node` is what your backend uses to talk to ClipMux: it creates
uploads, reads videos, signs playback tokens and verifies webhooks. It also
ships `clipmuxHandler`, the three routes the browser elements call, and a CLI
that connects your app to a server.
- Version 0.1.0, MIT licensed. The ClipMux server is AGPL-3.0; this package
is MIT so your app can embed it.
- ESM only. A CommonJS backend on Node 20.19 or later can `require()` it.
- No runtime dependencies other than `@clipmux/uploader`, which the CLI's
`upload` command uses. It uses Web APIs only, so it runs on Node 20.19 or
later, Bun, Deno, Cloudflare Workers and Vercel Edge.
- Its types are generated from the server's OpenAPI spec.
For how to use it, start with the [quickstart](/docs/build/quickstart).
## Install [#install]
```bash
npm i @clipmux/node
```
```bash
pnpm add @clipmux/node
```
## Entry points [#entry-points]
| Import | What it has |
| --- | --- |
| `@clipmux/node` | `ClipMux`, the errors, `signToken`, `importSigningKey`, `verifyWebhook`, `signWebhook`, and the API's types |
| `@clipmux/node/handlers` | `clipmuxHandler` |
| `@clipmux/node/express` | `toNodeListener`, for Express, Fastify and `node:http` |
The package also installs a `clipmux-node` binary, which `npx @clipmux/node`
runs.
## The client [#the-client]
```ts
import { ClipMux } from '@clipmux/node'
const clipmux = new ClipMux() // reads the CLIPMUX_* variables
```
### Options [#options]
`new ClipMux(options?)` reads each setting from its option, or else from the
environment. A missing setting throws a `ClipMuxConfigError` only when a call
needs it.
","description":"Where the defaults come from. Pass the binding on Cloudflare Workers.","default":"process.env"},"fetch":{"type":"typeof fetch","description":"The fetch to use.","default":"globalThis.fetch"},"maxRetries":{"type":"number","description":"Retries of a temporary failure.","default":"3"},"timeoutMs":{"type":"number","description":"Timeout per request, in milliseconds.","default":"30000"}}} />
Every `POST` carries an `Idempotency-Key`, and a retry reuses it. The client
retries 408, 429 (after `Retry-After`), 5xx and network errors.
### uploads [#uploads]
| Method | Does |
| --- | --- |
| `create(body, { idempotencyKey? })` | Creates an upload (`POST /v1/uploads`). Returns it with `upload_token` and `endpoint`, the object `@clipmux/uploader` takes as it is |
| `cancel(uploadId)` | Cancels an upload; the video becomes `errored` with `upload_cancelled` |
### assets [#assets]
| Method | Does |
| --- | --- |
| `get(assetId)` | One video |
| `findByPassthrough(passthrough)` | Your own reference's videos, newest first |
| `changes({ since, limit? })` | An async iterator of every video changed since a time, oldest first, deleted ones included: the catch-up for missed webhooks |
| `update(assetId, { title })` | Sets the title; `null` clears it |
| `delete(assetId)` | Deletes a video; playback stops at once |
| `reencode(assetId, body?)` | Queues a re-encode |
| `importUrl(body, { idempotencyKey? })` | Imports a public http(s) URL (`POST /v1/assets` with `url`) |
| `waitUntilReady(assetId, { timeoutMs?, signal? })` | Resolves once the video is ready, from the events long-poll; rejects with code `asset_errored` if it fails, or `timeout` after 30 minutes by default. For scripts and tests; an app should use the webhook |
### tracks [#tracks]
| Method | Does |
| --- | --- |
| `create(assetId, { kind, supersede? })` | Makes subtitles or chapters for a video |
| `get(assetId, trackId)` | One track, with its chapters once ready |
| `transcript(assetId, trackId, { words? })` | A ready subtitles track's transcript, with word timings when `words` is true |
| `delete(assetId, trackId)` | Deletes a track |
### playbackIds, shares, events, analytics, app [#playbackids-shares-events-analytics-app]
| Method | Does |
| --- | --- |
| `playbackIds.create(assetId, { policy })` | Adds a playback ID |
| `playbackIds.delete(assetId, playbackId)` | Revokes a playback ID |
| `shares.create(assetId, { name?, expires_at? })` | Creates a share link |
| `shares.list(assetId)` | A video's share links |
| `shares.delete(shareId)` | Revokes a share link |
| `shares.streamUrl(shareId)` | A signed `master.m3u8` URL for a share link |
| `events.poll({ since?, after?, wait?, signal? })` | Long-polls the app's events, what its webhooks receive |
| `analytics.get(range)` | The app's analytics for `24h`, `7d`, `30d` or `90d`; needs a key with `analytics:read` |
| `analytics.asset(assetId, range)` | The same for one video |
| `app.get({ fresh? })` | The key's app (`GET /v1/app`): scopes, URLs, the longest token, signing keys. Cached until `fresh: true` |
### playback [#playback]
These sign locally with your signing key and make no call per play.
| Method | Does |
| --- | --- |
| `token(playbackId, options?)` | Signs a playback token. Returns a promise of the JWT |
| `urls(target, token?)` | Playback URLs, `{ hls, poster, track(trackId) }`, for a video (its first active playback ID) or `{ baseUrl, playbackId, policy? }` |
| `session(target, { viewerId?, native?, expiresIn? })` | Everything `` needs, as the answer to its request: `{playback_id, base_url, token, expires_at, poster_url, title?, duration_seconds, tracks}`. Pass the video, not only its playback ID, to include its tracks and duration |
`token` options:
`session` gives `poster_url` its own poster-only token, so the poster URL is
safe in an `og:image`.
### webhooks [#webhooks]
| Method | Does |
| --- | --- |
| `verify(rawBody, headers, { tolerance? })` | Verifies a webhook against `CLIPMUX_WEBHOOK_SECRET` and returns its event. Pass the raw body as it arrived. `tolerance` is the seconds a timestamp may be off, 300 by default |
## Route handlers [#route-handlers]
`clipmuxHandler(options)` returns a Fetch handler, `(req: Request) => Promise`,
for three `POST` routes, chosen by the last part of the path:
| Route | Called by | Calls |
| --- | --- | --- |
| `…/upload` | `` | `upload(req, { file })` |
| `…/playback` | `` | `playback(req, { playbackId, native })` |
| `…/webhook` | ClipMux's webhook | `event(event)`, then `asset(asset, event)` |
```ts title="app/api/clipmux/[action]/route.ts"
import { clipmuxHandler } from '@clipmux/node/handlers'
export const POST = clipmuxHandler({
async upload(req, { file }) {
return { passthrough: 'lesson_42', title: file.name }
},
async playback(req, { playbackId }) {
return { viewerId: 'user_7' } // or null to refuse
},
async asset(asset) {
// store asset.status and asset.playback_ids by asset.passthrough
},
})
```
Every route is default-deny:
- A callback you don't pass is a `404`; the webhook route needs `asset` or
`event`.
- A callback that returns `null` is `403 denied`.
- The browser routes accept only `Content-Type: application/json`
(`415 unsupported_media_type`), and any method but `POST` is `405`.
- A webhook that fails verification is `400`, with the reason as its code:
`missing_header`, `stale`, `bad_signature` or `invalid_body`.
When ClipMux refuses a request, the browser gets what it can act on:
- 400, 409, 413 and 422 pass through with ClipMux's `code`, and the
elements don't retry them.
- 429 passes through with `Retry-After`.
- A wrong key or app is `500 clipmux_misconfigured`, logged on your server.
- ClipMux unreachable or failing is `502 clipmux_unavailable`, which the
elements retry.
### toNodeListener [#tonodelistener]
`toNodeListener(handler)` runs a Fetch handler on Node's request and
response, for Express, Fastify (through its raw request) or `node:http`.
Mount the route before `express.json()`, or give it
`express.raw({ type: '*/*' })`: the webhook needs the body as it arrived.
```ts
import { clipmuxHandler } from '@clipmux/node/handlers'
import { toNodeListener } from '@clipmux/node/express'
app.post('/api/clipmux/:action', toNodeListener(clipmuxHandler({ /* … */ })))
```
## Functions [#functions]
| Export | Does |
| --- | --- |
| `importSigningKey(pem)` | Imports a P-256 PKCS #8 PEM as a `CryptoKey` for signing |
| `signToken(key, kid, claims)` | Signs an ES256 playback token from `{sub, aud: 'v' \| 't', iat, exp, vid?}` |
| `verifyWebhook(secret, rawBody, headers, { tolerance?, now? })` | Verifies a webhook and returns its event, without a client |
| `signWebhook(secret, timestamp, body)` | The `X-Webhook-Signature` value ClipMux sends for a body, for tests |
| `VERSION` | The package version |
## Errors [#errors]
| Class | When | Fields |
| --- | --- | --- |
| `ClipMuxError` | The API answered with an error, or couldn't be reached (`status` 0) | `status`, `code`, `details`, `request` |
| `ClipMuxConfigError` | A setting the call needs is missing or malformed | `variable` |
| `WebhookVerificationError` | A webhook that must not be trusted; answer it with `400` | `reason`: `missing_header`, `stale`, `bad_signature` or `invalid_body` |
A `ClipMuxError`'s message says what to do next. The codes are in
[Errors](/docs/reference/errors).
## Types [#types]
The package exports the API's types, generated from the spec (`Asset`,
`Upload`, `Track`, `PlaybackID`, `CreateUpload` and the rest), and these of
its own: `ClipMuxOptions`, `CreatedUpload`, `PlaybackSession`,
`SessionOptions`, `TokenOptions`, `TokenClaims`, `Audience`,
`WebhookEvent` (an `AssetEvent` or a `TrackEvent`, narrowed by `type`),
`HeadersLike`, `RawBody`, `VerifyOptions` and `WebhookFailure`.
## CLI [#cli]
```bash
npx @clipmux/node init --server https://video.example.com
npx @clipmux/node doctor
npx @clipmux/node listen --forward-to localhost:3000/api/clipmux/webhook
npx @clipmux/node upload lesson-42.mp4 --passthrough lesson_42 --wait
```
| Command | Does |
| --- | --- |
| `init` | Connects this app to a server: the owner approves it in the dashboard, and the credentials go to an env file, never printed |
| `doctor` | Checks the server, the API key, the signing key and the webhook secret, and prints the Content-Security-Policy sources your pages need |
| `listen` | Forwards this app's webhook events to a local URL, signed with `CLIPMUX_WEBHOOK_SECRET` |
| `upload` | Uploads a file |
Every flag is in [Command line](/docs/reference/cli).
## Next [#next]
- [Quickstart](/docs/build/quickstart)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Verify webhook signatures](/docs/build/webhooks/verify-signatures)
---
# @clipmux/player
The player element, its attributes, properties and events, and the token-refresh helpers for other players.
Source: https://clipmux.com/docs/reference/sdks/player
`@clipmux/player` plays ClipMux videos with Video.js 10 and hls.js, and
renews an expired playback token without losing the viewer's place. It
registers ``, and exports the token-refresh parts without
the UI for another player.
- Version 0.6.0, MIT licensed. The ClipMux server is AGPL-3.0; this package
is MIT so your app can embed it.
- It depends on `@videojs/html` 10.2, `@videojs/hlsjs-video` 10.2 and
hls.js 1.6.
- Video.js 10.2's declaration files don't all type-check, so keep
`"skipLibCheck": true` in a TypeScript project that imports the element.
For how to use it, see [Add the player](/docs/build/play/player).
## Install [#install]
```bash
npm i @clipmux/player
```
```bash
pnpm add @clipmux/player
```
## Entry points [#entry-points]
| Import | What it has |
| --- | --- |
| `@clipmux/player/element` | Registers `` and exports `ClipMuxPlayerElement` and its event types |
| `@clipmux/player` | The parts without the UI: token refresh, sessions, sources and tracks |
| `@clipmux/player/react` | Types only: adds `` to React's JSX, with no React dependency |
## The element [#the-element]
```html
```
The element gets its token one of two ways:
- **`session-url`.** The element sends `POST` with
`{"playback_id": "pid_…", "native": false}` to your backend for the first
load and for every renewal. Your backend
answers with a playback session, the shape `clipmuxHandler`'s `playback`
route and `clipmux.playback.session` return. A `401` or `403` from it fires
`clipmux-denied`.
- **`getToken`.** Set `base-url` and `playback-id`, and a `getToken`
function that returns a token, or `null` to deny.
A public playback ID needs neither: set `base-url` and `playback-id`.
### Attributes [#attributes]
| Attribute | Value |
| --- | --- |
| `playback-id` | The playback ID, `pid_…` |
| `session-url` | Your backend's route that answers with a playback session |
| `base-url` | The media origin, for example `https://media.example.com`. Not needed with `session-url`, which supplies it |
| `poster` | A poster URL; with `session-url` the session's `poster_url` is used when it's unset |
| `chapters-track` | A chapters track ID, `trk_…`, to mark on the time slider; with `session-url` the first ready chapters track is used when it's unset |
| `autoplay`, `muted` | Passed to the media element |
### Properties [#properties]
| Property | Type | Value |
| --- | --- | --- |
| `token` | `string` | The playback token in use. Set it to start with one |
| `getToken` | `GetToken` | Called for a token, `({ playbackId, native }) => Promise`; `null` stops playback. Set as well as `session-url`, it is used for renewals |
| `hls` | `Record` | Extra hls.js options; set before the first load. Write-only |
| `session` | `PlaybackSession \| null` | The `session-url` answer in use. Read-only |
| `chapters` | `PlayerChapter[]` | The chapters of the chapters track, in seconds, once loaded. Read-only |
| `media` | element | The inner `` element, for its own properties and events. Read-only |
`native` is `true` when the browser plays HLS itself, without MediaSource
(iOS before 17.1, AirPlay). Such a player can't renew a token, so your
backend signs one that lasts the whole session. iOS 17.1 and later play
through hls.js and renew.
### Events [#events]
They bubble and are typed on `HTMLElementEventMap`, so
`player.addEventListener('clipmux-chapters', (e) => e.detail.chapters)`
needs no cast.
| Event | `detail` | When |
| --- | --- | --- |
| `clipmux-token` | `{ token }` | A new token is in use |
| `clipmux-denied` | `{}` | Your app said no (`null`, or `401` or `403` from `session-url`), or delivery answered `403`. Playback stops |
| `clipmux-error` | `{ status, track? }` | A request failed: its HTTP status, or `0` for a network or media error. `track` is set when a track's VTT failed to load. A `404` means the playback ID was revoked or never existed |
| `clipmux-chapters` | `{ chapters }` | The chapters loaded, in seconds |
### React [#react]
```tsx
import type {} from '@clipmux/player/react'
setDenied(true)} />
```
The import types the attributes, the `token`, `getToken` and `hls`
properties and the `onclipmux-*` handlers, for React 18 or 19. React 19
attaches the handlers only to an element it creates in the browser; for a
server-rendered one, or on React 18, listen on a ref.
## How renewal works [#how-renewal-works]
A signed playback URL carries its token in the path,
`{base_url}/v/{token}/{playback_id}/…`, and every playlist, segment and key
below it is relative. When the token expires, delivery answers
`401 token_expired`. The player asks for a new token once, however many
requests failed together, puts it into that request and every later one, and
retries. hls.js never sees the error. A failed request for a token is tried
again after 1, 2 and 4 seconds.
## Exports for other players [#exports-for-other-players]
From `@clipmux/player`:
| Export | Does |
| --- | --- |
| `rewriteTokenUrl(url, mediaOrigin, playbackId, token)` | Puts a token into a signed playback URL of that playback ID on that origin. Any other URL is returned unchanged |
| `TokenSession` | The current token of one playback: `new TokenSession(token, getToken?, { onToken?, onDenied? })`, with `current`, `denied`, `refresh(seen)` and `deny()`. `refresh` calls `getToken` at most once for many failed requests |
| `createRefreshLoader(Loader, session, mediaOrigin, playbackId)` | Wraps an hls.js loader class (`Hls.DefaultConfig.loader`) so every request carries the session's token and a `401` is answered with a new token and a retry |
| `fetchSession(url, playbackId, native)` | Asks a session URL for a playback session. Resolves `null` on `401` or `403`; rejects with a `SessionError` (with `status`) otherwise |
| `chaptersTrackOf(session)` | The session's first ready chapters track ID, or `''` |
| `playbackUrl({ baseUrl, playbackId, token? })` | The `master.m3u8` URL, signed or public |
| `clipmuxSource(options, session?)` | The source object for Video.js's ``, with the refresh loader when given a session |
| `playsNatively()` | Whether the browser will play HLS itself, where tokens can't be renewed |
| `trackUrl(baseUrl, playbackId, trackId, token?)` | A track's VTT URL, signed or public |
| `fetchTrack(url, session, token)` | Loads a track's VTT, renewing the token through the session on a `401`. `url` is a function from token to URL |
| `parseChapters(vtt)` | Reads a chapters VTT into `{ startTime, endTime, title }[]`, in seconds |
| `SessionError` | The error `fetchSession` rejects with |
Types: `GetToken`, `TokenRequest`, `SessionOptions`, `LoaderClass`,
`PlaybackSession`, `SessionTrack`, `ClipMuxSource`, `SourceOptions`,
`PlayerChapter` and `Chapter` (the same, in seconds; the API's chapters are
in milliseconds).
## Content-Security-Policy [#content-security-policy]
A page with the player must allow, besides its own origin:
- `connect-src`: the media origin.
- `media-src`: `blob:` and the media origin.
- `img-src`: the media origin, for the poster.
- `style-src`: `'unsafe-inline'`, for the styles Video.js injects.
`npx @clipmux/node doctor` prints the exact origins. hls.js runs on the main
thread, so no `worker-src` is needed.
## Next [#next]
- [Add the player](/docs/build/play/player)
- [Sign playback tokens](/docs/build/play/sign-tokens)
- [Other players and native apps](/docs/build/play/other-players)
---
# @clipmux/uploader
The upload element, its attributes, events and styling, and the headless ClipMuxUpload class.
Source: https://clipmux.com/docs/reference/sdks/uploader
`@clipmux/uploader` uploads a file from the browser to ClipMux in parts,
straight to storage, and resumes from what storage already holds. It
registers ``, a drop zone with progress, Cancel and Retry,
and exports `ClipMuxUpload`, the same without the UI. The browser never holds
an API key: your backend creates the upload and hands it over.
- Version 0.5.0, MIT licensed. The ClipMux server is AGPL-3.0; this package
is MIT so your app can embed it.
- No dependencies.
For how to use it, see [Upload from the browser](/docs/build/upload/browser)
and [Headless uploads and Uppy](/docs/build/upload/headless-and-uppy).
## Install [#install]
```bash
npm i @clipmux/uploader
```
```bash
pnpm add @clipmux/uploader
```
## Entry points [#entry-points]
| Import | What it has |
| --- | --- |
| `@clipmux/uploader/element` | Registers `` and exports `ClipMuxUploaderElement` and its event types |
| `@clipmux/uploader` | `ClipMuxUpload`, `ClipMuxUploadError`, `rememberUpload`, `planParts` and their types |
| `@clipmux/uploader/react` | Types only: adds `` to React's JSX, with no React dependency |
## The element [#the-element]
```html
```
When the viewer chooses or drops a file, the element sends `POST` with
`{"size", "name", "type"}` to `create-url`, sending the page's cookies when
that URL is on the same origin. Your backend checks the user, creates the
upload with its API key, and answers with it plus `endpoint`, the ClipMux
URL. `clipmuxHandler`'s `upload` route does exactly that. The upload is
remembered in `localStorage` until it completes, so choosing the same file
after a reload resumes it.
### Attributes [#attributes]
| Attribute | Value |
| --- | --- |
| `create-url` | Your backend's route that creates the upload |
| `accept` | As on ` `, for example `video/*,.mkv`; dropped files are checked too |
| `max-size` | The largest file accepted, in bytes |
| `state` | Set by the element: `idle`, `uploading`, `done` or `error`, for styling |
### Properties and methods [#properties-and-methods]
| Member | Does |
| --- | --- |
| `options` | Further `ClipMuxUpload` options for each upload, such as `concurrency`, `endpoint` or `store` |
| `state` | The state, as the attribute. Read-only |
| `file` | The file being uploaded, or `null`. Read-only |
| `asset` | The video once the upload completes, or `null`. Read-only |
| `upload(file)` | Uploads a file, as choosing or dropping it does. Resolves with the video, or `null` |
| `retry()` | Tries the last failed upload again, from what storage holds |
| `cancel()` | Stops the upload for good and tells ClipMux |
### Events [#events]
They bubble and are typed on `HTMLElementEventMap`.
| Event | `detail` |
| --- | --- |
| `clipmux-progress` | `{ bytesUploaded, bytesTotal, partsDone, partsTotal }` |
| `clipmux-uploaded` | `{ asset }`: the video, `processing`. Your webhook hears when it's ready |
| `clipmux-error` | `{ code, message, status, error }` |
`code` is `file_too_large`, `file_type_rejected`, `create_denied` (a `401` or
`403` from `create-url`), or a `ClipMuxUploadError` code.
### Styling [#styling]
- Parts: `dropzone`, `label`, `button`, `progress`, `bar`, `status`,
`cancel` and `retry`, as in `clipmux-uploader::part(bar) { … }`.
- Custom properties: `--clipmux-uploader-accent`, `--clipmux-uploader-border`,
`--clipmux-uploader-radius`, `--clipmux-uploader-background`,
`--clipmux-uploader-color` and `--clipmux-uploader-font`.
- The default slot replaces the drop zone's text.
### React [#react]
```tsx
import type {} from '@clipmux/uploader/react'
save(e.detail.asset.id)} />
```
The import types the attributes, `options` and the `onclipmux-*` handlers,
for React 18 or 19. React 19 attaches the handlers only to an element it
creates in the browser; for a server-rendered one, or on React 18, listen on
a ref.
## ClipMuxUpload [#clipmuxupload]
The upload without the element.
```ts
import { ClipMuxUpload } from '@clipmux/uploader'
const asset = await new ClipMuxUpload(file, { createUrl: '/api/clipmux/upload' }).start()
```
`new ClipMuxUpload(file, options)` needs `upload`, `createUrl` or `create`.
| Member | Does |
| --- | --- |
| `start()` | Uploads what storage doesn't hold yet and completes the upload. Resolves with the video, `processing`. After a rejection, calling it again retries from what storage holds |
| `pause()` | Stops sending; parts already stored stay |
| `resume()` | Continues after `pause()` |
| `cancel()` | Stops for good and tells ClipMux to cancel the upload. Resolves with the video, `errored` with `upload_cancelled`, or `null` when there was none. An upload still being created is cancelled once it exists |
| `upload` | The upload in use, or `null` until `start()` has one |
How it behaves:
- Parts are the upload's `part_size`, which the server chooses.
- After a reload, `start()` asks ClipMux which parts are stored and sends
the rest.
- Retries honour `Retry-After`, and an offline browser waits for `online`.
Part uploads retry network errors, 5xx, 408 and 429; the calls to ClipMux
and to `createUrl` retry network errors, 5xx and 429. A 4xx such as
`413 too_large` fails at once.
- A failure rejects with a `ClipMuxUploadError` and leaves the upload
resumable for 24 hours.
- With `createUrl` or `create`, a remembered upload that ClipMux has ended
(expired, cancelled, its video deleted) is replaced by a new one.
- Storage must expose the `ETag` header to the page. ClipMux's own storage
does, and adding a bucket in the dashboard sets its CORS.
## Other exports [#other-exports]
| Export | Does |
| --- | --- |
| `ClipMuxUploadError` | The error a failed upload rejects with: `code`, `status` (`0` without an answer) and `retryable` |
| `rememberUpload(store)` | Remembers an upload per file in a store such as `localStorage`: `{ save(file, upload), load(file), forget(file), list() }`. It keeps only the upload's ID, token, part layout and endpoint. `list()` returns `{ name, size, lastModified, upload }` for each, when the store has `length` and `key()` |
| `planParts(size, partSize)` | Splits a size into parts, `{ number, start, end }[]` |
Types: `CreatedUpload`, `Asset`, `Progress`, `UploadOptions`, `UploadStore`,
`RememberedUpload`, `FileLike`, `PlannedPart` and `PutPart`.
With your own backend route and `rememberUpload`:
```ts
import { ClipMuxUpload, rememberUpload } from '@clipmux/uploader'
const memory = rememberUpload(localStorage)
const upload = memory.load(file) ?? (await createUploadOnMyBackend(file.size))
memory.save(file, upload)
const asset = await new ClipMuxUpload(file, {
endpoint: 'https://video.example.com',
upload,
onProgress: (p) => console.log(p.bytesUploaded / p.bytesTotal),
}).start()
memory.forget(file)
```
## Content-Security-Policy [#content-security-policy]
A page with the uploader must allow, besides its own origin:
- `connect-src`: the ClipMux URL, which signs and completes parts, and the
storage bucket's origin, which receives them. With files on the server's
own disk, that is the ClipMux URL too.
- `style-src`: `'unsafe-inline'`, for the element's styles.
`npx @clipmux/node doctor` prints the exact origins, from `GET /v1/app`
(`public_url` and `upload_origins`).
## Next [#next]
- [Upload from the browser](/docs/build/upload/browser)
- [Headless uploads and Uppy](/docs/build/upload/headless-and-uppy)
- [Choose renditions](/docs/build/upload/renditions)
---
# Changelog
What changed in each release of the server and the npm packages.
Source: https://clipmux.com/docs/reference/changelog
What changed in each release, in [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
form. The server is versioned by its `v*` tag; each npm package by its own
`package.json` version. The npm 0.1.x releases of `@clipmux/player` and
`@clipmux/uploader` came from the archived predecessor and share nothing with
these.
## Unreleased [#unreleased]
### Fixed [#fixed]
- RunPod: ClipMux now uses RunPod's REST API v2. RunPod retired v1 on
2026-11-15, so in rc.1 Connect RunPod failed with `lookup rest.runpod.io
… no such host`, and no pod could start. RunPod now places a pod on one
GPU type at a time, so the chosen GPUs are tried in order until one has
capacity; with none free, the wake waits and tries again.
- The README's quick start installs from `clipmux.com/install.sh`.
`releases/latest/download/install.sh` is a 404 while every release is a
prerelease.
- Dashboard: the jobs page no longer calls a running delete, move or
chapters job "Not claimed yet". The server runs those itself, and a
delete or move waits until the video's upload links expire, up to 16
minutes after its last job. An encode cancelled before it ran no longer
reads "Done by the server".
## v1.0.0-rc.1 - 2026-11-19 [#v100-rc1---2026-11-19]
The first release of the server: the image, the agent tarballs, the
`clipmux` binaries and the one-line installers, on a GitHub Release.
### Install and upgrade [#install-and-upgrade]
- `curl -fsSL https://clipmux.com/install.sh | sudo sh` installs ClipMux,
Postgres and Caddy in `/opt/clipmux` from
`ghcr.io/visheshgubrani/clipmux:v1.0.0-rc.1` (amd64 and arm64). Run it
again to upgrade; `--uninstall` keeps the volumes unless `--purge`.
- The installer prints the address the internet sees the server at (from
clipmux.com's CDN), then the server's own address, instead of the first
local address, which behind NAT or on a cloud VM is private.
- The dashboard's Docker command for a PC agent names the server's own
image tag (`:v1.0.0-rc.1`), so the agent speaks its worker API.
### @clipmux/node 0.1.0 [#clipmuxnode-010]
The first release: the client, the drop-in handlers, webhook verification
and the `init`, `doctor`, `listen` and `upload` CLI.
Fixed before release:
- `listen` and `assets.waitUntilReady` sent an event ID as `after`, which
the server refuses (it takes a time), so both failed on the first event;
and past 100 events they read the same page forever. They now move their
window as the server's `clipmux listen` does. `listen` takes `--since`.
- `uploads.create` returns `upload_token` as required, so its answer goes
into `new ClipMuxUpload(file, { upload })` as it is. An idempotent replay
of a finished upload throws `upload_not_active`.
- The handlers no longer turn every ClipMux 4xx into 502: 400, 409, 413 and
422 keep their status and code, 429 keeps `Retry-After`, a wrong key or
app is 500 `clipmux_misconfigured`, and ClipMux unreachable is 502
`clipmux_unavailable`.
- `playback.token()` takes `native` and `durationSeconds`, and reads the
server's maximum lifetime from `/v1/app` (waiting at most 3 s).
- `playback.session()` signs `poster_url` with a poster-only token.
- `WebhookEvent` is a union discriminated on `type`; a track event has its
`track`.
- `doctor` prints the Content-Security-Policy sources a page needs.
- Node ≥ 20.19 (ESM only).
### @clipmux/player 0.6.0 [#clipmuxplayer-060]
- `getToken` receives `{ playbackId, native }`, so a token route can sign a
session-length token for native HLS. A callback with no arguments still
works.
- `PlaybackSession` accepts what `@clipmux/node`'s `playback.session()`
answers (`expires_at` may be null; `title` and `duration_seconds`).
- The chapter type is `PlayerChapter` (seconds); `Chapter` is a deprecated
alias.
- Content-Security-Policy guidance in the README.
- Installs next to `@types/react` 18 (the optional peer was `>=19`, which
npm refused).
### @clipmux/uploader 0.6.0 [#clipmuxuploader-060]
- `create`, a function that creates the upload with your own client, joins
`upload` and `createUrl`. Its upload is remembered like a `createUrl` one,
and a remembered upload ClipMux has ended is replaced by a new one.
- `cancel()` resolves with the video ClipMux answered with (`errored`,
`upload_cancelled`), or `null`. A cancel while the upload is still being
created cancels it once it exists, instead of leaving it waiting.
- `rememberUpload(store).list()` returns the remembered uploads with their
file's name, size and time, so a page can ask for them after a reload.
`forget()` takes a `{ name, size, lastModified }` as well as a file.
### @clipmux/uploader 0.5.0 [#clipmuxuploader-050]
- A given `upload` without `upload_token` is refused at once instead of
sending `Bearer undefined`.
- Installs next to `@types/react` 18.
- Content-Security-Policy guidance in the README.
### Server [#server]
- `GET /v1/app` lists `upload_origins`, for an app's Content-Security-Policy.
- The OpenAPI spec at `/openapi.json` describes every operation and webhook,
groups its tags, and has an example for every JSON body.
- `clipmux worker --pair` names `clipmux admin create-pairing` as where its
code comes from, not the removed Workers page.
- `clipmux admin create-key` defaults to the scopes `doctor` checks
(`uploads:write`, `assets:read`, `assets:write`) and accepts spaces in
`--scopes`.
- `clipmux listen` reads `CLIPMUX_URL` when `CLIPMUX_SERVER` is unset.
- The share page's `poster_url` carries a poster-only token.
- The ladder goes up to the source: 2160p and 1440p join 1080p and below. Uploads, imports and re-encodes take `renditions` (e.g.
`["1080p", "480p"]`); the dashboard's upload and re-encode dialogs,
`clipmux push --renditions` and `npx @clipmux/node upload --renditions`
offer it. The worker contract is version 2: update PC agents.
- Speech runs on the GPU it names: the amd64 image carries whisper.cpp's
CUDA backend for NVIDIA serverless machines, the speech probe fails a GPU
backend whisper didn't use, and Vulkan whisper works under Landlock (it ran
on the CPU before). `--speech cuda` is a mode.
- Faster encodes: a hybrid GPU stage scales every rung on the GPU,
audio encodes beside the video, uploads run 8 at a time, and each commit
logs its phase timings, the GPU's name and why any GPU stage fell back.
### Server fixes [#server-fixes]
- An upload larger than about 29 GiB can complete. The complete request
was capped at 64 KiB, about 936 parts, and the refusal said "body must be
a JSON object". It now takes every part of the largest upload. Any
request body over its route's limit answers `413 too_large` with the
limit, instead of `400 invalid_request`.
- A failed video says why. The worker's message, such as ffmpeg's first
error lines, is kept on each failed attempt (with URL query strings
removed) and shown on the video page and the Jobs page; the management
API's attempts carry it as `error_message`. Re-encode is offered on a
failed video when there is a source to encode, and the page no longer
suggests it for a file ClipMux can't read or an upload that never
finished.
- Sources that failed to encode now do:
- OBS and other MPEG-TS recordings whose keyframes are far apart: the
poster step seeked to where nothing decodes and threw the finished
encode away;
- a video of a single frame;
- a clip under 3 s whose audio is digital silence (loudness
normalisation measured it as NaN; clips that short are no longer
normalised);
- a declared audio track with no packets (a recorder with a dead mic),
which now gives a video-only output;
- WebM recorded in the browser with MediaRecorder, whose header has no
duration (it's read from the packets);
- very tall or very wide frames (400×5000, 8192×700), which no rung fit:
the one rendition is scaled until its long side fits 4096.
- A source whose frame size changes partway through (a stitched capture)
kept only the part before the change, and still showed as ready. Every
rendition now runs the whole length.
- An audio file with cover art is refused as having no video, instead of
becoming a video a frame long.
- Concurrent upload completes or cancels no longer freeze the server: each
held a database connection while waiting for a second, so a burst as large
as the pool deadlocked it until a restart.
- A rotated phone video (portrait, or upside down) no longer comes out
sideways or upside down on a full-GPU encode: a rotated source takes the
hybrid stage, whose CPU decode applies the rotation.
- The dashboard can upload a file again after its earlier upload ended on
the server (its video deleted, the upload expired or cancelled elsewhere).
It kept the dead upload and failed with "the upload is no longer active"
every time.
- The dashboard asks before a page with uploads running is left. After a
reload it lists the stopped uploads with how much is stored; adding the
file again resumes it, and Discard ends it.
- Cancelling an upload in the dashboard deletes its empty video instead of
leaving it as Failed. A video whose upload was cancelled elsewhere shows as
Cancelled.
- Deleting an asset, or one of its tracks, no longer fails with 500 when a
track is `errored` (chapters with no LLM connected, say): a deleted track
drops its `error_code` (found by the first live integration, Edural).
### Server security (the security review, findings 1–6) [#server-security-the-security-review-findings-16]
- The built-in worker refuses to run without Landlock, and serve and the
workers are undumpable, so a hostile file can't read serve's secrets. Set `CLIPMUX_UNSANDBOXED_WORKER` to run it anyway.
- Seccomp denies new namespaces to the media tools.
- A device the owner signed in from skips the global sign-in limit, so
strangers can't lock the owner out.
- An upload part URL binds the part's length.
- The Dashboard app takes no API keys, and its existing keys are revoked;
an unsandboxed agent takes no URL imports (migration 00035).
- Delivery serves only the files a committed output's manifest lists, and
sweeps the rest (migration 00036).
---
# Resources
Guides for moving from Mux or Cloudflare Stream, how ClipMux is built, common questions, and how to take part.
Source: https://clipmux.com/docs/resources
Guides for moving an app to ClipMux from another service, a short tour of
how ClipMux is built, answers to common questions, and how to contribute or
report a security problem.
## Migrate [#migrate]
Map Mux's assets, tokens and webhooks to ClipMux, and move an app across.
Map Stream's signed URLs, uploads and webhooks to ClipMux, and move an app across.
## The project [#the-project]
The core model, the adapters and the rules that never bend.
DRM, scaling, cost, the licence, Docker and live streaming.
Set up the repository and send a pull request.
Report a vulnerability privately.
## Next [#next]
- [Quickstart](/docs/build/quickstart)
- [Install with one line](/docs/self-host/install)
---
# Migrate from Mux
Map what you use in Mux to ClipMux, see what ClipMux doesn't have, and move an app across step by step.
Source: https://clipmux.com/docs/resources/migrate-from-mux
ClipMux has the same shape as Mux Video: a video gets one or more playback
IDs, your backend signs a JWT for private playback, browsers upload straight
to storage, and webhooks tell you when a video is ready. The difference is
that you run it: one server and Postgres, with your own storage and,
optionally, your own Cloudflare account and GPUs.
This page maps the two, lists what ClipMux doesn't do, and moves an app
across without downtime: new uploads go to ClipMux while old videos keep
playing from Mux until they are imported.
## Concept map [#concept-map]
| Mux | ClipMux | What changes |
| --- | --- | --- |
| Asset | Video, `ast_…` (`asset` in the API) | The status is `waiting_upload`, `processing`, `ready`, `errored` or `deleted` |
| Playback ID, `public` or `signed` policy | Playback ID, `pid_…`, `public` or `signed` policy | The same idea. A video can have several, and revoking one stops it at once |
| `passthrough` | `passthrough` | The same: your own reference, returned on the video and its webhooks. Find videos by it with `GET /v1/assets?passthrough=` |
| Direct upload (create it at `/video/v1/uploads`, then `PUT` the file to its URL) | Upload (`POST /v1/uploads`), then parts sent straight to storage | Uploads are multipart and resumable. `@clipmux/uploader` does it in the browser |
| Asset from a URL (an asset created with an input URL) | `POST /v1/assets` with `url` | The server fetches the file from a public http(s) URL |
| Signing key, RS256 JWT | Signing key, ES256 JWT (P-256) | Signing stays local in your backend |
| JWT `aud`: `v` video, `t` thumbnail, `g` GIF, `s` storyboard, `d` DRM licence | JWT `aud`: `v` video, its tracks and poster; `t` poster only | Only `v` and `t` exist |
| Token in the query, `stream.mux.com/{playback_id}.m3u8?token=…` | Token in the path, `https://media.example.com/v/{token}/{playback_id}/master.m3u8` | Public videos are `/p/{playback_id}/master.m3u8` |
| Thumbnails, GIFs and storyboards | One poster per video, `…/{playback_id}/poster.jpg` | No size or time parameters |
| `Mux-Signature: t=…,v1=…`, HMAC-SHA256 of `timestamp.body` | `X-Webhook-Timestamp` and `X-Webhook-Signature: sha256=…`, HMAC-SHA256 of `timestamp.body` | The same construction in other headers. Dedupe on `X-Webhook-Id` |
| Mux Data | Views, watch time and unique viewers, counted at delivery | No player beacon, no quality-of-experience metrics |
### Webhook events [#webhook-events]
| Mux | ClipMux |
| --- | --- |
| `video.asset.created` | No event; the upload or import response is the video |
| `video.asset.ready` | `video.asset.ready` |
| `video.asset.errored` | `video.asset.errored` |
| `video.asset.updated` | `video.asset.updated` |
| `video.asset.deleted` | `video.asset.deleted` |
| `video.asset.track.*` | `video.asset.track.ready`, `video.asset.track.errored`, `video.asset.track.deleted` |
| `video.upload.*` | No events; a cancelled upload makes the video `errored` with `upload_cancelled` |
| None | `video.asset.reencode_failed`: a re-encode failed, and the current version keeps playing |
The full list, with payloads, is in [Webhook events](/docs/reference/webhooks).
## What ClipMux doesn't have [#what-clipmux-doesnt-have]
- **Live streaming.** ClipMux is video on demand only; there is no RTMP
ingest.
- **DRM.** Videos are AES-128 encrypted HLS, which protects your storage
but isn't DRM: anyone with a valid token can fetch the key. See
[What encryption does and doesn't do](/docs/build/concepts/encryption).
- **MP4 downloads.** Playback is HLS only.
- **Thumbnails, GIFs and storyboards.** There is one poster per video, with
no time or size parameters, and no animated or storyboard images.
- **Mux Data's depth.** Analytics are views, watch time, bytes and unique
viewers, counted from what delivery serves.
- **A hosted service.** You run the server, its database and backups. See
[Requirements and sizing](/docs/self-host/requirements).
## Move an app [#move-an-app]
### Create the app in ClipMux [#create-the-app-in-clipmux]
[Install a server](/docs/self-host/install), then connect your app. From the
app's project:
```bash
npx @clipmux/node init --server https://video.example.com
```
The owner approves it in the dashboard, and the API key, signing key and
webhook secret go to `.env.local`. Keep your Mux credentials until the move
is done.
### Store which service each video is on [#store-which-service-each-video-is-on]
Add a column to your own records, such as `provider`, set to `mux` for every
existing video. Your pages pick the player and the token signing by it
while both run.
### Send new uploads to ClipMux [#send-new-uploads-to-clipmux]
Point your upload route at ClipMux, with the same `passthrough` you gave
Mux:
```ts
const upload = await clipmux.uploads.create({ size, passthrough: 'lesson_42' })
```
In the browser, replace UpChunk or your Mux upload code with
`` or `ClipMuxUpload`. See
[Upload from the browser](/docs/build/upload/browser).
### Receive ClipMux webhooks [#receive-clipmux-webhooks]
Add a webhook route that verifies ClipMux's signature and handles
`video.asset.ready`, matching the video to your record by `passthrough`.
Keep the Mux webhook route until the last Mux video is gone. See
[Receive webhooks](/docs/build/webhooks).
### Switch token signing [#switch-token-signing]
For ClipMux videos, sign an ES256 token with your ClipMux signing key, with
`sub` the ClipMux playback ID and `aud` `v`:
```ts
const token = await clipmux.playback.token('pid_…', { viewerId: user.id })
```
Mux's RS256 keys don't work with ClipMux, and a Mux `aud` of `g`, `s` or `d`
has no equivalent. See [Sign playback tokens](/docs/build/play/sign-tokens).
### Switch the player [#switch-the-player]
For ClipMux videos, use `` with a `session-url`, or give
another HLS player the ClipMux URL, which carries the token in its path
rather than in `?token=`. See [Add the player](/docs/build/play/player).
### Import your existing videos [#import-your-existing-videos]
For each Mux video, give ClipMux a URL it can fetch the original from, with
your existing `passthrough`:
```bash
curl https://video.example.com/v1/assets \
-H "Authorization: Bearer cmx_…" \
-H "Content-Type: application/json" \
-d '{"url": "https://files.example.com/lesson-42.mp4", "passthrough": "lesson_42"}'
```
The URL must be public http(s), with no credentials in it. When
`video.asset.ready` arrives, store the new playback ID and set the record's
`provider` to `clipmux`. See [Import from a URL](/docs/build/upload/from-url).
### Retire Mux [#retire-mux]
Once every record says `clipmux`, remove the Mux player, token signing and
webhook route, and delete the videos from Mux.
## Check it works [#check-it-works]
- `npx @clipmux/node doctor` passes every check.
- A new upload reaches `ready`, your webhook route logs `video.asset.ready`,
and the video plays for a signed-in viewer.
- An imported video plays from ClipMux with its old `passthrough`, which
`GET /v1/assets?passthrough=lesson_42` finds.
## Next [#next]
- [Quickstart](/docs/build/quickstart)
- [How ClipMux works](/docs/build/concepts/how-it-works)
- [Limitations](/docs/self-host/limitations)
---
# Migrate from Cloudflare Stream
Map what you use in Cloudflare Stream to ClipMux, see what ClipMux doesn't have, and move an app across step by step.
Source: https://clipmux.com/docs/resources/migrate-from-cloudflare-stream
Cloudflare Stream and ClipMux both take an upload, encode it, and stream
HLS with signed tokens for private videos. With Stream, Cloudflare stores
and encodes the video. With ClipMux, you run the server, choose the storage,
and can still serve playback from Cloudflare's edge through a Worker and R2
bucket in your own account.
This page maps the two, lists what ClipMux doesn't do, and moves an app
across without downtime: new uploads go to ClipMux while old videos keep
playing from Stream until they are imported.
## Concept map [#concept-map]
| Cloudflare Stream | ClipMux | What changes |
| --- | --- | --- |
| Video, by its `uid` | Video, `ast_…` (`asset` in the API), played through a playback ID, `pid_…` | In ClipMux the playback ID is separate from the video. A video can have several, and revoking one stops it at once |
| `requireSignedURLs: true` | A playback ID with the `signed` policy | Uploads are `signed` unless you ask for `playback_policy: "public"` |
| `meta` | `passthrough` and `title` | `passthrough` is one string, your own reference, returned on the video and its webhooks |
| Direct creator upload, created at `/stream/direct_upload`, then tus or a single upload to `uploadURL` | Upload (`POST /v1/uploads`), then parts sent straight to storage | Multipart and resumable without tus. `@clipmux/uploader` does it in the browser |
| Upload from a link, at `/stream/copy` with `url` | `POST /v1/assets` with `url` | The server fetches the file from a public http(s) URL |
| Signing key from `/stream/keys`, RS256 JWT | Signing key, ES256 JWT (P-256) | Signing stays local in your backend |
| JWT claims `sub` (the video), `kid`, `exp`, `nbf`, `accessRules`, `downloadable` | Header `kid`; claims `sub` (the playback ID), `aud`, `iat`, `exp`, optional `vid` | No IP or country rules. `aud` is `v` to play, or `t` for the poster only |
| `exp` at most 24 hours after signing | `exp − iat` at most the server's maximum, 7 days by default | Read it as `max_token_lifetime_seconds` from `GET /v1/app` |
| Token in place of the video ID, `customer-.cloudflarestream.com//manifest/video.m3u8` | Token before the playback ID, `https://media.example.com/v/{token}/{playback_id}/master.m3u8` | Public videos are `/p/{playback_id}/master.m3u8` |
| Thumbnails with `time`, `height` and `width`, and animated GIFs | One poster per video, `…/{playback_id}/poster.jpg` | No parameters and no GIFs |
| One webhook URL per account, `Webhook-Signature: time=…,sig1=…`, HMAC-SHA256 of `time.body` | Webhook endpoints per app, `X-Webhook-Timestamp` and `X-Webhook-Signature: sha256=…`, HMAC-SHA256 of `timestamp.body` | The same construction in other headers. Dedupe on `X-Webhook-Id` |
| A notification when processing ends, with `status.state` `ready` or `error` | `video.asset.ready` or `video.asset.errored` | ClipMux also sends `updated`, `deleted`, `reencode_failed` and track events; see [Webhook events](/docs/reference/webhooks) |
| The Stream Player iframe | `@clipmux/player`, or any HLS player | No iframe or hosted embed |
## What ClipMux doesn't have [#what-clipmux-doesnt-have]
- **Live streaming.** ClipMux is video on demand only.
- **MP4 downloads.** Playback is HLS only; there is nothing like Stream's
`downloadable`.
- **Access rules.** Tokens have no IP or country rules. Your backend decides
who gets a token.
- **Thumbnails at a chosen time, and GIFs.** There is one poster per video.
- **An iframe embed.** You add the player to your pages yourself.
- **DRM.** Videos are AES-128 encrypted HLS, which protects your storage
but isn't DRM. See
[What encryption does and doesn't do](/docs/build/concepts/encryption).
- **A hosted service.** You run the server, its database and backups. See
[Requirements and sizing](/docs/self-host/requirements).
## Move an app [#move-an-app]
### Create the app in ClipMux [#create-the-app-in-clipmux]
[Install a server](/docs/self-host/install), then connect your app. From the
app's project:
```bash
npx @clipmux/node init --server https://video.example.com
```
The owner approves it in the dashboard, and the API key, signing key and
webhook secret go to `.env.local`. To keep serving from Cloudflare's edge,
connect Cloudflare delivery on the server; see
[Cloudflare edge delivery](/docs/self-host/delivery/cloudflare).
With Cloudflare delivery, new videos' encrypted, encoded files are stored
in an R2 bucket in your Cloudflare account, and a Worker there serves them
and their keys to viewers.
### Store which service each video is on [#store-which-service-each-video-is-on]
Add a column to your own records, such as `provider`, set to `stream` for
every existing video, and a column for your own reference if `meta` held it.
Your pages pick the player and the token signing by `provider` while both
run.
### Send new uploads to ClipMux [#send-new-uploads-to-clipmux]
Point your upload route at ClipMux, with your own reference as
`passthrough`:
```ts
const upload = await clipmux.uploads.create({ size, passthrough: 'lesson_42' })
```
In the browser, replace the tus client and `uploadURL` with
`` or `ClipMuxUpload`. See
[Upload from the browser](/docs/build/upload/browser).
### Receive ClipMux webhooks [#receive-clipmux-webhooks]
Add a webhook route that verifies ClipMux's signature and handles
`video.asset.ready`, matching the video to your record by `passthrough`.
Keep the Stream webhook route until the last Stream video is gone. See
[Receive webhooks](/docs/build/webhooks).
### Switch token signing [#switch-token-signing]
For ClipMux videos, sign an ES256 token with your ClipMux signing key, with
`sub` the ClipMux playback ID and `aud` `v`:
```ts
const token = await clipmux.playback.token('pid_…', { viewerId: user.id })
```
Stream's RS256 keys don't work with ClipMux. See
[Sign playback tokens](/docs/build/play/sign-tokens).
### Switch the player [#switch-the-player]
For ClipMux videos, use `` with a `session-url` in place of
the iframe, or give another HLS player the ClipMux URL. See
[Add the player](/docs/build/play/player).
### Import your existing videos [#import-your-existing-videos]
For each Stream video, give ClipMux a URL it can fetch the original from,
with your reference as `passthrough`:
```bash
curl https://video.example.com/v1/assets \
-H "Authorization: Bearer cmx_…" \
-H "Content-Type: application/json" \
-d '{"url": "https://files.example.com/lesson-42.mp4", "passthrough": "lesson_42"}'
```
The URL must be public http(s), with no credentials in it. When
`video.asset.ready` arrives, store the new playback ID and set the record's
`provider` to `clipmux`. See [Import from a URL](/docs/build/upload/from-url).
### Retire Stream [#retire-stream]
Once every record says `clipmux`, remove the Stream player, token signing
and webhook route, and delete the videos from Stream.
## Check it works [#check-it-works]
- `npx @clipmux/node doctor` passes every check.
- A new upload reaches `ready`, your webhook route logs `video.asset.ready`,
and the video plays for a signed-in viewer.
- An imported video plays from ClipMux, and
`GET /v1/assets?passthrough=lesson_42` finds it.
## Next [#next]
- [Quickstart](/docs/build/quickstart)
- [How ClipMux works](/docs/build/concepts/how-it-works)
- [Limitations](/docs/self-host/limitations)
---
# Architecture overview
The core model, the three adapters and the rules that keep ClipMux safe, on one screen.
Source: https://clipmux.com/docs/resources/architecture
ClipMux is one Go binary and Postgres. Ingest (how bytes get in), compute
(who encodes and encrypts) and delivery (how viewers get the video) are
separate layers that share one data model in Postgres. Each sits behind a
narrow adapter, so the API your apps call stays the same when you change
storage, encoding or delivery.
The full specification is
[docs/architecture.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/architecture.md)
on GitHub.
## The core model [#the-core-model]
| Object | What it is |
| --- | --- |
| App | One integration, such as a course site. It owns its API keys, signing keys, webhook endpoints and the videos it creates |
| Asset | A video, as the API sees it |
| Output | An immutable set of encrypted files from one encode |
| Job | A unit of work on a video: transcode, re-encode, move, delete |
| Attempt | One executor's run of a job, with a lease |
| Playback ID | The public handle a player uses. A video can have several, public or signed |
| Upload | A multipart upload in progress |
| Agent | A PC you approved to encode |
A video points at its current output, and a playback ID reaches files only
through that pointer. A re-encode writes a new output, and the pointer moves
when it's done, so viewers never see a half-written version.
All work goes through one job queue in Postgres. Every executor, including
the worker built into the server, claims jobs through the same worker API.
## The adapters [#the-adapters]
| Adapter | Choices |
| --- | --- |
| Storage | This server's disk, Cloudflare R2, or any S3-compatible bucket |
| Executor | The server's built-in worker, a PC agent, Modal, RunPod |
| Delivery | The built-in handler, or a Cloudflare Worker in your account |
Core logic never branches on a vendor. Both delivery adapters use the same
hostname, URLs, tokens and key derivation, so moving to the Worker changes no
playback URL.
## The rules [#the-rules]
These hold everywhere in the code, and nothing weakens them:
- **Executors hold no storage credentials.** A worker gets a job and
short-lived signed URLs for the files it may write. Its file names are
checked against a path grammar, its playlists at commit, and delivery
serves only allowed file types. FFmpeg runs sandboxed.
- **Outputs are immutable.** Only the video's current-output pointer moves.
A path is never reused, so cached files never go stale.
- **Outputs are ciphertext.** Every output is AES-128 encrypted, and its key
is derived at delivery, never stored.
- **One mutating job per video.** A re-encode, a move and a delete never
overlap on the same video. A delete always wins.
- **Side effects run from an outbox.** Anything outside Postgres, such as
publishing a playback route or sending a webhook, is written as an outbox
row in the same transaction and retried until it succeeds.
- **Routes are default-deny.** Delivery serves a playback ID only from its
route record; an unknown or revoked ID is refused.
- **The dashboard and CLI are API clients.** Neither has a private path into
the server.
## Next [#next]
- [How ClipMux works](/docs/build/concepts/how-it-works)
- [Security model](/docs/self-host/security-model)
- [Management API](/docs/reference/management-api)
---
# FAQ
Short answers about DRM, scaling, cost, the licence, Docker, live streaming and more.
Source: https://clipmux.com/docs/resources/faq
## Is this DRM? [#is-this-drm]
No. Every video is stored and streamed as AES-128 encrypted HLS, and its key
goes only to a request with a valid token. That keeps your storage useless
to anyone who copies it, and a leaked segment URL useless without the key.
But anyone with a valid token can fetch the key, and common download tools
do that. There is no Widevine or FairPlay. See
[What encryption does and doesn't do](/docs/build/concepts/encryption).
## Can I run more than one replica? [#can-i-run-more-than-one-replica]
Not of the server. One `clipmux serve` is the supported shape: rate limits,
sign-in limits and some caches live in the process, so a second replica
would double the limits and keep stale settings. Encoding scales
separately: add PC agents, or connect Modal or RunPod, and they take jobs
from the same queue. Delivery can scale out to Cloudflare's edge with a
Worker in your account. See [Limitations](/docs/self-host/limitations).
## What does it cost to run? [#what-does-it-cost-to-run]
There is no licence fee and nothing to pay ClipMux. You pay for:
- **Your server**, its disk, and its bandwidth when it serves playback
itself. See [Requirements and sizing](/docs/self-host/requirements).
- **Storage**, if you use R2 or another S3-compatible bucket rather than the
server's disk.
- **Optional GPUs** on Modal or RunPod, billed by the provider for the time a
machine runs. Each provider has a monthly spend limit, $50 unless you set
another; at the limit, ClipMux sends it no more jobs. See
[Routing, fallback and spend limits](/docs/self-host/encoding/routing-and-limits)
and [Encoding performance](/docs/self-host/encoding/performance).
- **Optional Cloudflare**, for edge delivery from your own account.
- **Optional speech or LLM APIs**, if you use one for subtitles or chapters
instead of the server's own whisper.cpp.
## Why AGPL? [#why-agpl]
The server is AGPL-3.0, so the platform and the improvements made to it stay
open. The parts your app embeds are MIT: `@clipmux/node`,
`@clipmux/player`, `@clipmux/uploader` and the Cloudflare Worker. They are
MIT so your app can use them freely.
## Can I use it without Docker? [#can-i-use-it-without-docker]
The server is installed with Docker Compose: the one-line installer and the
from-source install both run ClipMux, Postgres and Caddy in containers. See
[Install with one line](/docs/self-host/install).
A PC agent, which encodes on a machine you own, can run on Linux without
Docker. See [Encode on a PC you own](/docs/self-host/encoding/your-pc).
## Does it do live streaming? [#does-it-do-live-streaming]
No. ClipMux is video on demand: videos are uploaded, imported from a URL or
pushed from the command line, then encoded and streamed.
## Do videos leave my servers? [#do-videos-leave-my-servers]
Not unless you choose a service that sends them. Encoding on Modal or
RunPod, Cloudflare delivery, a speech API for subtitles and an LLM for
chapters each send something to that provider, and each is off until you
connect it. The pages for each say exactly what goes where.
## Can I use my own player? [#can-i-use-my-own-player]
Yes. Any HLS player can play a ClipMux URL: the token rides in the path, so
the player needs no special support, though only a player that asks for a
new token can renew one. See
[Other players and native apps](/docs/build/play/other-players).
## Can my app's users upload directly? [#can-my-apps-users-upload-directly]
Yes. Your backend creates an upload with its API key, and the browser sends
the file in parts straight to storage with a token that reaches only that
upload. See [Upload from the browser](/docs/build/upload/browser).
## Can I migrate from Mux or Cloudflare Stream? [#can-i-migrate-from-mux-or-cloudflare-stream]
Yes, without downtime: send new uploads to ClipMux and import existing
videos by URL. See [Migrate from Mux](/docs/resources/migrate-from-mux) and
[Migrate from Cloudflare Stream](/docs/resources/migrate-from-cloudflare-stream).
## Next [#next]
- [Limitations](/docs/self-host/limitations)
- [Architecture overview](/docs/resources/architecture)
- [Security model](/docs/self-host/security-model)
---
# Contributing
How to set up the repository, how changes are made, and what a pull request needs.
Source: https://clipmux.com/docs/resources/contributing
Thanks for helping. ClipMux is one Go binary (`cmd/clipmux`) with a
Postgres job queue, immutable encrypted outputs and filesystem-first
storage. Before you change anything, read
[docs/architecture.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/architecture.md),
the specification, and
[AGENTS.md](https://github.com/visheshgubrani/clipmux/blob/main/AGENTS.md),
the working rules for people and coding agents alike.
By taking part you agree to the
[Code of Conduct](https://github.com/visheshgubrani/clipmux/blob/main/CODE_OF_CONDUCT.md).
Report a security problem privately, never in an issue; see the
[security policy](/docs/resources/security-policy).
## Licence and sign-off [#licence-and-sign-off]
- The repository is AGPL-3.0. `packages/node`, `packages/player`,
`packages/uploader` and `worker/` are MIT, each with its own `LICENSE`, so
apps embed them freely.
- Contributions are accepted under the licence of the directory they touch,
certified with the
[Developer Certificate of Origin](https://developercertificate.org/). There
is no CLA. Sign off every commit:
```bash
git commit -s -m "Explain the change"
```
This adds `Signed-off-by: Your Name `, which certifies
that you wrote the change or have the right to submit it under the
project's licence. A pull request whose commits aren't all signed off
can't be merged; `git rebase --signoff main` fixes an existing branch.
## Set up [#set-up]
You need Go (the version in `go.mod`), Docker with Compose, Node 24 and
pnpm (`corepack enable`).
```bash
make db-up # dev Postgres on :5444
make test # go vet ./... && go test ./...
make test-db # the same, with the *_db_test.go tests against dev Postgres
make lint # gofmt, vet, staticcheck -checks all, govulncheck
make run # clipmux serve; it prints a setup token for the dashboard
pnpm install && pnpm -r run build # dashboard, packages, Worker
```
The media tests need FFmpeg, ffprobe and Shaka Packager 3.9.1 or later
(`toolchain/install_packager.sh`); they skip without them. The whisper.cpp
tests need `toolchain/build_whisper.sh` and its models
(`toolchain/fetch_speech_models.sh`).
## How changes are made [#how-changes-are-made]
- **Tests first, at the seams.** A failing test, then the code that passes
it, one vertical slice at a time. Expected values come from literals or
worked examples, never from the code under test.
- **Database behaviour is tested against real Postgres** with
`dbtest.New(t)`, in files named `*_db_test.go`, never with SQL-substring
checks.
- **Schema changes are new goose migrations** in `internal/db/migrations`,
each with a working Down. Never edit an applied migration. Queries live in
`internal/db/queries` and are generated with `make sqlc`.
- **Keep it lean.** No package before its code, interfaces belong to their
consumer, the standard library first, and duplicate once before
abstracting. AGENTS.md has the rest.
- **The invariants aren't negotiable.** Executors hold no storage
credentials; outputs are immutable and only `current_output_id` moves; one
mutating job per asset; side effects outside Postgres run from outbox rows;
route records default-deny; worker file names are untrusted; FFmpeg runs
sandboxed.
- **Never commit secrets.** No `.env*` except `.env.example`. Never log
Authorization headers, tokens, presigned URLs, content keys or secrets.
- **The delivery contract** is `internal/delivery/testdata/vectors.json`,
shared by the Go handler and the Cloudflare Worker. Change it first, and
both sides together.
- **Media tool versions** are written only in `toolchain/versions.env`.
- **Docs change with behaviour.** A change in behaviour updates its page in
`site/content/docs` in the same pull request.
## Pull requests [#pull-requests]
- One change per pull request, with the reasoning it rests on.
- `make lint` and `make test-db` pass locally; for TypeScript, `pnpm lint`,
`pnpm typecheck` and `pnpm test`.
- A change to playback, delivery, the player or the dashboard also runs the
end-to-end suites, which a maintainer starts.
- A limitation you introduce or find goes in
[docs/known-gaps.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/known-gaps.md).
## Next [#next]
- [Architecture overview](/docs/resources/architecture)
- [Security policy](/docs/resources/security-policy)
- [FAQ](/docs/resources/faq)
---
# Security policy
How to report a vulnerability privately, what is in scope, and what ClipMux defends.
Source: https://clipmux.com/docs/resources/security-policy
ClipMux holds storage credentials, content keys, signing keys and webhook
secrets for the people who run it, and plays media to the public. Please
report vulnerabilities privately.
## Report a vulnerability [#report-a-vulnerability]
Don't open a public issue, discussion or pull request. Use GitHub's private
vulnerability reporting: on
[visheshgubrani/clipmux](https://github.com/visheshgubrani/clipmux), open
**Security**, then **Report a vulnerability**. Include what you can of:
- the version (`clipmux version`) or commit, and how it is deployed:
Compose, the agent installer, a serverless provider, Cloudflare delivery;
- a minimal reproduction: requests, files, configuration;
- what an attacker gains;
- a fix, if you have one.
You'll get an acknowledgement within 3 days and an update at least every 7
days until it is resolved. Please give us 90 days, or until a fixed release
ships if that is sooner, before disclosing. We credit reporters in the
advisory unless you ask us not to.
## Scope [#scope]
In scope: everything in the repository. That is the `clipmux` binary
(serve, the built-in worker, PC agents, `push`, `listen`, `admin`), the
image and agent tarball as released, the Cloudflare Worker (`worker/`),
`@clipmux/node`, `@clipmux/player`, `@clipmux/uploader`, and the installers in `deploy/`. A
vulnerable dependency we ship is in scope.
Out of scope: a deployment's own configuration (a leaked key, a public
bucket, a disabled sandbox), vulnerabilities in Cloudflare, RunPod, Modal or
another provider's platform, and denial of service by sheer volume.
## What we defend [#what-we-defend]
The threat model is the "Threats and controls" table in
[docs/architecture.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/architecture.md),
and
[docs/security-review.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/security-review.md)
records its latest review against the code. In short:
- **Playback** uses ES256 JWTs per app, checked on every request. Route
records default-deny, and segments are AES-128 encrypted with keys served
only to valid tokens.
- **Workers are untrusted.** Executors hold no storage credentials: they get
short-lived signed URLs for names that pass a path grammar, playlists are
checked at commit, and delivery serves only allowed file types. FFmpeg,
ffprobe, the packager and whisper.cpp run sandboxed (seccomp, rlimits,
`no_new_privs`, and Landlock where the kernel has it).
- **Secrets at rest**, such as storage and provider credentials, signing
keys, webhook secrets, the content key secret, TOTP secrets and AI keys,
are sealed in Postgres with a key held outside it, and can be rotated.
- **Logs** never hold Authorization headers, tokens, presigned URLs, content
keys or secrets.
[docs/known-gaps.md](https://github.com/visheshgubrani/clipmux/blob/main/docs/known-gaps.md)
lists the limitations we know of and accept for now. A report that one of
them is worse than it says is welcome.
## Supported versions [#supported-versions]
The latest release gets security fixes. Before v1.0.0, only `main`.
## Next [#next]
- [Security model](/docs/self-host/security-model)
- [Security checklist](/docs/self-host/operate/security-checklist)
- [Rotate keys and secrets](/docs/self-host/operate/rotate-secrets)