@hussmartinez/video-sdk
v0.11.1
Published
Client-side video SDK: a headless core, a React editor and a custom element. Videos never leave the device.
Downloads
5,177
Maintainers
Readme
video-sdk
A client-side video SDK: trim, split, arrange, rotate, crop and export videos entirely in the browser. Videos never leave the device. Its headless core, React editor (VideoEditor) and <hm-video-editor> custom element are published.
This repository publishes @hussmartinez/video-sdk. It follows the family standards in sdk-core's STANDARDS.md, and in particular the decisions on hostile input and no network, workers and assets and ports and adapters.
Status: pre-1.0. The headless core, the React editor and the
<hm-video-editor>element are published. The editor's inspector sets a clip's volume, mute, fades, rotation, fit and crop, and, with no clip selected, the exported video's size, frame rate and sound, and its title and other details; audio tracks come later (ADR 0008 has the order). The API may change between minor versions until 1.0.
Install
pnpm add @hussmartinez/video-sdkReact and React DOM 18.3 or later are optional peer dependencies, needed only for @hussmartinez/video-sdk/react. @hussmartinez/ui and @hussmartinez/sdk-core come with the package.
| Entry | What it has | Where it runs |
|---|---|---|
| @hussmartinez/video-sdk | The headless core: the session, commands, engine, playback output, export, limits, errors and messages | Anywhere, servers included: no React, and no DOM access on import |
| @hussmartinez/video-sdk/react | VideoEditor, its building blocks and hooks | Client components: it starts with "use client" |
| @hussmartinez/video-sdk/element | defineVideoEditorElement, for the <hm-video-editor> custom element | Browsers; it registers nothing on import, and needs React and React DOM |
| @hussmartinez/video-sdk/styles.css | The editor's styles, in the hm.sdk cascade layer | Import it once, after @hussmartinez/ui/styles.css |
The editor
import "@hussmartinez/ui/styles.css";
import "@hussmartinez/video-sdk/styles.css";
import { VideoEditor } from "@hussmartinez/video-sdk/react";
export function Editor() {
return (
<VideoEditor
filePolicy={{ maxDuration: 30 * 60 * 1_000 }} // or leave it out for the defaults
locale="en"
onEvent={(event) => analytics.track(event)} // anonymous: no names, frames, audio or metadata; "download" when Download hands the file to the browser
/>
);
}It renders through ui's editor frame (ADR 0010): a top bar with the mode switch, Undo, Redo, the theme toggle, Settings and Export; a tools panel of the editing tools, by mode; the preview; the inspector as the properties panel; and the transport, the zoom and the timeline across the foot. It covers: add videos, trim, split, move and delete clips, set their volume, mute and fades, rotate, fit and crop them, undo and redo, play, and export through a dialog that shows what the file will contain before the download. Every action has keys, listed in ADR 0007.
- Props:
initialFiles,fileName(the name an export downloads under, such as the original file's, or the video's title otherwise, cleaned as the family cleans a file name, pdf-sdk ADR 0009),onExport(takes the exportedBlobinstead of the download, such as to upload it),filePolicy,assetsUrl,localeandmessages,toolsandtoolbarto choose the tools,preferences,defaultPreferencesandonPreferencesChangefor the person's mode, theme and panels (ui'sEditorPreferences, which the editor never stores),onEvent,engineandprocessorto supply your own, andclassName. - The ref handle has
open(file), which opens a file in place of the plan,insert(file, at?),undo(),redo(),play(),pause(),seek(frame)andexport(options?), which exports the plan as it is for a host's own export button, without the dialog, resolving with the file and what clamping did to its sound. - Building blocks:
VideoEditorProviderwithVideoToolbar,VideoStage,VideoTransport,VideoTimeline,VideoInspectorandVideoExportDialog, and the hooksuseVideoSession,useVideoOutputanduseVideoPlayhead, for a layout of your own. - Server rendering: on a server the editor renders its empty state, with no canvas, engine or worker.
- Layout follows the container, not the viewport: an editor in a narrow column lays out for the column.
The element
import "@hussmartinez/ui/styles.css";
import "@hussmartinez/video-sdk/styles.css";
import {
defineVideoEditorElement,
type VideoEditorElementProps,
} from "@hussmartinez/video-sdk/element";
defineVideoEditorElement();
const editor = document.querySelector("hm-video-editor") as HTMLElement & VideoEditorElementProps;
editor.file = file;
editor.addEventListener("hm-video-editor-change", (event) => save((event as CustomEvent).detail));<hm-video-editor> renders VideoEditor into its light DOM, for pages without React of their own. React and React DOM, the package's optional peer dependencies, are still needed. Importing the entry registers nothing: call defineVideoEditorElement() once, for hm-video-editor or a tag you name. The stylesheet makes the element a block, which you size.
- Attributes:
theme(light,darkorsystem),locale, andtools, space-separated. - Properties:
fileopens a video in place of the plan when you set it, and setting another opens that one, replacing it. A failed open keeps the plan.insertadds more files;fileName,filePolicy,assetsUrl,messages,engineandprocessor.
- Methods:
open,insert,export,undo,redo,play,pauseandseek.open,insertandexportwait for the editor's first render, andplayfor its preview. If the element is removed before then, they reject withABORTEDanddetails.reason: "removed". - Events, none of which carries a file name or contents:
hm-video-editor-change, with the plan;hm-video-editor-event, with the usage event;hm-video-editor-export, with aVideoExportReportafter the export dialog finishes: the container, size, peak and clamped frames, and no file;hm-video-editor-error, with a failure'scodeanddetails.
The headless core
createVideoSession() holds what's being edited: a clip plan over immutable sources, edited with commands, with undo and redo (ADR 0003). The engine reads files in a Web Worker, the output plays the plan into a canvas, and the processor exports it:
import {
createVideoEngine,
createVideoOutput,
createVideoProcessor,
createVideoSession,
videoMessages,
} from "@hussmartinez/video-sdk";
import { createMessages } from "@hussmartinez/sdk-core";
const messages = createMessages(videoMessages, { locale: "en" });
const engine = createVideoEngine();
const session = createVideoSession({ engine, processor: createVideoProcessor({ engine }) });
const output = createVideoOutput({ engine, canvas });
session.subscribe(() => {
const { plan } = session.getSnapshot(); // or useSyncExternalStore in React
if (plan) output.load(plan);
});
try {
await session.insert(file); // probed and checked against the limits before anything decodes
// session.open(file) instead starts over: it replaces the plan, and clears undo.
// Split the first clip one second in, and make its first part quieter, fading in.
const first = session.getSnapshot().plan?.clips[0];
const { num, den } = session.getSnapshot().plan?.output.frameRate ?? { num: 30, den: 1 };
if (first) {
session.execute({
type: "video.splitClip",
key: first.key,
at: Math.round(num / den), // a timeline position, in output frames
newKey: session.newClipKey(),
});
session.execute([
{ type: "video.setVolume", keys: [first.key], volumeDb: -6 },
{ type: "video.setFade", key: first.key, edge: "in", duration: 500_000, curve: "equalPower" },
]); // one undo step; times are microseconds
}
session.undo(); // and session.redo()
await output.play(); // call it from a click: browsers start audio only then
// The plan as it is now; edits while it runs don't change the file.
const { blob, peakDb, clippedFrames } = await session.export({ container: "mp4", signal });
offerDownload(blob); // a Blob: the SDK never downloads anything itself
if (clippedFrames > 0) warnTooLoud(peakDb); // the sound was clamped at full scale, by this much
for (const warning of session.getSnapshot().warnings) show(messages.warning(warning));
} catch (error) {
showError(messages.error(error)); // text by code and reason, never the error's message
}- The snapshot has the
plan(the output's size and rates, the clips, and the metadata), thesources,canUndoandcanRedo, how many files are being inserted, the lasterror, andwarnings: limits past their warning thresholds, as{ type: "limit", limit, actual, source? }, whose textmessages.warning(warning)gives.videoErrorTextandvideoWarningTextare deprecated: sdk-core'smessages.errorandmessages.warninggive the same text. - Commands are plain data, such as
video.trimClip,video.moveClips,video.setMutedorvideo.setTransform, with an exact inverse for undo. One that doesn't apply throwsINVALID_COMMANDwith a stabledetails.reason, such asunknown-clip. - Times are whole microseconds, and positions on the timeline are output frames, so every edit lands on a whole frame (ADR 0003).
- Audio: each clip has a volume, a mute and fades, and its sound stays with its picture through every edit. Playback uses the audio as its clock, so sound and picture stay within a frame of each other (ADR 0005).
- Exports decode, compose and encode every frame and sample again, faster than real time where the encoder is. The sound is clamped at full scale, never limited or normalised, and the result says how far over it was (
peakDb) and for how many frames (clippedFrames). They contain only what the plan names and the metadata you set: nothing a user cut, and nothing from a source's own metadata, such as its location or device. - Plans are portable JSON:
toVideoPlanDocumentandreadVideoPlanDocumentwrite and read thehm-video-planformat, whose JSON Schema ships in the package (format record).
Formats
| | Containers | Codecs |
|---|---|---|
| Opening | MP4, MOV, WebM and Matroska, and DAV recordings from Dahua recorders (DHAV), recognised by signature, never by name | Whatever the browser's WebCodecs decodes, such as H.264, VP8, VP9, AV1, AAC and Opus. In DAV: H.264, or HEVC where the browser has it, with G.711 or 16-bit PCM sound |
| Exporting | MP4, or WebM | H.264 with AAC, or with Opus where the browser has no AAC encoder; VP9 or VP8 with Opus in WebM |
Decoding and encoding are the browser's own, in workers, so support varies by browser: the SDK asks the one it runs in, and a file whose picture it can't decode fails with UNSUPPORTED_CODEC. A file whose sound it can't decode opens without sound, with a warning; and where it can't encode sound, an export fails with UNSUPPORTED_CODEC for the audio track, and session.export({ audio: "omit" }) makes it without sound. docs/capabilities.md shows what Chromium, Firefox and WebKit offer in the test image. Encrypted files, files with several edits in an edit list and files without a video track are refused, with a reason (ADR 0001).
Limits
Every file is treated as hostile. Before any decoder is configured, the SDK's own code checks the file's structure and walks every packet, and checks what it found, never what a header claims, against the file policy: size, frame size and rate, duration, bitrate, packet size, tracks, index size, channels and sample rate. Each has its own error code, and filePolicy raises or lowers any of them; a misspelt name throws. ADR 0004 lists the defaults, such as 4 GB, 4K, 120 frames a second and 3 hours.
Workers and Content Security Policy
| Mode | How | Directives |
|---|---|---|
| Inline (the default) | Nothing to set: the workers are inlined and start from blob: URLs | worker-src blob: |
| Self-hosted | <VideoEditor assetsUrl="/video-sdk/" />, or the same option for createVideoEngine and createVideoProcessor: serve the package's dist/assets/ there; the workers are video/media.worker.js and video/export.worker.js | worker-src 'self' |
Neither mode needs 'unsafe-eval', 'wasm-unsafe-eval' or 'unsafe-inline' styles, and the SDK makes no network requests of its own: no CDN, fonts or telemetry (ADR 0002). The examples run under default-src 'self'; script-src 'self'; style-src 'self' with each worker-src, and the end-to-end suite fails on a policy violation or a request to another origin.
Copy dist/assets again after every upgrade. A self-hosted worker from another version of the SDK is refused with WORKER_START_FAILED, whose details name the file and both versions.
Leave the inlined workers out of a self-hosted build with the hm-self-hosted resolve condition (sdk-core ADR 0060). Without it, an app that passes assetsUrl still bundles both inlined workers, about 605 kB minified, which it never loads. With it, the package's #hm-video-media-worker and #hm-video-export-worker imports resolve to a small stub instead. It's opt-in, and one setting covers every family SDK in your build:
| Bundler | Option | Status |
|---|---|---|
| Vite | resolve: { conditions: ["hm-self-hosted", ...defaultClientConditions] } | Verified |
| esbuild | conditions: ["hm-self-hosted"] | Verified |
| webpack | resolve.conditionNames | Expected to work, not yet verified |
| Rollup, with @rollup/plugin-node-resolve | exportConditions | Expected to work, not yet verified |
| Next.js | resolve.conditionNames, through its webpack configuration | Expected to work, not yet verified |
A build with the condition must pass assetsUrl: without it, starting a worker fails with WORKER_START_FAILED, whose details are { condition: "hm-self-hosted", missing: "assetsUrl" }, never a silent failure.
Errors
Every failure is a VideoError with a stable code and structured details; isVideoError(error, code) checks one, across workers and copies of the package. Show people the text for the code from videoMessages through createMessages, never error.message.
videoMessages holds only what the headless API hands you to show: sdk-core's text, and errors' and warnings' text. The editor's interface text, its labels, titles and announcements, is in videoEditorMessages, from @hussmartinez/video-sdk/react, with ui's text and videoMessages. Type overrides of the editor's text, for its messages prop or the element's, with MessageOverrides<VideoEditorMessageCatalogue> (sdk-core ADR 0059).
| Code | When |
|---|---|
| INVALID_VIDEO | A file is malformed, its headers disagree with its packets, or it decodes to more than its probe allows |
| UNSUPPORTED_FORMAT | A container the SDK doesn't read, an encrypted file, an edit list it refuses, or no video track |
| UNSUPPORTED_CODEC | A video codec the browser can't decode, or nothing it can encode for an export; details.track says whether it's the picture or the sound |
| DECODE_FAILED, ENCODE_FAILED | The browser failed on a file or an export it claimed to support |
| FILE_TOO_LARGE, FRAME_TOO_LARGE, DURATION_TOO_LONG and the other limit codes | A file, the plan or an export exceeds a limit; details name it, with its maximum and the actual value |
| INVALID_COMMAND, INVALID_DOCUMENT | A command or a stored plan that doesn't apply, with a details.reason |
| BUSY | An export was requested while another runs |
| PROCESSING_TIME_EXCEEDED, ABORTED | A call ran out of maxProcessingTime, or its signal aborted |
| UNSUPPORTED_ENVIRONMENT | The browser lacks a feature, such as WebCodecs in workers, which details.feature names |
| WORKER_START_FAILED, WORKER_CRASHED and other WORKER_* codes | A worker couldn't start, stopped unexpectedly, or is from another version |
Development
The repository root is the published package, laid out as in the family's standard layout: the source is in src. The pnpm workspace also holds the test applications (ADR 0039): examples/vite and examples/next, which run the built editor with its workers inlined and self-hosted, each under its Content Security Policy, and the e2e Playwright suite that tests them.
You need Node 24 (see .node-version) and pnpm. The exact pnpm version is pinned in package.json, and pnpm switches to it automatically.
pnpm install # also installs the git hooks
pnpm verify # everything CI runs
pnpm verify:fast # the subset the pre-push hook runsBrowser tests, the end-to-end tests and the screenshots run in the pinned browser image of ci/Dockerfile, as CI's do, through hm-in-image from @hussmartinez/sdk-config (sdk-core ADR 0049). So they need Docker, and no browsers installed on the machine: the host's own libraries and network changes can't affect them. Pass a test file to run only it, such as pnpm test:browser test/playback.browser.test.ts, and use pnpm test:browser:all for all three engines. The capability matrix is checked there too.
pnpm verify runs, in order:
| Step | Script | Tool |
|---|---|---|
| Format and lint | lint | Biome |
| CSS rules | lint:css | stylelint, with the hm- namespace and token rules |
| React rendering rules | lint:react | React's own ESLint plugin and nothing else, through hm-lint-react (sdk-core ADR 0063) |
| Types | typecheck | TypeScript |
| Dependency rules | lint:deps | dependency-cruiser, through hm-lint-deps |
| Build | build | Vite, then api-extractor for the type declarations |
| Unit tests | test | Vitest |
| Browser tests | test:browser | Vitest in the browser image, in Chromium, and in Firefox and WebKit too in CI |
| Example builds | build:examples | Vite and Next.js, on the workspace's build of the package |
| End-to-end tests | test:e2e | Playwright in the browser image, against the built examples, in Chromium, and all three engines in CI |
| Screenshots | test:visual | Playwright, in the pinned browser image through Docker; test:visual:update rewrites the baselines (sdk-core ADR 0048) |
| Size budgets | check:size | size-limit, brotli size of each entry point |
| API reports | check:api | api-extractor, one report per entry point in api |
| Package checks | check:package | publint and Are the Types Wrong? |
The configuration extends the shared presets in @hussmartinez/sdk-config. The git hooks (ADR 0016) run automatically: a secret scan and lint of staged files on commit, a Conventional Commits check of the message, and pnpm verify:fast on push.
When a change alters the public API on purpose, update the reports with pnpm api:update and commit them.
Contributing
Read CONTRIBUTING.md before opening a pull request. Coding agents also start with AGENTS.md. Everyone taking part follows the code of conduct. Report vulnerabilities privately, as described in the security policy.
