Server (Node)
The same export from Node, plus a CLI.
@miraiclip/server-export exports a project document from Node. It launches headless Chrome, loads the document into a page, and runs the same exportProject the browser uses.
npm install @miraiclip/server-exportimport { exportProjectFile } from "@miraiclip/server-export";
import { readFile } from "node:fs/promises";
const doc = JSON.parse(await readFile("project.json", "utf8"));
const { filePath, bytesWritten } = await exportProjectFile(doc, {
format: "mp4",
quality: "high",
out: "render/final.mp4",
assets: { interview: "./media/interview.mp4" },
onProgress: (p) => console.log(p.phase, p.framesDone, "/", p.totalFrames),
});The document is what project.toJSON() returns. Server export renders built-in clip kinds only: custom clip kinds need their factories, which can't cross into the page. In the next release, custom kinds packaged as plugins render here too. See Plugins.
Options
| Option | Default | What it does |
|---|---|---|
format | required | "mp4" or "webm" |
quality | "standard" | "draft", "standard", "high" or { videoBitrate } |
fps | project fps | Output frame rate (a number) |
width, height | project size | Output size |
range | whole composition | { startUs, endUs } |
out | none | File path to stream into. Parent folders are created |
assets | none | Asset id → local file path |
assetsDir | process.cwd() | Base folder for relative asset src values |
audioChunkSeconds | 60 | Audio mix chunk length |
signal | none | Rejects with ServerExportAbortedError |
onProgress | none | { phase, framesDone, totalFrames, audioMixedUs?, audioTotalUs?, bytesWritten? } |
browser | see The browser | { executablePath?, args?, swiftshader? } |
plugins | off | Next release. { allow, requireIntegrity?, dir? }. See Plugins |
Result
With out | Without out |
|---|---|
{ filePath, bytesWritten }. The file streamed to disk as it was encoded | { bytes }. The whole file in memory |
Use out for anything long. Without it, the file crosses from the page to Node in one piece, which briefly costs about twice its size in memory. A failed streamed export deletes the partial file.
bytesWritten in progress events is only set with out. Output is written in chunks of about 16 MiB, so short exports may report 0 until the end. Use framesDone / totalFrames for completion.
Cancel
import { ServerExportAbortedError, exportProjectFile } from "@miraiclip/server-export";
import type { ProjectDocument } from "@miraiclip/core";
declare const doc: ProjectDocument;
const controller = new AbortController();
process.on("SIGINT", () => controller.abort());
try {
await exportProjectFile(doc, { format: "webm", out: "out.webm", signal: controller.signal });
} catch (error) {
if (!(error instanceof ServerExportAbortedError)) throw error;
}Assets
Each asset's media must be readable on the server. Per asset, in order:
| Rule | Example |
|---|---|
An assets entry for the asset id | assets: { intro: "/data/intro.mp4" } |
An http(s): or data: src is fetched as-is | src: "https://cdn.example.com/intro.mp4" |
Any other src is a path relative to assetsDir | src: "media/intro.mp4" |
A local file that doesn't exist fails the export before the browser starts.
The browser
The package depends on playwright-core and downloads no browser. It launches the first of:
browser.executablePath- The
MIRAICLIP_BROWSERenvironment variable - The installed Google Chrome
| Browser | MP4 (H.264 + AAC) | WebM (VP9 + Opus) |
|---|---|---|
| Google Chrome | Yes | Yes |
| Chromium (including Playwright's download and most Docker images) | No: fails the codec check with a clear error | Yes |
On a server without Chrome, npx playwright install chrome installs it.
browser option | Default | What it does |
|---|---|---|
executablePath | none | Path to any Chrome or Chromium binary |
args | none | Extra Chrome flags, added after the defaults |
swiftshader | true on Linux, false elsewhere | Render WebGL in software. Servers rarely have a GPU |
Warm sessions
exportProjectFile launches a browser on every call. createExportSession keeps one browser open, so each export skips the launch. Calls on one session run one at a time, in order. A failed call doesn't break the session.
import { createExportSession } from "@miraiclip/server-export";
import type { ProjectDocument } from "@miraiclip/core";
declare const docA: ProjectDocument;
declare const docB: ProjectDocument;
const session = await createExportSession({ assetsDir: "./media" });
try {
await session.exportFile(docA, { format: "mp4", out: "out/a.mp4" });
await session.exportFile(docB, { format: "mp4", out: "out/b.mp4" });
} finally {
await session.close();
}| Function | Session options | Per call |
|---|---|---|
createExportSession(options?) | assets, assetsDir, browser, plugins | exportFile(doc, options): every exportProjectFile option except those four |
createRenderSession(options?) | assets, assetsDir, browser | renderStill(doc, { timeUs, width?, height? }): a PNG. See Stills |
For many videos from one template, Batch rendering runs rows through export sessions for you.
Plugins
Coming in the next release
Plugin loading in server export ships in the next SDK release.
A document's plugins are code, so server export never runs them unless you allow it. A document that lists a plugin you haven't allowed fails with a clear error.
import { exportProjectFile } from "@miraiclip/server-export";
import type { ProjectDocument } from "@miraiclip/core";
declare const doc: ProjectDocument;
await exportProjectFile(doc, {
format: "mp4",
out: "out.mp4",
plugins: { allow: ["https://cdn.example.com/plugins/"], requireIntegrity: true },
});plugins option | Default | Meaning |
|---|---|---|
allow | none | true for any plugin, a list of allowed URL prefixes, or a function (ref) => boolean |
requireIntegrity | false | Refuse plugins without an SRI integrity hash |
dir | assetsDir, else the working directory | Base folder for relative and file: plugin URLs |
Plugin sources are read and integrity-checked in Node, loaded for one export, then unloaded, so a warm session never carries one document's kinds into the next.
Distributed rendering
Coming in the next release
Distributed rendering ships in the next SDK release.
renderDistributed splits one export into frame-aligned video chunks, renders them in parallel, renders the sound once over the whole range, and joins everything with an ffmpeg stream copy (no re-encode). Each chunk runs the same export pipeline as a single-pass export, and the sound is mixed exactly as a single pass mixes it, so there are no seams at chunk boundaries.
import { localRunner, renderDistributed } from "@miraiclip/server-export";
import type { ProjectDocument } from "@miraiclip/core";
declare const doc: ProjectDocument;
const runner = localRunner({ concurrency: 4, assetsDir: "./media" });
try {
const { filePath, chunks } = await renderDistributed(doc, {
format: "mp4",
out: "out/final.mp4",
runner,
onProgress: (p) => console.log(p.phase, p.jobsDone, "/", p.jobsTotal),
});
} finally {
await runner.close?.();
}The machine that calls renderDistributed needs ffmpeg on its PATH (or pass ffmpegPath). Workers don't.
| Option | Default | Meaning |
|---|---|---|
format, out | required | Container and output file |
runner | required | Where chunks render. See below |
quality, fps, width, height, range | as in exportProjectFile | Output settings |
chunks | one per runner slot | Number of video chunks |
minChunkUs | 2_000_000 | Shortest chunk worth a separate job |
ffmpegPath | "ffmpeg" | ffmpeg binary |
signal, onProgress | none | Cancel; progress as { jobsDone, jobsTotal, phase: "render" | "join" } |
keepChunks | false | Keep the chunk files |
The result is { filePath, chunks, hasAudio }.
Runners
| Runner | Runs chunks |
|---|---|
localRunner({ concurrency?, ...sessionOptions }) | On this machine, in a pool of warm browsers (default 2). Takes the same assets, assetsDir, browser and plugins options as createExportSession |
httpRunner({ endpoints, concurrency?, headers?, retries? }) | On HTTP workers you deploy, spread round-robin (default 8 jobs in flight, 2 retries on network errors and 5xx) |
| Your own | Any object with concurrency and run(job, { signal, workDir }) that returns { id, file } or { id, bytes } |
Workers
Each HTTP worker runs createRenderJobHandler: a Fetch API handler that renders one job per request and answers with the encoded chunk.
import { createRenderJobHandler } from "@miraiclip/server-export";
const handler = createRenderJobHandler({
token: process.env.RENDER_TOKEN, // checked against "Authorization: Bearer <token>"
browser: { swiftshader: true },
});
// Mount `handler` in any Node server. Call handler.close() on shutdown.| Option | Default | Meaning |
|---|---|---|
token | none | Reject requests without this bearer token. Set it on every public URL |
maxPixels | 3840 × 2160 | Largest output frame accepted |
assets, assetsDir, browser, plugins | As in createExportSession |
Jobs carry the whole document, so workers are stateless and can scale to zero. Assets must be reachable from the workers: use http(s) URLs (signed URLs work), not local paths. examples/render-worker in the SDK repository is a ready-to-deploy container. Deployments walks through running it with Docker, on AWS and on Google Cloud.
Render cost
pnpm --filter @miraiclip/server-export bench:cost measures CPU-seconds per minute of output for a typical product video (a screen recording with zooms, a cursor, an HTML lower third and karaoke captions) on the machine it runs on. On a 2-vCPU Xeon with software rendering and software encoding:
| Output | CPU-seconds per output minute |
|---|---|
| 1920 × 1080, 30 fps, WebM | about 930 |
| 3840 × 2160, 30 fps, WebM | about 4,400 |
Run it on your own hardware before sizing workers: a GPU or hardware encoder changes these numbers a lot.
CLI
npx miraiclip-export project.json --out final.mp4 --quality high --asset interview=./media/interview.mp4It prints progress to stderr and <file> (<MB> MB, <seconds>s) to stdout. Ctrl-C cancels the export.
| Flag | Default | What it does |
|---|---|---|
<project.json> | required | The project document |
--out <file>, -o <file> | required | Output path |
--format mp4|webm | from the --out extension: .webm → WebM, anything else → MP4 | Container |
--quality draft|standard|high | standard | Quality preset |
--fps <n> | project fps | Output frame rate |
--width <px>, --height <px> | project size | Output size |
--start <s>, --end <s> | whole composition | Range in seconds. Give both or neither |
--asset <id>=<path> | none | Map an asset id to a local file. Repeatable |
--assets-dir <dir> | the project file's folder | Base folder for relative asset paths |
--browser <path> | see The browser | Chrome or Chromium binary |
--quiet | off | No progress output |
The CLI has no --help flag. An unknown flag exits with unknown flag ….