Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): package share renders as an adaptive HLS ladder [rebuild]

David Le44f8983183a8
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prisma
index d1d9f0d7..388ce068 100644
--- a/site/prisma/Cut.prisma
+++ b/site/prisma/Cut.prisma
@@ -137,7 +137,7 @@ model CutRenderJob {
id String @id @default(cuid())
userId String
projectId String?
- kind String // export | preview | import_url
+ kind String // export | preview | hls | import_url
state String @default("queued") // queued | running | done | error | canceled
progress Float @default(0)
spec Json
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index b3f2d344..b9fe3e99 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -12,10 +12,11 @@ import { lookFilterLines } from "../lib/looks";
export interface ExportSpec {
projectId: string;
- /** Where the render lands instead of a stamped file in exports/: "preview"
+ /** Where the render lands instead of a stamped file in exports/: "hls" is the
+ * share's streaming ladder, "preview"
* writes the project's low-res hover proxy, "card" the opening seconds the
* cloud worker derives a shared link's preview image from. */
- target?: "export" | "preview" | "card";
+ target?: "export" | "preview" | "card" | "hls";
width: number;
height: number;
fps: number;
@@ -227,7 +228,7 @@ function regionPx(
* message on a non-zero exit or a missing binary. Shared by the encode pass and
* the rotation-strip remux.
*/
-function runFfmpeg(
+export function runFfmpeg(
job: RenderHandle,
args: string[],
onProgress?: (seconds: number) => void
diff --git a/site/src/cut/server/hlsLadder.test.ts b/site/src/cut/server/hlsLadder.test.ts
new file mode 100644
index 00000000..cef0350d
--- /dev/null
+++ b/site/src/cut/server/hlsLadder.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, test } from "bun:test";
+
+import { HLS_RUNGS, planLadder } from "./hlsLadder";
+
+const shortSideOf = (r: { width: number; height: number }) => Math.min(r.width, r.height);
+
+describe("ladder planning", () => {
+ test("never upscales past the source", () => {
+ for (const [w, h] of [
+ [3840, 2160],
+ [1920, 1080],
+ [1280, 720],
+ [640, 360],
+ [1080, 1920], // portrait
+ [1080, 1080], // square
+ ] as const) {
+ for (const rung of planLadder(w, h)) {
+ expect(rung.width).toBeLessThanOrEqual(w);
+ expect(rung.height).toBeLessThanOrEqual(h);
+ }
+ }
+ });
+
+ test("the top rung is the source itself", () => {
+ const plan = planLadder(1920, 1080);
+ const top = plan[plan.length - 1];
+ expect(shortSideOf(top)).toBe(1080);
+ });
+
+ test("a small source gets exactly one rung", () => {
+ // Below the lowest rung there is nothing to choose between, and a ladder of
+ // one is still a valid stream.
+ const plan = planLadder(426, 240);
+ expect(plan).toHaveLength(1);
+ expect(shortSideOf(plan[0])).toBe(240);
+ });
+
+ test("a 4K source gets the whole ladder", () => {
+ expect(planLadder(3840, 2160)).toHaveLength(HLS_RUNGS.length);
+ });
+
+ test("rungs climb, so the master lists a real range to choose from", () => {
+ const plan = planLadder(3840, 2160);
+ for (let i = 1; i < plan.length; i++) {
+ expect(shortSideOf(plan[i])).toBeGreaterThan(shortSideOf(plan[i - 1]));
+ expect(plan[i].videoKbps).toBeGreaterThan(plan[i - 1].videoKbps);
+ }
+ });
+
+ test("portrait and landscape ladder by the short side", () => {
+ // A phone-shaped cut scaled by height would put its 360p rung at 202px
+ // wide; the rung name has to mean the same thing in both orientations.
+ const landscape = planLadder(1920, 1080);
+ const portrait = planLadder(1080, 1920);
+ expect(portrait.map(shortSideOf)).toEqual(landscape.map(shortSideOf));
+ expect(portrait[0].width).toBe(360);
+ expect(landscape[0].height).toBe(360);
+ });
+
+ test("every dimension is even, which the encoder requires", () => {
+ for (const [w, h] of [
+ [3840, 2160],
+ [1080, 1920],
+ [1440, 1080],
+ [2048, 858], // cinemascope
+ ] as const) {
+ for (const rung of planLadder(w, h)) {
+ expect(rung.width % 2).toBe(0);
+ expect(rung.height % 2).toBe(0);
+ }
+ }
+ });
+
+ test("a wider frame at the same rung is given more bits", () => {
+ // Bitrates are tuned for 16:9; an ultrawide frame carries more pixels at the
+ // same short side and would otherwise be starved at every rung.
+ const wide = planLadder(2560, 1080).find((r) => r.shortSide === 720);
+ const normal = planLadder(1920, 1080).find((r) => r.shortSide === 720);
+ expect(wide!.videoKbps).toBeGreaterThan(normal!.videoKbps);
+ });
+
+ test("aspect ratio survives every rung", () => {
+ for (const [w, h] of [
+ [1920, 1080],
+ [1080, 1920],
+ [2048, 858],
+ ] as const) {
+ for (const rung of planLadder(w, h)) {
+ // Even-rounding moves each side by at most a pixel, so allow for that
+ // rather than demanding the ratio match exactly.
+ expect(Math.abs(rung.width / rung.height - w / h)).toBeLessThan(0.02);
+ }
+ }
+ });
+});
diff --git a/site/src/cut/server/hlsLadder.ts b/site/src/cut/server/hlsLadder.ts
new file mode 100644
index 00000000..510c66fb
--- /dev/null
+++ b/site/src/cut/server/hlsLadder.ts
@@ -0,0 +1,265 @@
+// Packaging a finished render as an HLS ladder.
+//
+// A share plays through HLS rather than the flattened mp4 for two reasons. The
+// edge refuses to cache a single object past 512 MB (worker/cf/media.ts), which
+// a long or 4K cut passes easily — so the one file that most needs the cache is
+// the one that never gets it, while segments of a few megabytes always do. And
+// a ladder is what lets one asset serve a phone on a weak cellular link and a
+// desktop on a 4K panel, which a fixed-bitrate file cannot.
+//
+// The ladder is built FROM the rendered master, not from the timeline. By that
+// point the pixels are already upright, already BT.709 SDR, and already
+// composited, so this stage is a pure transcode and never has to know what a
+// clip is.
+import { spawn } from "node:child_process";
+import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { runFfmpeg, type RenderHandle } from "./exportPipeline";
+import { hasStream, videoDimensions } from "./util";
+
+/** Segment length. Six seconds is the common VOD choice: long enough that
+ * per-segment request overhead stays small on a long cut, short enough that a
+ * player switching rungs commits to only a few seconds of the wrong bitrate. */
+export const HLS_SEGMENT_SECONDS = 6;
+
+/** Audio is encoded per variant rather than as one shared rendition. It costs
+ * this much extra per rung, which buys variants that are each self-contained —
+ * no audio group to mis-associate, and a rung switch that can never desync. */
+const AUDIO_KBPS = 128;
+
+/**
+ * One rung, addressed by the SHORT side so portrait and landscape ladders are
+ * the same ladder. `kbps` is the video bitrate for a 16:9 frame at that short
+ * side; an aspect that carries more pixels scales up from it.
+ */
+export interface Rung {
+ name: string;
+ shortSide: number;
+ kbps: number;
+}
+
+export const HLS_RUNGS: Rung[] = [
+ { name: "360p", shortSide: 360, kbps: 800 },
+ { name: "540p", shortSide: 540, kbps: 1400 },
+ { name: "720p", shortSide: 720, kbps: 2800 },
+ { name: "1080p", shortSide: 1080, kbps: 5000 },
+ { name: "1440p", shortSide: 1440, kbps: 9000 },
+ { name: "2160p", shortSide: 2160, kbps: 18000 },
+];
+
+/** Rungs published in the first pass. The share becomes watchable once these
+ * land, so they are the ones a phone would pick anyway. */
+export const FIRST_PASS_RUNGS = 3;
+
+export interface PlannedRung extends Rung {
+ width: number;
+ height: number;
+ /** Video bitrate after scaling `kbps` for this frame's pixel count. */
+ videoKbps: number;
+}
+
+const even = (n: number) => Math.max(2, 2 * Math.round(n / 2));
+
+/**
+ * The rungs worth building for a source of this size: every rung below the
+ * source's short side, plus one capped AT the source. Upscaling is never
+ * useful — it spends encode time and storage to add no detail — so the top rung
+ * is the source itself.
+ */
+export function planLadder(width: number, height: number): PlannedRung[] {
+ const sourceShort = Math.min(width, height);
+ const aspect = width / height;
+ const plan: PlannedRung[] = [];
+ for (const rung of HLS_RUNGS) {
+ const capped = Math.min(rung.shortSide, sourceShort);
+ const portrait = height > width;
+ const w = even(portrait ? capped : capped * aspect);
+ const h = even(portrait ? capped / aspect : capped);
+ // `kbps` is tuned for 16:9, whose pixel count at a given short side is the
+ // same in both orientations. A squarer or wider frame at that short side
+ // carries a different pixel count and needs proportionally different bits.
+ const reference = ((capped * capped) * 16) / 9;
+ const videoKbps = Math.round(rung.kbps * Math.min(2.5, Math.max(0.5, (w * h) / reference)));
+ plan.push({ ...rung, width: w, height: h, videoKbps });
+ if (capped >= sourceShort) break;
+ }
+ return plan;
+}
+
+/** `#EXT-X-STREAM-INF` line plus the variant path it introduces. */
+export interface Variant {
+ inf: string;
+ uri: string;
+}
+
+/** Pull the variant entries out of a master playlist ffmpeg wrote, so passes
+ * that ran separately can be merged into one master. */
+function parseVariants(master: string): Variant[] {
+ const lines = master.split("\n").map((l) => l.trim());
+ const out: Variant[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (!lines[i].startsWith("#EXT-X-STREAM-INF")) continue;
+ const uri = lines[i + 1];
+ if (uri && !uri.startsWith("#")) out.push({ inf: lines[i], uri });
+ }
+ return out;
+}
+
+/** A master playlist listing `variants`, ordered lowest bitrate first so a
+ * player with no measurement yet starts on the rung most likely to play. */
+function masterPlaylist(variants: Variant[]): string {
+ const bandwidth = (v: Variant) => Number(/BANDWIDTH=(\d+)/.exec(v.inf)?.[1] ?? 0);
+ const ordered = [...variants].sort((a, b) => bandwidth(a) - bandwidth(b));
+ return ["#EXTM3U", "#EXT-X-VERSION:3", ...ordered.flatMap((v) => [v.inf, v.uri]), ""].join("\n");
+}
+
+/**
+ * Encode `rungs` out of `source` into `outDir`, in ONE ffmpeg run.
+ *
+ * The single run is the point: the graph decodes the source once and splits it
+ * to every rung. Running ffmpeg per rung would re-decode the whole file each
+ * time, which on a 4K master is most of the cost of the job and would saturate
+ * a render pool that only has four slots.
+ */
+export async function encodeRungs(
+ handle: RenderHandle,
+ source: string,
+ outDir: string,
+ rungs: PlannedRung[],
+ duration: number,
+ onProgress?: (fraction: number) => void
+): Promise<Variant[]> {
+ await Promise.all(rungs.map((r) => mkdir(path.join(outDir, r.name), { recursive: true })));
+ const withAudio = await hasStream(source, "a");
+
+ const split = `[0:v]split=${rungs.length}${rungs.map((_, i) => `[s${i}]`).join("")}`;
+ const scales = rungs.map(
+ (r, i) => `[s${i}]scale=${r.width}:${r.height}:flags=lanczos[o${i}]`
+ );
+
+ const maps: string[] = [];
+ for (let i = 0; i < rungs.length; i++) maps.push("-map", `[o${i}]`);
+ if (withAudio) for (let i = 0; i < rungs.length; i++) maps.push("-map", "0:a:0");
+
+ const codecArgs: string[] = [];
+ rungs.forEach((r, i) => {
+ codecArgs.push(
+ `-c:v:${i}`, "libx264",
+ `-preset:v:${i}`, "veryfast",
+ `-profile:v:${i}`, "high",
+ `-b:v:${i}`, `${r.videoKbps}k`,
+ // A ceiling and a matching buffer are what make the rung honest: without
+ // them a complex passage overshoots the bitrate the master advertises and
+ // the player that chose this rung on that number stalls.
+ `-maxrate:v:${i}`, `${Math.round(r.videoKbps * 1.07)}k`,
+ `-bufsize:v:${i}`, `${Math.round(r.videoKbps * 1.5)}k`,
+ // Every rung must cut at the same instants or a player cannot switch
+ // between them. Forcing IDR frames on the segment grid guarantees it
+ // regardless of frame rate; disabling scene-cut keeps x264 from adding
+ // keyframes that would let the muxer split somewhere else.
+ `-force_key_frames:v:${i}`, `expr:gte(t,n_forced*${HLS_SEGMENT_SECONDS})`,
+ `-x264-params:v:${i}`, "scenecut=0"
+ );
+ });
+
+ const streamMap = rungs
+ .map((r, i) => (withAudio ? `v:${i},a:${i},name:${r.name}` : `v:${i},name:${r.name}`))
+ .join(" ");
+
+ await runFfmpeg(
+ handle,
+ [
+ "-y",
+ "-i", source,
+ "-filter_complex", [split, ...scales].join(";"),
+ ...maps,
+ ...codecArgs,
+ ...(withAudio ? ["-c:a", "aac", "-b:a", `${AUDIO_KBPS}k`, "-ac", "2"] : []),
+ "-pix_fmt", "yuv420p",
+ "-f", "hls",
+ "-hls_time", String(HLS_SEGMENT_SECONDS),
+ "-hls_playlist_type", "vod",
+ // Declares that every segment can be decoded without the one before it,
+ // which is what lets a player join or switch rungs at any segment.
+ "-hls_flags", "independent_segments",
+ "-hls_segment_filename", path.join(outDir, "%v", "seg%05d.ts"),
+ "-master_pl_name", "master.m3u8",
+ "-var_stream_map", streamMap,
+ path.join(outDir, "%v", "index.m3u8"),
+ ],
+ duration > 0 && onProgress
+ ? (t) => onProgress(Math.min(1, t / Math.max(0.1, duration)))
+ : undefined
+ );
+
+ // ffmpeg writes the master beside the variant dirs, naming each variant by
+ // the same %v it used for the directory.
+ const written = await readFile(path.join(outDir, "master.m3u8"), "utf8").catch(() => "");
+ const variants = parseVariants(written);
+ return variants.length > 0
+ ? variants
+ : // A build of ffmpeg that declined to write a master still produced usable
+ // variants; describe them from the plan rather than losing the pass.
+ rungs.map((r) => ({
+ inf: `#EXT-X-STREAM-INF:BANDWIDTH=${(r.videoKbps + AUDIO_KBPS) * 1000},RESOLUTION=${r.width}x${r.height}`,
+ uri: `${r.name}/index.m3u8`,
+ }));
+}
+
+/** Write the merged master covering every variant published so far. */
+export async function writeMaster(outDir: string, variants: Variant[]): Promise<void> {
+ await writeFile(path.join(outDir, "master.m3u8"), masterPlaylist(variants), "utf8");
+}
+
+/** Every file under `dir`, relative to it — what the upload step walks. */
+export async function listFiles(dir: string, base = ""): Promise<string[]> {
+ const entries = await readdir(path.join(dir, base), { withFileTypes: true });
+ const out: string[] = [];
+ for (const e of entries) {
+ const rel = base ? path.join(base, e.name) : e.name;
+ if (e.isDirectory()) out.push(...(await listFiles(dir, rel)));
+ else out.push(rel);
+ }
+ return out;
+}
+
+/** Source geometry and duration for a rendered master, with sane fallbacks so a
+ * failed probe still produces a usable single-rung ladder. */
+export async function probeSource(
+ file: string
+): Promise<{ width: number; height: number; duration: number }> {
+ const dims = await videoDimensions(file);
+ return {
+ width: dims?.width ?? 1920,
+ height: dims?.height ?? 1080,
+ duration: await mediaDuration(file),
+ };
+}
+
+/** Duration in seconds via ffprobe; 0 when unknown. */
+function mediaDuration(file: string): Promise<number> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "csv=p=0",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve(0);
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", () => {
+ clearTimeout(timer);
+ const seconds = Number(out.trim());
+ resolve(Number.isFinite(seconds) && seconds > 0 ? seconds : 0);
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve(0);
+ });
+ });
+}
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index ee9b5c87..0c37e9b7 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -124,6 +124,57 @@ export function videoColorInfo(
});
}
+/**
+ * The first video stream's coded size, or null when the probe fails or the file
+ * has no video. Reported in display orientation: ffprobe gives coded dimensions,
+ * so a phone portrait clip tagged with a 90° display matrix reads back as
+ * landscape, and the rotation is applied here rather than left to each caller.
+ */
+export function videoDimensions(
+ file: string
+): Promise<{ width: number; height: number } | null> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-select_streams", "v:0",
+ "-show_entries", "stream=width,height:stream_side_data=rotation",
+ "-of", "json",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve(null);
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", (code) => {
+ clearTimeout(timer);
+ if (code !== 0) return resolve(null);
+ try {
+ const s = JSON.parse(out).streams?.[0];
+ const width = Number(s?.width);
+ const height = Number(s?.height);
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return resolve(null);
+ }
+ const rotation = Number(
+ (s?.side_data_list ?? []).find((d: { rotation?: unknown }) => d?.rotation != null)
+ ?.rotation ?? 0
+ );
+ const quarterTurned = Math.abs(rotation) % 180 === 90;
+ resolve(quarterTurned ? { width: height, height: width } : { width, height });
+ } catch {
+ resolve(null);
+ }
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve(null);
+ });
+ });
+}
+
/**
* Whether a media file carries a stream of the given kind ("a" audio /
* "v" video). Resolves false only when ffprobe reports no such stream; a
diff --git a/site/src/cut/worker/Dockerfile b/site/src/cut/worker/Dockerfile
index a0c6f07a..84c4cb00 100644
--- a/site/src/cut/worker/Dockerfile
+++ b/site/src/cut/worker/Dockerfile
@@ -23,6 +23,12 @@ RUN apt-get update \
RUN ffmpeg -hide_banner -h full 2>&1 | grep -q -- '-display_rotation' \
|| { echo "ffmpeg is too old: the export re-mux needs -display_rotation (6.0+)." >&2; exit 1; }
+# The share ladder encodes every rung with libx264 and tunes it through
+# -x264-params. A build without it (an LGPL ffmpeg) would fail per rung at
+# encode time, so it fails here instead.
+RUN ffmpeg -hide_banner -encoders 2>&1 | grep -q '\blibx264\b' \
+ || { echo "ffmpeg has no libx264: the share HLS ladder cannot encode." >&2; exit 1; }
+
WORKDIR /app
COPY dist/cut-worker/main.js ./main.js
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index 5941876d..9b2b9d9f 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -10,9 +10,14 @@ import { downloadToFile, exportKey, mediaKey, previewKey, uploadFile } from "./r
* plus the R2 keys of the browser-rendered overlay PNGs (title/caption stills
* and sub_blank.png). The queueing route (cloud/jobs.ts) stores exactly this
* and puts the already-deduped export name on the row's outName column. */
-interface ExportJobSpec {
+export interface ExportJobSpec {
spec: ExportSpec;
overlays?: { name: string; key: string }[];
+ /** HLS only: whether the client burned captions into this render, decided by
+ * what the share grants. Recorded on the ladder so a share that later stops
+ * granting Subtitles is refused the render rather than served cue text it
+ * cannot strip out of the pixels. */
+ burnedSubtitles?: boolean;
}
/** The job's overlay-PNG R2 keys, restricted to the job owner's own overlay
@@ -32,7 +37,7 @@ export function overlayKeysOf(job: ClaimedJob): string[] {
* on purpose: inside the run, a `return somePromise` would hand back work that
* still needs those files while the `finally` deleted them out from under it.
*/
-async function inWorkDir<T>(render: (work: string) => Promise<T>): Promise<T> {
+export async function inWorkDir<T>(render: (work: string) => Promise<T>): Promise<T> {
const work = await mkdtemp(path.join(os.tmpdir(), "cut-worker-"));
try {
return await render(work);
@@ -41,6 +46,52 @@ async function inWorkDir<T>(render: (work: string) => Promise<T>): Promise<T> {
}
}
+/**
+ * Pull everything the render reads into a project-shaped work dir: the clips,
+ * overlay videos and audio the spec names, plus the browser-rendered overlay
+ * PNGs. Returns the media dir the pipeline resolves file names against.
+ *
+ * Shared by every job that runs the export pipeline — the mp4 renders here and
+ * the HLS ladder in hlsJob.ts — so they cannot drift on what a staged project
+ * looks like.
+ */
+export async function stageJobMedia(
+ job: ClaimedJob,
+ body: ExportJobSpec,
+ projectId: string,
+ work: string,
+ handle: RenderHandle
+): Promise<string> {
+ // The pipeline reads overlay/caption PNGs from handle.tmpDir by base name
+ // and writes its encode intermediate there too — mirror the engine's
+ // uploaded-PNG staging.
+ handle.tmpDir = path.join(work, "overlays");
+ const mediaDir = path.join(work, "media");
+ await Promise.all([
+ mkdir(handle.tmpDir, { recursive: true }),
+ mkdir(mediaDir, { recursive: true }),
+ ]);
+
+ const spec = body.spec;
+ const mediaFiles = new Set<string>();
+ for (const c of spec.clips) if (c.file) mediaFiles.add(c.file);
+ for (const o of spec.overlayVideos ?? []) if (o.file) mediaFiles.add(o.file);
+ for (const a of spec.audio ?? []) if (a.file) mediaFiles.add(a.file);
+ const overlayPrefix = `cut/${job.userId}/overlays/`;
+ for (const o of body.overlays ?? []) {
+ if (!o.key.startsWith(overlayPrefix)) throw new Error("Invalid overlay key.");
+ }
+ await Promise.all([
+ ...[...mediaFiles].map((f) =>
+ downloadToFile(mediaKey(job.userId, projectId, f), path.join(mediaDir, path.basename(f)))
+ ),
+ ...(body.overlays ?? []).map((o) =>
+ downloadToFile(o.key, path.join(handle.tmpDir, path.basename(o.name)))
+ ),
+ ]);
+ return mediaDir;
+}
+
/**
* Run one export, preview, or card job: stage a project-shaped work dir
* (media/ + overlay PNGs in the pipeline tmp dir), render through the engine's
@@ -66,29 +117,7 @@ export async function runExportJob(
const preview = mode === "preview";
return inWorkDir(async (work) => {
- // The pipeline reads overlay/caption PNGs from handle.tmpDir by base name
- // and writes its encode intermediate there too — mirror the engine's
- // uploaded-PNG staging.
- handle.tmpDir = path.join(work, "overlays");
- const mediaDir = path.join(work, "media");
- await Promise.all([mkdir(handle.tmpDir, { recursive: true }), mkdir(mediaDir, { recursive: true })]);
-
- const mediaFiles = new Set<string>();
- for (const c of spec.clips) if (c.file) mediaFiles.add(c.file);
- for (const o of spec.overlayVideos ?? []) if (o.file) mediaFiles.add(o.file);
- for (const a of spec.audio ?? []) if (a.file) mediaFiles.add(a.file);
- const overlayPrefix = `cut/${job.userId}/overlays/`;
- for (const o of body.overlays ?? []) {
- if (!o.key.startsWith(overlayPrefix)) throw new Error("Invalid overlay key.");
- }
- await Promise.all([
- ...[...mediaFiles].map((f) =>
- downloadToFile(mediaKey(job.userId, projectId, f), path.join(mediaDir, path.basename(f)))
- ),
- ...(body.overlays ?? []).map((o) =>
- downloadToFile(o.key, path.join(handle.tmpDir, path.basename(o.name)))
- ),
- ]);
+ const mediaDir = await stageJobMedia(job, body, projectId, work, handle);
const outName = mode === "export" ? job.outName?.trim() || "export.mp4" : `${mode}.mp4`;
handle.outPath = path.join(work, "out", outName);
diff --git a/site/src/cut/worker/hlsJob.ts b/site/src/cut/worker/hlsJob.ts
new file mode 100644
index 00000000..42c2f6d8
--- /dev/null
+++ b/site/src/cut/worker/hlsJob.ts
@@ -0,0 +1,151 @@
+// The share-playback job: render the cut, then package it as an HLS ladder in
+// R2 so a shared project streams instead of downloading.
+//
+// It renders its own master rather than reusing an export. An export is
+// whatever settings the user picked and may not exist at all; the ladder has to
+// track the CURRENT doc, since that is what the share serves.
+//
+// The ladder publishes in two passes. The low rungs go up first and the master
+// is written the moment they land, so a share becomes watchable in a fraction
+// of the total encode; the high rungs follow and the master is rewritten to
+// include them. Without that split a 4K cut would be unwatchable until the
+// slowest rung finished.
+import path from "node:path";
+import { mkdir } from "node:fs/promises";
+import {
+ FIRST_PASS_RUNGS,
+ encodeRungs,
+ listFiles,
+ planLadder,
+ probeSource,
+ writeMaster,
+ type Variant,
+} from "../server/hlsLadder";
+import type { RenderHandle } from "../server/exportPipeline";
+import { runExport } from "../server/exportPipeline";
+import { beginLadder, publishLadder } from "../server/cloud/ladderStore";
+import { inWorkDir, stageJobMedia, type ExportJobSpec } from "./exportJob";
+import { prisma, type ClaimedJob } from "./db";
+import { hlsPrefix, uploadTree } from "./r2";
+
+/** Progress split between rendering the master and packaging the ladder. The
+ * ladder is the longer half on a large frame — it encodes the whole cut once
+ * per rung — so the render is not allowed to look like most of the job. */
+const RENDER_SHARE = 0.35;
+
+/** Abort if the row stopped being ours: a project deleted or a share revoked
+ * mid-render cancels its jobs, and uploading after that charges storage nothing
+ * will ever free. */
+async function stillRunning(jobId: string): Promise<boolean> {
+ const live = await prisma.cutRenderJob.findUnique({
+ where: { id: jobId },
+ select: { state: true },
+ });
+ return live?.state === "running";
+}
+
+export async function runHlsJob(
+ job: ClaimedJob,
+ handle: RenderHandle
+): Promise<{ outputKey: string; outName: string }> {
+ const body = job.spec as ExportJobSpec;
+ const spec = body?.spec;
+ if (!spec || !Array.isArray(spec.clips)) throw new Error("Malformed HLS spec.");
+ const projectId = job.projectId ?? spec.projectId;
+ if (!projectId) throw new Error("HLS job has no project.");
+
+ return inWorkDir(async (work) => {
+ const mediaDir = await stageJobMedia(job, body, projectId, work, handle);
+
+ // Render the master at the doc's own frame size: the ladder caps its top
+ // rung at the source, so anything lost here is lost for every viewer.
+ handle.outPath = path.join(work, "out", "master.mp4");
+ await mkdir(path.dirname(handle.outPath), { recursive: true });
+ await runExport(handle, spec, (file) => path.join(mediaDir, path.basename(file)));
+ handle.progress = RENDER_SHARE;
+
+ if (!(await stillRunning(job.id))) throw new Error("Canceled.");
+
+ const source = await probeSource(handle.outPath);
+ const ladder = planLadder(source.width, source.height);
+ const outDir = path.join(work, "hls");
+ await mkdir(outDir, { recursive: true });
+
+ // A fresh tree per render: the version is a path segment, so viewers on the
+ // old ladder keep playing from the edge cache while this one is written,
+ // and neither can serve the other's segments.
+ const version = `v${Date.now().toString(36)}`;
+ const prefix = hlsPrefix(job.userId, projectId, version);
+
+ // Claimed BEFORE any upload. The record is the only index of ladder trees,
+ // so a version that started uploading without being named there would be
+ // invisible to every sweep if this job then died — a whole cut's worth of
+ // segments leaking with nothing left that could find them.
+ await beginLadder(projectId, job.userId, version);
+
+ const published: Variant[] = [];
+ let bytes = 0;
+ const passes = [ladder.slice(0, FIRST_PASS_RUNGS), ladder.slice(FIRST_PASS_RUNGS)].filter(
+ (rungs) => rungs.length > 0
+ );
+
+ for (const [index, rungs] of passes.entries()) {
+ // Shares of the encode budget, over the passes that actually exist: a
+ // small source plans one pass, and dividing by a fixed two would leave
+ // its progress stuck at the halfway mark.
+ const base = RENDER_SHARE + (1 - RENDER_SHARE) * (index / passes.length);
+ const span = (1 - RENDER_SHARE) / passes.length;
+ const before = new Set(await listFiles(outDir).catch(() => []));
+
+ const added = await encodeRungs(
+ handle,
+ handle.outPath,
+ outDir,
+ rungs,
+ source.duration,
+ (f) => {
+ handle.progress = Math.min(0.99, base + span * f);
+ }
+ );
+ if (!(await stillRunning(job.id))) throw new Error("Canceled.");
+
+ // Upload only what this pass produced, then republish the master. The
+ // master goes last on purpose: it is the file that makes segments
+ // reachable, so it must never name a rung whose bytes are not up yet.
+ const all = await listFiles(outDir);
+ const fresh = all.filter((f) => !before.has(f) && path.basename(f) !== "master.m3u8");
+ bytes += await uploadTree(outDir, prefix, fresh);
+
+ // encodeRungs leaves behind a master describing only its own pass; the
+ // merged one replaces it so every rung published so far stays listed.
+ const known = new Set(published.map((v) => v.uri));
+ published.push(...added.filter((v) => !known.has(v.uri)));
+ await writeMaster(outDir, published);
+ bytes += await uploadTree(outDir, prefix, ["master.m3u8"]);
+
+ // Publishing after the first pass is what makes the share playable early;
+ // republishing after the last keeps the record's duration and burn-in
+ // flag describing the finished ladder. Unguarded: a ladder nothing can
+ // point at is not a partial success, so a failed write fails the job and
+ // the row carries the reason.
+ await publishLadder(projectId, job.userId, {
+ version,
+ duration: source.duration,
+ // What the render actually burned in, decided by the client from the
+ // share's own grants. Recorded because captions in the pixels cannot be
+ // stripped later — the server has to refuse the whole ladder instead.
+ burnedSubtitles: body.burnedSubtitles === true,
+ });
+ }
+
+ // No media row, and so no storage quota: a ladder is a delivery format the
+ // product chose, not media the user put anywhere. They already pay for the
+ // footage it was rendered from, and a share re-rendering would otherwise
+ // charge them again for the same cut. It follows the same rule as the other
+ // untracked bytes in this bucket (r2.ts's inference scratch): found by
+ // prefix, swept by prefix, never counted.
+ console.log(`[cut-worker] hls ${job.id} published ${prefix} (${bytes} bytes, untracked)`);
+
+ return { outputKey: `${prefix}/master.m3u8`, outName: "master.m3u8" };
+ });
+}
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 999560e9..103516bc 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -2,6 +2,7 @@ import type { Prisma } from "@/generated/prisma/client";
import type { RenderHandle } from "../server/exportPipeline";
import { prisma, type ClaimedJob } from "./db";
import { overlayKeysOf, runExportJob } from "./exportJob";
+import { runHlsJob } from "./hlsJob";
import { runImportUrlJob } from "./importUrlJob";
import { deleteObjects } from "./r2";
@@ -146,6 +147,12 @@ async function runJob(job: ClaimedJob): Promise<void> {
where: { id: job.id, state: "running" },
data: { state: "done", progress: 1, outputKey, outName },
});
+ } else if (job.kind === "hls") {
+ const { outputKey, outName } = await runHlsJob(job, handle);
+ await prisma.cutRenderJob.updateMany({
+ where: { id: job.id, state: "running" },
+ data: { state: "done", progress: 1, outputKey, outName },
+ });
} else if (job.kind === "import_url") {
const result = await runImportUrlJob(job, () => entry.canceled);
await prisma.cutRenderJob.updateMany({
diff --git a/site/src/cut/worker/r2.ts b/site/src/cut/worker/r2.ts
index a85e036b..f172d78e 100644
--- a/site/src/cut/worker/r2.ts
+++ b/site/src/cut/worker/r2.ts
@@ -17,6 +17,8 @@ import {
export {
projectCardKey as cardKey,
projectExportKey as exportKey,
+ projectHlsPrefix as hlsPrefix,
+ projectHlsRoot as hlsRoot,
projectMediaKey as mediaKey,
projectPreviewKey as previewKey,
} from "../server/cloud/r2";
@@ -79,6 +81,31 @@ export async function uploadFile(key: string, file: string, contentType: string)
return info.size;
}
+/** Upload `files` (paths relative to `dir`) under `keyPrefix`, a few at a time.
+ * Returns the total bytes written. An HLS ladder is hundreds of small objects,
+ * so this bounds concurrency rather than opening one request per segment. */
+export async function uploadTree(
+ dir: string,
+ keyPrefix: string,
+ files: string[],
+ concurrency = 8
+): Promise<number> {
+ let total = 0;
+ let next = 0;
+ const workers = Array.from({ length: Math.min(concurrency, files.length) }, async () => {
+ for (let i = next++; i < files.length; i = next++) {
+ const rel = files[i];
+ total += await uploadFile(
+ `${keyPrefix}/${rel.split(path.sep).join("/")}`,
+ path.join(dir, rel),
+ mimeFor(rel)
+ );
+ }
+ });
+ await Promise.all(workers);
+ return total;
+}
+
const MIME_BY_EXT: Record<string, string> = {
".mp4": "video/mp4",
".mov": "video/quicktime",
@@ -98,6 +125,11 @@ const MIME_BY_EXT: Record<string, string> = {
".gif": "image/gif",
".avif": "image/avif",
".bmp": "image/bmp",
+ // HLS. The playlist type matters to players; a wrong one makes Safari refuse
+ // the stream outright rather than degrade.
+ ".m3u8": "application/vnd.apple.mpegurl",
+ ".ts": "video/mp2t",
+ ".m4s": "video/iso.segment",
};
export function mimeFor(fileName: string): string {