# 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 `