Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(render-farm): export into a recording's folder with GPU source transcodes and signed callbacks

Richie McIlroy79e6fa69040b
diff --git a/apps/render-farm/README.md b/apps/render-farm/README.md
index 5b86cd977..bfcd34644 100644
--- a/apps/render-farm/README.md
+++ b/apps/render-farm/README.md
@@ -74,6 +74,10 @@ expires `hls/` and `jobs/` objects.
| `RF_TOKEN` | required | Bearer token between clients, coordinator and workers |
| `RF_S3_ENDPOINT`, `RF_S3_BUCKET`, `RF_S3_REGION` | required | Bucket holding recordings, outputs, HLS and the journal |
| `RF_S3_IMDS` | off | Use the instance role instead of `RF_S3_ACCESS_KEY_ID`/`RF_S3_SECRET_ACCESS_KEY` |
+| `RF_MEDIA_S3_BUCKET` (`_REGION`, `_ENDPOINT`) | the `RF_S3_*` bucket | Bucket holding recordings and receiving exports; may belong to another account whose policy grants the farm's role. Objects are written `bucket-owner-full-control`; the journal stays in `RF_S3_BUCKET` |
+| `RF_CALLBACK_HOSTS` | none | Host suffixes a job's `callbackUrl` may use (e.g. `vercel.app,cap.so`) |
+| `RF_CALLBACK_SECRET` | `RF_TOKEN` | HMAC key for callback signatures |
+| `RF_TRANSCODE_ENCODER` | `h264_nvenc` | Encoder for source transcodes (`libx264` without a GPU) |
| `RF_COORDINATOR_URL` | `http://127.0.0.1:8080` | Coordinator address (workers) and its advertised URL |
| `RF_SLOTS` / `RF_AUDIO_SLOTS` | `5` / `4` | Render slots and audio lanes per worker (tuned on one L4 with 8 vCPUs) |
| `RF_LOCAL_AUDIO_SLOTS` | `2` | Audio lanes on the coordinator |
@@ -92,6 +96,27 @@ expires `hls/` and `jobs/` objects.
| `CAP_DECODER_READAHEAD` | `8` | Frames each decoder decodes ahead of the renderer |
| `RF_HOT_SWAP` | off | Development: pull the engine, app and tuning from the bucket's `bin/` pointers |
+## Product integration
+
+A job can export a recording that lives in the product's bucket:
+
+- `sourceRoot` names the recording's folder (e.g. `<owner>/<video>/`); manifest
+ keys may point anywhere inside it, so a small render project (manifest,
+ project config, cursors) can sit beside the untouched source files.
+- `output: { key, hlsPrefix }` places the MP4 and HLS segments inside that
+ folder instead of `out/` and `hls/`.
+- `callbackUrl` receives the job's outcome once it is ready or failed, signed
+ `x-render-farm-signature: sha256=<hex HMAC of the body>`. `GET /jobs/:id`
+ reports `progress` (0-1), `hlsSegments` and a freshly signed `hlsUrl`.
+
+Browser recordings are WebM with no seek index and few keyframes, so chunks
+cannot start in the middle of them. A manifest entry with `transcodeFrom`
+names such a source; the coordinator first has a GPU slot re-encode it into
+the entry's `key` as H.264 with a keyframe every second (kept and reused for
+later exports). `POST /transcodes {sourceRoot, source, output}` starts one
+ahead of time (e.g. when the editor opens) and `GET /transcodes/:id` reports
+it.
+
## Development
```sh
diff --git a/apps/render-farm/src/coordinator.test.ts b/apps/render-farm/src/coordinator.test.ts
index 848945bef..f0e77c726 100644
--- a/apps/render-farm/src/coordinator.test.ts
+++ b/apps/render-farm/src/coordinator.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, test } from "bun:test";
-import { randomUUID, timingSafeEqual } from "node:crypto";
+import {
+ createHash,
+ createHmac,
+ randomUUID,
+ timingSafeEqual,
+} from "node:crypto";
import { readFileSync } from "node:fs";
import type { Job, TaskState } from "./coordinator";
import * as fmp4 from "./fmp4";
@@ -18,7 +23,12 @@ function harness() {
const watchdogs: (() => void)[] = [];
let putGate: Promise<void> | undefined;
let failures = 0;
+ const callbacks: { url: string; init: RequestInit }[] = [];
const s3 = {
+ async head(key: string) {
+ const value = objects.get(key);
+ return value ? { size: value.byteLength } : null;
+ },
async put(key: string, body: Uint8Array | string) {
writes.push(key);
await putGate;
@@ -53,6 +63,8 @@ function harness() {
const deps = {
timingSafeEqual,
randomUUID,
+ createHash,
+ createHmac,
...validate,
...fmp4,
...hls,
@@ -67,10 +79,16 @@ function harness() {
}
},
s3ConfigFromEnv: () => ({}),
+ mediaS3ConfigFromEnv: () => ({}),
ProbeEngine: class {},
Engine: class {},
process: {
- env: { RF_TOKEN: "test", RF_LOCAL_AUDIO_SLOTS: "0", RF_HLS: "1" },
+ env: {
+ RF_TOKEN: "test",
+ RF_LOCAL_AUDIO_SLOTS: "0",
+ RF_HLS: "1",
+ RF_CALLBACK_HOSTS: "cap.test",
+ },
},
Bun: {
serve: (options: { fetch: typeof fetchHandler }) => {
@@ -85,6 +103,10 @@ function harness() {
return { unref() {} };
},
clearTimeout: () => {},
+ fetch: async (url: string, init: RequestInit) => {
+ callbacks.push({ url, init });
+ return new Response("ok");
+ },
console: { log() {}, warn() {}, error() {} },
mkdirSync: () => {},
rmSync: () => {},
@@ -122,6 +144,7 @@ function harness() {
...coordinator,
objects,
writes,
+ callbacks,
timers,
watchdogs,
fetch: (request: Request) => fetchHandler(request),
@@ -521,3 +544,173 @@ test("job acknowledgement waits for a planning receipt and receipt-only jobs res
expect(planned).toEqual([receipt.id, receipt.id]);
expect(h.jobs.get(receipt.id)?.status).toBe("planning");
});
+
+function call(
+ h: ReturnType<typeof harness>,
+ path: string,
+ body?: Record<string, unknown>,
+) {
+ return h.fetch(
+ new Request(`http://test${path}`, {
+ method: body ? "POST" : "GET",
+ headers: {
+ authorization: "Bearer test",
+ "content-type": "application/json",
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ }),
+ );
+}
+
+describe("transcodes", () => {
+ const request = {
+ sourceRoot: "owner/video/",
+ source: "owner/video/raw-upload.webm",
+ output: "owner/video/.recording/render/sources/display.mp4",
+ };
+
+ test("are queued once, go to a video slot first and settle on the worker's report", async () => {
+ const h = harness();
+ const created = (await (await call(h, "/transcodes", request)).json()) as {
+ id: string;
+ status: string;
+ };
+ expect(created.status).toBe("queued");
+ const again = (await (await call(h, "/transcodes", request)).json()) as {
+ id: string;
+ };
+ expect(again.id).toBe(created.id);
+ const work = (await (
+ await call(h, "/work", {
+ worker: "gpu-a",
+ slots: 1,
+ cpus: 8,
+ kinds: ["video"],
+ })
+ ).json()) as { task: protocol.TranscodeTask };
+ expect(work.task).toMatchObject({
+ kind: "transcode",
+ source: request.source,
+ output: request.output,
+ attempt: 1,
+ });
+ const heartbeat = (await (
+ await call(h, "/heartbeat", {
+ worker: "gpu-b",
+ slots: 1,
+ cpus: 8,
+ running: [
+ {
+ taskId: work.task.taskId,
+ attempt: 1,
+ frames: 3,
+ total: 0,
+ elapsedMs: 10,
+ },
+ ],
+ })
+ ).json()) as { cancel: string[] };
+ expect(heartbeat.cancel).toContain(work.task.taskId);
+ await call(h, `/transcodes/${created.id}/done`, {
+ worker: "gpu-a",
+ attempt: 1,
+ size: 1234,
+ });
+ expect(
+ await (await call(h, `/transcodes/${created.id}`)).json(),
+ ).toMatchObject({ status: "ready", size: 1234 });
+ });
+
+ test("reuse an output already in the bucket", async () => {
+ const h = harness();
+ h.objects.set(request.output, new Uint8Array(42));
+ expect(await (await call(h, "/transcodes", request)).json()).toMatchObject({
+ status: "ready",
+ size: 42,
+ });
+ });
+
+ test("must stay inside their source folder", async () => {
+ const h = harness();
+ for (const body of [
+ { ...request, source: "other/raw-upload.webm" },
+ { ...request, output: "owner/other/display.mp4" },
+ { ...request, output: "owner/video/display.webm" },
+ { ...request, sourceRoot: "owner/../" },
+ ]) {
+ expect((await call(h, "/transcodes", body)).status).toBe(400);
+ }
+ });
+});
+
+describe("jobs for the product", () => {
+ test("write to the requested keys and call back signed when finished", async () => {
+ const h = harness();
+ h.setPlanner(async () => {});
+ const receipt = (await (
+ await call(h, "/jobs", {
+ recording: "owner/video/.recording/render/abc/project",
+ sourceRoot: "owner/video/",
+ output: {
+ key: "owner/video/.recording/render/abc/result.mp4",
+ hlsPrefix: "owner/video/.recording/render/abc/hls",
+ },
+ callbackUrl: "https://preview.cap.test/api/render-farm/callback",
+ reference: "video-1",
+ })
+ ).json()) as { id: string };
+ const exported = h.jobs.get(receipt.id) as Job;
+ expect(exported.key).toBe("owner/video/.recording/render/abc/result.mp4");
+ expect(exported.hls?.prefix).toBe("owner/video/.recording/render/abc/hls");
+ exported.status = "ready";
+ exported.totalFrames = 60;
+ h.finish(exported);
+ const callback = h.callbacks[0];
+ expect(callback?.url).toBe(
+ "https://preview.cap.test/api/render-farm/callback",
+ );
+ const body = String(callback?.init.body);
+ expect(JSON.parse(body)).toMatchObject({
+ id: receipt.id,
+ reference: "video-1",
+ status: "ready",
+ key: "owner/video/.recording/render/abc/result.mp4",
+ durationSeconds: 2,
+ });
+ expect(
+ (callback?.init.headers as Record<string, string>)[
+ "x-render-farm-signature"
+ ],
+ ).toBe(`sha256=${createHmac("sha256", "test").update(body).digest("hex")}`);
+ });
+
+ test("refuse callbacks to hosts that are not allowed", async () => {
+ const h = harness();
+ h.setPlanner(async () => {});
+ const response = await call(h, "/jobs", {
+ recording: "recording",
+ callbackUrl: "https://attacker.example/hook",
+ });
+ expect(response.status).toBe(400);
+ });
+
+ test("report the share of frames rendered", async () => {
+ const h = harness();
+ const j = job();
+ h.jobs.set(j.id, j);
+ j.videoResults.set(0, {} as protocol.VideoResult);
+ const running = videoState(j);
+ running.task = { ...running.task, chunk: 1 } as protocol.VideoTask;
+ running.progress = {
+ frames: 15,
+ total: 30,
+ elapsedMs: 100,
+ at: 0,
+ advancedAt: 0,
+ };
+ const summary = (await (await call(h, `/jobs/${j.id}`)).json()) as {
+ progress: number;
+ };
+ expect(summary.progress).toBe(0.75);
+ });
+});
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index 59c2e210c..1bde2de50 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -1,4 +1,9 @@
-import { randomUUID, timingSafeEqual } from "node:crypto";
+import {
+ createHash,
+ createHmac,
+ randomUUID,
+ timingSafeEqual,
+} from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import { join } from "node:path";
import { Engine } from "./engine";
@@ -24,8 +29,10 @@ import {
MIN_PART,
type SegmentReport,
type Task,
+ type TranscodeTask,
type VideoResult,
type VideoTask,
+ type WorkItem,
} from "./protocol";
import {
acceptOnce,
@@ -33,16 +40,20 @@ import {
PART_RANGES,
reservePartRange,
} from "./recovery";
-import { S3, s3ConfigFromEnv } from "./s3";
+import { mediaS3ConfigFromEnv, S3, s3ConfigFromEnv } from "./s3";
import { pickQueued as pickQueuedTask } from "./scheduler";
import {
AUDIO_FILE,
checkManifestBounds,
+ isKey,
sourceLimitsFromEnv,
validateJobRequest,
} from "./validate";
-const s3 = new S3(s3ConfigFromEnv());
+// Recordings and exports live in the media bucket (possibly the product's
+// own); the journal stays in the render farm's bucket.
+const s3 = new S3(mediaS3ConfigFromEnv());
+const journalS3 = new S3(s3ConfigFromEnv());
const ENGINE_BIN = process.env.RF_ENGINE_BIN ?? "cap-render-farm";
const WORK_DIR = process.env.RF_WORK_DIR ?? "/tmp/rf-coordinator";
const PORT = Number(process.env.PORT ?? 8080);
@@ -309,7 +320,7 @@ type Poller = {
kinds?: string[];
/** A busy slot reserving its next task: queued work only, never a hedge. */
prefetch?: boolean;
- resolve: (task: Task | null) => void;
+ resolve: (task: WorkItem | null) => void;
};
const pollers: Poller[] = [];
const finishedJobs: string[] = [];
@@ -344,7 +355,7 @@ async function newJob(
acceptances: new Map(),
request,
status: "planning",
- key: `out/${id}.mp4`,
+ key: request.output?.key ?? `out/${id}.mp4`,
t: { requested: requestedAt },
fps: request.fps ?? 30,
bpp: COMPRESSION_BPP[compression],
@@ -365,13 +376,23 @@ async function newJob(
waiters: [],
taskStats: [],
};
- if (HLS) job.hls = await newHlsState(`hls/${id}`);
+ if (HLS) {
+ job.hls = await newHlsState(request.output?.hlsPrefix ?? `hls/${id}`);
+ }
return job;
}
// ---------------------------------------------------------------- planning ---
-type Manifest = { files: { path: string; size: number; key?: string }[] };
+type Manifest = {
+ files: {
+ path: string;
+ size: number;
+ key?: string;
+ /** Transcode this source to `key` first (see TranscodeTask). */
+ transcodeFrom?: string;
+ }[];
+};
type RecordingMeta = {
segments?: {
@@ -475,7 +496,11 @@ async function getBounded(key: string, limit: number) {
}
/** Manifests name local paths and bucket keys; neither may escape its scope. */
-function checkManifest(manifest: Manifest, prefix: string) {
+function checkManifest(
+ manifest: Manifest,
+ prefix: string,
+ sourceRoot?: string,
+) {
const bounds = checkManifestBounds(manifest, SOURCE_LIMITS);
if (bounds) throw new Error(bounds);
for (const file of manifest.files) {
@@ -487,17 +512,27 @@ function checkManifest(manifest: Manifest, prefix: string) {
) {
throw new Error(`manifest path ${file.path} is not a relative path`);
}
- if (
- file.key !== undefined &&
- !file.key.startsWith(`${prefix}/`) &&
- !SOURCE_KEY_PREFIXES.some((allowed) => file.key?.startsWith(allowed))
- ) {
- throw new Error(`manifest key for ${file.path} is outside the recording`);
+ const inScope = (key: string) =>
+ key.startsWith(`${prefix}/`) ||
+ (sourceRoot !== undefined && key.startsWith(sourceRoot)) ||
+ SOURCE_KEY_PREFIXES.some((allowed) => key.startsWith(allowed));
+ for (const key of [file.key, file.transcodeFrom]) {
+ if (key !== undefined && (!isKey(key) || !inScope(key))) {
+ throw new Error(
+ `manifest key for ${file.path} is outside the recording`,
+ );
+ }
+ }
+ if (file.transcodeFrom !== undefined && file.key === undefined) {
+ throw new Error(`manifest transcode for ${file.path} names no key`);
}
}
}
-async function sourceIndex(prefix: string): Promise<SourceIndex> {
+async function sourceIndex(
+ prefix: string,
+ sourceRoot?: string,
+): Promise<SourceIndex> {
const cached =
process.env.RF_INDEX_CACHE !== "0" ? sourceIndexes.get(prefix) : undefined;
if (cached) return cached;
@@ -506,9 +541,19 @@ async function sourceIndex(prefix: string): Promise<SourceIndex> {
await getBounded(`${prefix}/manifest.json`, SOURCE_LIMITS.metadataBytes),
),
) as Manifest;
- checkManifest(manifest, prefix);
+ checkManifest(manifest, prefix, sourceRoot);
const keyOf = (file: { path: string; key?: string }) =>
file.key ?? `${prefix}/${file.path}`;
+ await Promise.all(
+ manifest.files.map(async (file) => {
+ if (file.transcodeFrom === undefined) return;
+ file.size = await awaitTranscode(
+ await ensureTranscode(file.transcodeFrom, keyOf(file)),
+ );
+ }),
+ );
+ const bounds = checkManifestBounds(manifest, SOURCE_LIMITS);
+ if (bounds) throw new Error(bounds);
const metaFile = manifest.files.find(
(file) => file.path === "recording-meta.json",
);
@@ -541,7 +586,10 @@ async function sourceIndex(prefix: string): Promise<SourceIndex> {
async function planJob(job: Job) {
const request = job.request;
const prefix = request.recording.replace(/\/$/, "");
- const { manifest, recordingMeta, mediaMeta } = await sourceIndex(prefix);
+ const { manifest, recordingMeta, mediaMeta } = await sourceIndex(
+ prefix,
+ request.sourceRoot,
+ );
const keyOf = (file: { path: string; key?: string }) =>
file.key ?? `${prefix}/${file.path}`;
@@ -933,7 +981,7 @@ const journalKey = (id: string, name: string) => `jobs/${id}/${name}`;
async function journalPut(key: string, body: Uint8Array | string) {
if (!JOURNAL) return;
- await s3.put(key, body);
+ await journalS3.put(key, body);
}
type JournaledJob = Pick<
@@ -1035,7 +1083,7 @@ function segmentsFromResult(
async function resumeJobs() {
if (!JOURNAL) return;
- const keys = await s3.list("jobs/");
+ const keys = await journalS3.list("jobs/");
const byJob = new Map<string, Set<string>>();
for (const { key } of keys) {
const [, id, ...rest] = key.split("/");
@@ -1051,7 +1099,7 @@ async function resumeJobs() {
if (!names.has("request.json")) continue;
const receipt = JSON.parse(
new TextDecoder().decode(
- await s3.get(journalKey(id, "request.json")),
+ await journalS3.get(journalKey(id, "request.json")),
),
) as { request: JobRequest; requestedAt: number };
if (Date.now() - receipt.requestedAt > 5 * 3600_000) {
@@ -1064,7 +1112,9 @@ async function resumeJobs() {
continue;
}
const record = JSON.parse(
- new TextDecoder().decode(await s3.get(journalKey(id, "job.json"))),
+ new TextDecoder().decode(
+ await journalS3.get(journalKey(id, "job.json")),
+ ),
) as JournaledJob;
// Presigned segment/playlist URLs last 6 h; older jobs are abandoned.
if (Date.now() - (record.t.requested ?? 0) > 5 * 3600_000) {
@@ -1116,7 +1166,9 @@ async function resumeJobs() {
);
reservations.push(
JSON.parse(
- new TextDecoder().decode(await s3.get(journalKey(id, name))),
+ new TextDecoder().decode(
+ await journalS3.get(journalKey(id, name)),
+ ),
),
);
continue;
@@ -1124,14 +1176,14 @@ async function resumeJobs() {
const video = name.match(/^v\/(\d+)\.json$/);
if (video) {
const result = JSON.parse(
- new TextDecoder().decode(await s3.get(journalKey(id, name))),
+ new TextDecoder().decode(await journalS3.get(journalKey(id, name))),
) as VideoResult;
job.videoResults.set(Number(video[1]), result);
continue;
}
const audio = name.match(/^a\/(\d+)\.bin$/);
if (audio) {
- const bytes = await s3.get(journalKey(id, name));
+ const bytes = await journalS3.get(journalKey(id, name));
const length = new DataView(bytes.buffer, bytes.byteOffset).getUint32(
0,
);
@@ -1335,12 +1387,166 @@ function requeue(state: TaskState, reason: string) {
if (!queue.includes(state)) queue.unshift(state);
}
+// -------------------------------------------------------------- transcodes ---
+
+const TRANSCODE_KEYFRAME_SECONDS = 1;
+const TRANSCODE_ATTEMPTS = 3;
+
+type Transcode = {
+ id: string;
+ task: TranscodeTask;
+ state: "checking" | "queued" | "running" | "ready" | "error";
+ worker?: string;
+ attempts: number;
+ lastReportedAt?: number;
+ notBefore?: number;
+ size?: number;
+ error?: string;
+ /** Seconds of source encoded so far, from the worker's heartbeat. */
+ encodedSeconds?: number;
+ settledAt?: number;
+ settled: Promise<void>;
+ settle: () => void;
+};
+
+/** By output key: one transcode per target, shared by every job needing it. */
+const transcodes = new Map<string, Transcode>();
+
+async function ensureTranscode(source: string, output: string) {
+ const existing = transcodes.get(output);
+ if (existing && existing.state !== "error") return existing;
+ const { promise, resolve } = Promise.withResolvers<void>();
+ const id = createHash("sha256").update(output).digest("hex").slice(0, 16);
+ const transcode: Transcode = {
+ id,
+ task: {
+ kind: "transcode",
+ taskId: `tc:${id}`,
+ source,
+ output,
+ keyframeSeconds: TRANSCODE_KEYFRAME_SECONDS,
+ },
+ state: "checking",
+ attempts: 0,
+ settled: promise,
+ settle: resolve,
+ };
+ transcodes.set(output, transcode);
+ // Made by an earlier export (or a previous coordinator): reuse it.
+ const head = await s3.head(output).catch(() => null);
+ if (head && head.size > 0) {
+ settleTranscode(transcode, "ready", head.size);
+ } else {
+ transcode.state = "queued";
+ dispatch();
+ }
+ return transcode;
+}
+
+async function awaitTranscode(transcode: Transcode) {
+ await transcode.settled;
+ if (transcode.state !== "ready" || transcode.size === undefined) {
+ throw new Error(
+ `transcode of ${transcode.task.source} failed: ${transcode.error}`,
+ );
+ }
+ return transcode.size;
+}
+
+function nextTranscode() {
+ const at = Date.now();
+ for (const transcode of transcodes.values()) {
+ if (transcode.state === "queued" && (transcode.notBefore ?? 0) <= at) {
+ return transcode;
+ }
+ }
+}
+
+function transcodeById(id: string) {
+ for (const transcode of transcodes.values()) {
+ if (transcode.id === id) return transcode;
+ }
+}
+
+function settleTranscode(
+ transcode: Transcode,
+ state: "ready" | "error",
+ detail: number | string,
+) {
+ transcode.state = state;
+ transcode.worker = undefined;
+ if (state === "ready") transcode.size = Number(detail);
+ else transcode.error = String(detail);
+ transcode.settledAt = Date.now();
+ transcode.settle();
+}
+
+function requeueTranscode(transcode: Transcode, reason: string) {
+ console.warn(`requeue ${transcode.task.taskId}: ${reason}`);
+ if (transcode.attempts >= TRANSCODE_ATTEMPTS) {
+ settleTranscode(transcode, "error", reason);
+ return;
+ }
+ const delay = 1000 * 2 ** transcode.attempts;
+ transcode.state = "queued";
+ transcode.worker = undefined;
+ transcode.notBefore = Date.now() + delay;
+ setTimeout(dispatch, delay + 50).unref();
+}
+
+function transcodeSummary(transcode: Transcode) {
+ return {
+ id: transcode.id,
+ status: transcode.state === "checking" ? "queued" : transcode.state,
+ source: transcode.task.source,
+ output: transcode.task.output,
+ size: transcode.size,
+ error: transcode.error,
+ encodedSeconds: transcode.encodedSeconds,
+ };
+}
+
+setInterval(() => {
+ // Workers heartbeat every 3 s and report a running transcode each time.
+ const cutoff = Date.now() - 30_000;
+ for (const [output, transcode] of transcodes) {
+ if (transcode.state === "running") {
+ const worker = transcode.worker ? workers.get(transcode.worker) : null;
+ if (
+ !worker ||
+ worker.lastSeen < cutoff ||
+ (transcode.lastReportedAt ?? 0) < cutoff
+ ) {
+ requeueTranscode(transcode, "worker stopped reporting it");
+ }
+ } else if (
+ transcode.settledAt !== undefined &&
+ Date.now() - transcode.settledAt > JOB_RETENTION_MS
+ ) {
+ transcodes.delete(output);
+ }
+ }
+}, 5_000);
+
function dispatch() {
pumpLocalAudio();
for (let p = 0; p < pollers.length; ) {
const poller = pollers[p] as Poller;
const accepts = (kind: string) =>
!poller.kinds || poller.kinds.includes(kind);
+ // Transcodes gate an export's planning, so they go before any chunk.
+ const transcode =
+ accepts("video") && !poller.prefetch ? nextTranscode() : undefined;
+ if (transcode) {
+ pollers.splice(p, 1);
+ transcode.state = "running";
+ transcode.worker = poller.worker;
+ transcode.attempts++;
+ transcode.lastReportedAt = Date.now();
+ transcode.encodedSeconds = 0;
+ poller.resolve({ ...transcode.task, attempt: transcode.attempts });
+ continue;
+ }
const next = pickQueued(accepts);
let state: TaskState | undefined;
if (next >= 0) {
@@ -1499,6 +1705,11 @@ function supersede(id: string) {
if (old === id || old.slice(0, old.lastIndexOf("-")) !== host) continue;
if (worker.lastSeen > quietSince) continue;
workers.delete(old);
+ for (const transcode of transcodes.values()) {
+ if (transcode.state === "running" && transcode.worker === old) {
+ requeueTranscode(transcode, `worker ${old} restarted`);
+ }
+ }
for (const job of jobs.values()) {
if (job.status !== "rendering") continue;
for (const state of job.tasks.values()) {
@@ -1659,8 +1870,76 @@ function persistFinished(job: Job) {
});
}
+// ---------------------------------------------------------------- callbacks ---
+
+// Host suffixes a job may name as its callback (e.g. "vercel.app,cap.so").
+const CALLBACK_HOSTS = (process.env.RF_CALLBACK_HOSTS ?? "")
+ .split(",")
+ .map((host) => host.trim().toLowerCase())
+ .filter(Boolean);
+const CALLBACK_SECRET = process.env.RF_CALLBACK_SECRET || TOKEN;
+
+function callbackAllowed(callbackUrl: string) {
+ const host = new URL(callbackUrl).hostname.toLowerCase();
+ return CALLBACK_HOSTS.some(
+ (allowed) => host === allowed || host.endsWith(`.${allowed}`),
+ );
+}
+
+function callbackPayload(job: Job) {
+ return {
+ id: job.id,
+ reference: job.request.reference,
+ status: job.status,
+ error: job.error,
+ key: job.key,
+ bytes: job.outputBytes,
+ width: job.width,
+ height: job.height,
+ frames: job.totalFrames,
+ fps: job.fps,
+ durationSeconds: job.totalFrames / job.fps,
+ };
+}
+
+/** Posts the outcome, signed `sha256=<hex hmac of the body>`, with retries. */
+function notify(
+ job: Job,
+ body = JSON.stringify(callbackPayload(job)),
+ attempt = 0,
+) {
+ const url = job.request.callbackUrl;
+ if (!url) return;
+ const signature = createHmac("sha256", CALLBACK_SECRET)
+ .update(body)
+ .digest("hex");
+ fetch(url, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-render-farm-signature": `sha256=${signature}`,
+ },
+ body,
+ signal: AbortSignal.timeout(15_000),
+ })
+ .then((response) => {
+ if (!response.ok) throw new Error(`callback -> ${response.status}`);
+ })
+ .catch((error) => {
+ if (attempt >= 8) {
+ console.error(`job ${job.id} callback gave up: ${error}`);
+ return;
+ }
+ setTimeout(
+ () => notify(job, body, attempt + 1),
+ Math.min(60_000, 1000 * 2 ** attempt),
+ ).unref();
+ });
+}
+
function finish(job: Job) {
if (job.status === "error" || !job.hls || job.hls.ended) persistFinished(job);
+ notify(job);
job.audioCache?.close();
// Freeze the summary, then drop the media: rendered audio alone is ~290 MB
// for a 2 h export, and finished jobs were never evicted.
@@ -1981,6 +2260,29 @@ function percentile(values: number[], p: number) {
);
}
+/** Share of the export rendered, 0-1; 1 only once the MP4 is complete. */
+function jobProgress(job: Job) {
+ if (job.status === "ready") return 1;
+ if (job.totalFrames <= 0) return 0;
+ let frames = 0;
+ for (const chunk of job.chunks) {
+ if (job.videoResults.has(chunk.index)) {
+ frames += chunk.frames[1] - chunk.frames[0];
+ }
+ }
+ for (const state of job.tasks.values()) {
+ if (
+ state.task.kind === "video" &&
+ state.state === "running" &&
+ !state.duplicateOf &&
+ !job.videoResults.has(state.task.chunk)
+ ) {
+ frames += state.progress?.frames ?? 0;
+ }
+ }
+ return Math.min(0.99, frames / job.totalFrames);
+}
+
function summary(job: Job) {
const start = job.t.requested ?? 0;
const rel = Object.fromEntries(
@@ -2015,6 +2317,8 @@ function summary(job: Job) {
bytes: job.outputBytes,
},
url: job.status === "ready" ? job.url : undefined,
+ reference: job.request.reference,
+ progress: jobProgress(job),
timeline: rel,
plan: job.plan,
probe: job.probe,
@@ -2088,7 +2392,7 @@ Bun.serve({
workers.set(body.worker, worker);
if (body.draining)
return Response.json({ task: null, finished: finishedJobs });
- const task = await new Promise<Task | null>((resolve) => {
+ const task = await new Promise<WorkItem | null>((resolve) => {
const poller: Poller = {
worker: body.worker,
kinds: body.kinds,
@@ -2130,7 +2434,22 @@ Bun.serve({
elapsedMs: number;
}[];
};
+ const staleTranscodes: string[] = [];
for (const entry of body.running ?? []) {
+ if (entry.taskId.startsWith("tc:")) {
+ const transcode = transcodeById(entry.taskId.slice(3));
+ if (
+ transcode?.state === "running" &&
+ transcode.worker === body.worker &&
+ transcode.attempts === entry.attempt
+ ) {
+ transcode.lastReportedAt = Date.now();
+ transcode.encodedSeconds = entry.frames;
+ } else {
+ staleTranscodes.push(entry.taskId);
+ }
+ continue;
+ }
const job = jobs.get(entry.taskId.split(":")[0] ?? "");
const state = job?.tasks.get(entry.taskId);
if (!state) continue;
@@ -2190,7 +2509,7 @@ Bun.serve({
}
return Response.json({
finished: finishedJobs,
- cancel: cancellations(body.worker),
+ cancel: [...cancellations(body.worker), ...staleTranscodes],
});
}
@@ -2224,6 +2543,69 @@ Bun.serve({
return Response.json({ ok: true });
}
+ if (url.pathname === "/transcodes" && request.method === "POST") {
+ const { source, output, sourceRoot } = (await request.json()) as Record<
+ string,
+ unknown
+ >;
+ if (
+ !isKey(sourceRoot, { trailingSlash: true }) ||
+ !sourceRoot.endsWith("/") ||
+ !isKey(source) ||
+ !isKey(output) ||
+ !source.startsWith(sourceRoot) ||
+ !output.startsWith(sourceRoot) ||
+ !output.endsWith(".mp4")
+ ) {
+ return new Response(
+ "source and output must be keys inside sourceRoot, output an .mp4",
+ { status: 400 },
+ );
+ }
+ return Response.json(
+ transcodeSummary(await ensureTranscode(source, output)),
+ );
+ }
+ const transcodeMatch = url.pathname.match(
+ /^\/transcodes\/([0-9a-f]{16})(?:\/(done|fail))?$/,
+ );
+ if (transcodeMatch) {
+ const transcode = transcodeById(transcodeMatch[1] ?? "");
+ if (!transcode) return new Response("unknown transcode", { status: 404 });
+ if (!transcodeMatch[2] && request.method === "GET") {
+ return Response.json(transcodeSummary(transcode));
+ }
+ if (request.method !== "POST") {
+ return new Response("method not allowed", { status: 405 });
+ }
+ const report = (await request.json()) as {
+ worker: string;
+ attempt?: number;
+ size?: number;
+ error?: string;
+ };
+ // Outputs are written with If-None-Match, so any attempt that
+ // finished produced the one object there is; failures count only
+ // for the current attempt.
+ if (transcodeMatch[2] === "done") {
+ if (
+ transcode.state !== "ready" &&
+ typeof report.size === "number" &&
+ report.size > 0
+ ) {
+ settleTranscode(transcode, "ready", report.size);
+ dispatch();
+ }
+ } else if (
+ transcode.state === "running" &&
+ transcode.worker === report.worker &&
+ transcode.attempts === report.attempt
+ ) {
+ requeueTranscode(transcode, report.error ?? "failed");
+ }
+ return Response.json({ ok: true });
+ }
+
const taskMatch = url.pathname.match(
/^\/tasks\/([^/]+)\/(done|fail|audio)$/,
);
@@ -2358,7 +2740,7 @@ Bun.serve({
return new Response(parsed, { status: 400 });
const body = parsed;
const started = performance.now();
- await sourceIndex(body.recording.replace(/\/$/, ""));
+ await sourceIndex(body.recording.replace(/\/$/, ""), body.sourceRoot);
return Response.json({ ms: Math.round(performance.now() - started) });
}
@@ -2367,6 +2749,11 @@ Bun.serve({
if (typeof parsed === "string")
return new Response(parsed, { status: 400 });
const body = parsed;
+ if (body.callbackUrl && !callbackAllowed(body.callbackUrl)) {
+ return new Response("callbackUrl host is not in RF_CALLBACK_HOSTS", {
+ status: 400,
+ });
+ }
const active = [...jobs.values()].filter(
(job) => job.status !== "ready" && job.status !== "error",
).length;
diff --git a/apps/render-farm/src/protocol.ts b/apps/render-farm/src/protocol.ts
index c9cb44e54..6bfbba01a 100644
--- a/apps/render-farm/src/protocol.ts
+++ b/apps/render-farm/src/protocol.ts
@@ -66,6 +66,23 @@ export type AudioTask = {
export type Task = VideoTask | AudioTask;
+/**
+ * Re-encodes a source the planner cannot index (a browser recording's WebM
+ * has no seek index and rare keyframes) into an H.264 MP4 with a keyframe
+ * every `keyframeSeconds`, so chunks can start anywhere in it.
+ */
+export type TranscodeTask = {
+ kind: "transcode";
+ taskId: string;
+ attempt?: number;
+ source: string;
+ output: string;
+ keyframeSeconds: number;
+};
+
+/** Anything a worker slot can be handed. */
+export type WorkItem = Task | TranscodeTask;
+
export type TaskTimings = {
queuedMs: number;
fetch: FetchStats;
@@ -120,4 +137,15 @@ export type JobRequest = {
frameLimit?: number;
/** Pin the chunk count (profiling). */
chunks?: number;
+ /**
+ * Folder the recording belongs to (e.g. a video's root). Manifest keys and
+ * outputs may point anywhere inside it, not only inside `recording`.
+ */
+ sourceRoot?: string;
+ /** Where the MP4 and HLS segments go; default `out/<id>.mp4` and `hls/<id>`. */
+ output?: { key: string; hlsPrefix?: string };
+ /** Receives the job summary (HMAC-signed) once the export is ready or failed. */
+ callbackUrl?: string;
+ /** Opaque, echoed in callbacks. */
+ reference?: string;
};
diff --git a/apps/render-farm/src/transcode.test.ts b/apps/render-farm/src/transcode.test.ts
new file mode 100644
index 000000000..1666e234b
--- /dev/null
+++ b/apps/render-farm/src/transcode.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from "bun:test";
+import { encodedSeconds, transcodeArgs } from "./transcode";
+
+describe("transcodeArgs", () => {
+ test("NVENC keeps frames on the GPU and forces one-second IDR frames", () => {
+ const args = transcodeArgs("https://in", "/tmp/out.mp4", 1, "h264_nvenc");
+ expect(
+ args.slice(args.indexOf("-hwaccel"), args.indexOf("-hwaccel") + 2),
+ ).toEqual(["-hwaccel", "cuda"]);
+ expect(args).toContain("expr:gte(t,n_forced*1)");
+ expect(
+ args.slice(args.indexOf("-forced-idr"), args.indexOf("-forced-idr") + 2),
+ ).toEqual(["-forced-idr", "1"]);
+ expect(args.slice(args.indexOf("-bf"), args.indexOf("-bf") + 2)).toEqual([
+ "-bf",
+ "0",
+ ]);
+ expect(
+ args.slice(args.indexOf("-fps_mode"), args.indexOf("-fps_mode") + 2),
+ ).toEqual(["-fps_mode", "passthrough"]);
+ expect(args.at(-1)).toBe("/tmp/out.mp4");
+ expect(args.slice(-3, -1)).toEqual(["-movflags", "+faststart"]);
+ });
+
+ test("a CPU encoder drops the GPU options", () => {
+ const args = transcodeArgs("https://in", "/tmp/out.mp4", 2, "libx264");
+ expect(args).not.toContain("-hwaccel");
+ expect(args).not.toContain("-forced-idr");
+ expect(args).toContain("expr:gte(t,n_forced*2)");
+ });
+});
+
+describe("encodedSeconds", () => {
+ test("reads ffmpeg progress output times", () => {
+ expect(encodedSeconds("out_time_us=2500000")).toBe(2.5);
+ expect(encodedSeconds("out_time_ms=1000000")).toBe(1);
+ expect(encodedSeconds("frame=12")).toBeNull();
+ expect(encodedSeconds("out_time=00:00:01.000000")).toBeNull();
+ });
+});
diff --git a/apps/render-farm/src/transcode.ts b/apps/render-farm/src/transcode.ts
new file mode 100644
index 000000000..b049f65db
--- /dev/null
+++ b/apps/render-farm/src/transcode.ts
@@ -0,0 +1,53 @@
+/**
+ * ffmpeg arguments that re-encode a recording's video track into an H.264 MP4
+ * the planner can index: a keyframe every `keyframeSeconds`, no B-frames
+ * (the index orders samples by decode time), source timestamps kept as they
+ * are (browser recordings are variable frame rate) and the moov up front.
+ */
+export function transcodeArgs(
+ input: string,
+ output: string,
+ keyframeSeconds: number,
+ encoder: string,
+) {
+ const nvenc = encoder === "h264_nvenc";
+ return [
+ "-hide_banner",
+ "-nostdin",
+ "-y",
+ "-loglevel",
+ "error",
+ "-progress",
+ "pipe:1",
+ "-nostats",
+ ...(nvenc ? ["-hwaccel", "cuda"] : []),
+ "-i",
+ input,
+ "-map",
+ "0:v:0",
+ "-an",
+ "-fps_mode",
+ "passthrough",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:v",
+ encoder,
+ ...(nvenc
+ ? ["-preset", "p4", "-tune", "hq", "-rc", "vbr", "-cq", "19", "-b:v", "0"]
+ : ["-preset", "veryfast", "-crf", "18"]),
+ "-bf",
+ "0",
+ "-force_key_frames",
+ `expr:gte(t,n_forced*${keyframeSeconds})`,
+ ...(nvenc ? ["-forced-idr", "1"] : []),
+ "-movflags",
+ "+faststart",
+ output,
+ ];
+}
+
+/** Seconds of output written so far, from an ffmpeg `-progress` line. */
+export function encodedSeconds(line: string) {
+ const match = line.match(/^out_time_(?:us|ms)=(\d+)$/);
+ return match ? Number(match[1]) / 1_000_000 : null;
+}
diff --git a/apps/render-farm/src/validate.test.ts b/apps/render-farm/src/validate.test.ts
index 1b435617c..a3e1bbc9a 100644
--- a/apps/render-farm/src/validate.test.ts
+++ b/apps/render-farm/src/validate.test.ts
@@ -108,3 +108,93 @@ describe("checkManifestBounds", () => {
expect(parsed.exportSeconds).toBe(4 * 3600);
});
});
+
+describe("product job fields", () => {
+ const base = {
+ recording: "owner/video/.recording/render/abc/project",
+ sourceRoot: "owner/video/",
+ };
+
+ test("accepts outputs and callbacks inside the source folder", () => {
+ expect(
+ typeof validateJobRequest({
+ ...base,
+ output: {
+ key: "owner/video/.recording/render/abc/result.mp4",
+ hlsPrefix: "owner/video/.recording/render/abc/hls",
+ },
+ callbackUrl: "https://preview.cap.test/api/render-farm/callback",
+ reference: "video-1",
+ }),
+ ).toBe("object");
+ });
+
+ test.each([
+ [{ ...base, sourceRoot: "owner/other/" }, "sourceRoot"],
+ [{ ...base, sourceRoot: "owner/video" }, "sourceRoot"],
+ [{ ...base, output: { key: "owner/other/result.mp4" } }, "output"],
+ [{ ...base, output: { key: "owner/video/result.webm" } }, "output"],
+ [
+ { ...base, output: { key: "owner/video/result.mp4", hlsPrefix: "hls" } },
+ "output",
+ ],
+ [{ ...base, output: { key: "owner/video/../x/result.mp4" } }, "output"],
+ [{ ...base, callbackUrl: "http://preview.cap.test/hook" }, "callbackUrl"],
+ [{ ...base, callbackUrl: "not a url" }, "callbackUrl"],
+ [{ ...base, reference: 7 }, "reference"],
+ ])("rejects %j", (body, message) => {
+ expect(validateJobRequest(body)).toContain(message);
+ });
+
+ test("outputs default to the recording's own folder without a sourceRoot", () => {
+ expect(
+ validateJobRequest({
+ recording: "rec",
+ output: { key: "rec/out.mp4" },
+ }),
+ ).not.toBeString();
+ expect(
+ validateJobRequest({
+ recording: "rec",
+ output: { key: "other/out.mp4" },
+ }),
+ ).toContain("output");
+ });
+});
+
+describe("manifest transcodes", () => {
+ const limits = sourceLimitsFromEnv({});
+
+ test("a source to transcode may omit its size until it exists", () => {
+ expect(
+ checkManifestBounds(
+ {
+ files: [
+ {
+ path: "content/segments/segment-0/display.mp4",
+ key: "owner/video/.recording/render/sources/display.mp4",
+ transcodeFrom: "owner/video/raw-upload.webm",
+ },
+ ],
+ },
+ limits,
+ ),
+ ).toBeNull();
+ });
+
+ test("a transcode must produce an mp4", () => {
+ expect(
+ checkManifestBounds(
+ {
+ files: [
+ {
+ path: "content/segments/segment-0/display.webm",
+ transcodeFrom: "owner/video/raw-upload.webm",
+ },
+ ],
+ },
+ limits,
+ ),
+ ).toContain("transcodeFrom");
+ });
+});
diff --git a/apps/render-farm/src/validate.ts b/apps/render-farm/src/validate.ts
index d758979c8..ac446de14 100644
--- a/apps/render-farm/src/validate.ts
+++ b/apps/render-farm/src/validate.ts
@@ -74,6 +74,44 @@ export function validateJobRequest(body: unknown): JobRequest | string {
) {
return "duplicateStragglers must be a boolean";
}
+ const sourceRoot = request.sourceRoot;
+ if (sourceRoot !== undefined) {
+ if (
+ !isKey(sourceRoot, { trailingSlash: true }) ||
+ !sourceRoot.endsWith("/") ||
+ !recording.startsWith(sourceRoot)
+ ) {
+ return "sourceRoot must be a folder containing the recording";
+ }
+ }
+ const scope = typeof sourceRoot === "string" ? sourceRoot : `${recording}/`;
+ const output = request.output;
+ if (output !== undefined) {
+ const { key, hlsPrefix } = (output ?? {}) as Record<string, unknown>;
+ if (
+ !output ||
+ typeof output !== "object" ||
+ !isKey(key) ||
+ !key.endsWith(".mp4") ||
+ !key.startsWith(scope) ||
+ (hlsPrefix !== undefined &&
+ (!isKey(hlsPrefix) || !hlsPrefix.startsWith(scope)))
+ ) {
+ return "output must name an .mp4 key and HLS prefix inside the source folder";
+ }
+ }
+ if (
+ request.callbackUrl !== undefined &&
+ !isCallbackUrl(request.callbackUrl)
+ ) {
+ return "callbackUrl must be an https URL";
+ }
+ if (
+ request.reference !== undefined &&
+ (typeof request.reference !== "string" || request.reference.length > 200)
+ ) {
+ return "reference must be a string of at most 200 characters";
+ }
return request as JobRequest;
}
@@ -126,27 +164,67 @@ export function checkManifestBounds(
for (const file of files) {
if (!file || typeof file !== "object")
return "manifest entry is not an object";
- const { path, key, size } = file as Record<string, unknown>;
+ const { path, key, size, transcodeFrom } = file as Record<string, unknown>;
if (typeof path !== "string" || path.length === 0 || path.length > 1024) {
return "manifest paths must be strings of 1 to 1024 characters";
}
if (key !== undefined && (typeof key !== "string" || key.length > 1024)) {
return `manifest key for ${path} must be a string of at most 1024 characters`;
}
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
+ if (
+ transcodeFrom !== undefined &&
+ (typeof transcodeFrom !== "string" ||
+ transcodeFrom.length > 1024 ||
+ !path.endsWith(".mp4"))
+ ) {
+ return `manifest transcodeFrom for ${path} must be a key and produce an .mp4`;
+ }
+ // Size of a source still to be transcoded is only known afterwards.
+ if (
+ !(transcodeFrom !== undefined && size === undefined) &&
+ (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)
+ ) {
return `manifest size for ${path} must be a non-negative integer`;
}
if (
!path.endsWith(".mp4") &&
!AUDIO_FILE.test(path) &&
+ typeof size === "number" &&
size > limits.sidecarBytes
) {
return `${path} is ${size} bytes (limit ${limits.sidecarBytes})`;
}
- total += size;
+ total += typeof size === "number" ? size : 0;
}
if (total > limits.sourceBytes) {
return `recording is ${total} bytes (limit ${limits.sourceBytes})`;
}
return null;
}
+
+/** A bucket key or folder with no empty or parent segments. */
+export function isKey(
+ value: unknown,
+ options: { trailingSlash?: boolean } = {},
+): value is string {
+ if (typeof value !== "string" || !/^[A-Za-z0-9._/-]{1,512}$/.test(value)) {
+ return false;
+ }
+ const parts = value.split("/");
+ if (options.trailingSlash && parts.at(-1) === "") parts.pop();
+ return !parts.includes("..") && !parts.includes("") && !parts.includes(".");
+}
+
+function isCallbackUrl(value: unknown) {
+ if (typeof value !== "string" || value.length > 2048) return false;
+ try {
+ const url = new URL(value);
+ return (
+ url.protocol === "https:" ||
+ (url.protocol === "http:" &&
+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index 94ea723a9..a5f669f8c 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -12,14 +12,16 @@ import {
type AudioTask,
MIN_PART,
type SegmentReport,
- type Task,
type TaskTimings,
+ type TranscodeTask,
type VideoResult,
type VideoTask,
+ type WorkItem,
} from "./protocol";
-import { S3, s3ConfigFromEnv } from "./s3";
+import { mediaS3ConfigFromEnv, S3 } from "./s3";
+import { encodedSeconds, transcodeArgs } from "./transcode";
-const s3 = new S3(s3ConfigFromEnv());
+const s3 = new S3(mediaS3ConfigFromEnv());
const COORDINATOR = (
process.env.RF_COORDINATOR_URL ?? "http://127.0.0.1:8080"
).replace(/\/$/, "");
@@ -94,19 +96,26 @@ function dropJobs(finished: string[]) {
for (const jobId of finished) {
const cache = caches.get(jobId);
if (!cache) continue;
- if ([...busy.values()].some((task) => task.jobId === jobId)) continue;
+ if (
+ [...busy.values()].some(
+ (task) => task.kind !== "transcode" && task.jobId === jobId,
+ )
+ )
+ continue;
cache.close();
caches.delete(jobId);
rmSync(join(WORK_DIR, jobId), { recursive: true, force: true });
}
}
-const busy = new Map<number, Task>();
+const busy = new Map<number, WorkItem>();
+// Running ffmpeg transcodes, by slot, so cancels and the watchdog can stop them.
+const transcoders = new Map<number, Bun.Subprocess>();
const progress = new Map<
number,
{
taskId: string;
- kind: "video" | "audio";
+ kind: "video" | "audio" | "transcode";
frames: number;
total: number;
startedAt: number;
@@ -646,6 +655,67 @@ async function runAudio(task: AudioTask, engine: Engine, queuedMs: number) {
}
}
+const TRANSCODE_ENCODER = process.env.RF_TRANSCODE_ENCODER ?? "h264_nvenc";
+
+/** Re-encodes `task.source` into `task.output`; returns the stored size. */
+async function runTranscode(task: TranscodeTask, slot: number) {
+ const dir = join(WORK_DIR, `transcode-${randomUUID()}`);
+ mkdirSync(dir, { recursive: true });
+ const entry = {
+ taskId: task.taskId,
+ kind: "transcode" as const,
+ frames: 0,
+ total: 0,
+ startedAt: Date.now(),
+ lastProgressAt: Date.now(),
+ };
+ progress.set(slot, entry);
+ try {
+ const output = join(dir, "output.mp4");
+ const ffmpeg = Bun.spawn(
+ [
+ "ffmpeg",
+ ...transcodeArgs(
+ await s3.presignFresh("GET", task.source, 6 * 3600),
+ output,
+ task.keyframeSeconds,
+ TRANSCODE_ENCODER,
+ ),
+ ],
+ { stdout: "pipe", stderr: "pipe" },
+ );
+ transcoders.set(slot, ffmpeg);
+ const stderr = new Response(ffmpeg.stderr).text();
+ const decoder = new TextDecoder();
+ let buffered = "";
+ for await (const bytes of ffmpeg.stdout) {
+ buffered += decoder.decode(bytes, { stream: true });
+ const lines = buffered.split("\n");
+ buffered = lines.pop() ?? "";
+ for (const line of lines) {
+ const seconds = encodedSeconds(line.trim());
+ if (seconds !== null && seconds > entry.frames) {
+ entry.frames = Math.floor(seconds);
+ entry.lastProgressAt = Date.now();
+ }
+ }
+ }
+ const code = await ffmpeg.exited;
+ if (code !== 0) {
+ throw new Error(
+ `ffmpeg exited ${code}: ${(await stderr).trim().slice(-500)}`,
+ );
+ }
+ return await s3.uploadFile(task.output, output, "video/mp4", {
+ ifNoneMatch: true,
+ });
+ } finally {
+ transcoders.delete(slot);
+ progress.delete(slot);
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
async function poll(kinds: string[] | undefined, prefetch = false) {
const controller = new AbortController();
openPolls.add(controller);
@@ -664,7 +734,7 @@ async function poll(kinds: string[] | undefined, prefetch = false) {
controller.signal,
).finally(() => openPolls.delete(controller));
const body = (await response.json()) as {
- task: Task | null;
+ task: WorkItem | null;
finished: string[];
};
dropJobs(body.finished ?? []);
@@ -678,7 +748,7 @@ process.on("unhandledRejection", (error) => {
let draining = false;
// Slots holding a prefetched (already reserved) next task, once it is known.
-const reserved = new Map<number, Task | null>();
+const reserved = new Map<number, WorkItem | null>();
const busySince = new Map<number, number>();
function exitWhenIdle() {
@@ -703,14 +773,14 @@ for (const signal of ["SIGTERM", "SIGINT"] as const) {
async function slotLoop(slot: number) {
let engine = engines[slot] as Engine;
const kinds = slot >= SLOTS ? ["audio"] : SLOT_KINDS;
- let next: Promise<Task | null> | null = null;
+ let next: Promise<WorkItem | null> | null = null;
for (;;) {
if (draining && !next) {
exitWhenIdle();
await Bun.sleep(1000);
continue;
}
- let task: Task | null = null;
+ let task: WorkItem | null = null;
try {
task = next ? await next : await poll(kinds);
} catch (error) {
@@ -731,9 +801,11 @@ async function slotLoop(slot: number) {
.then((upcoming) => {
if (upcoming) {
reserved.set(slot, upcoming);
- cacheFor(upcoming.jobId)
- .materialize(upcoming.files)
- .catch(() => {});
+ if (upcoming.kind !== "transcode") {
+ cacheFor(upcoming.jobId)
+ .materialize(upcoming.files)
+ .catch(() => {});
+ }
}
return upcoming;
})
@@ -750,7 +822,14 @@ async function slotLoop(slot: number) {
);
engines[slot] = engine;
}
- if (task.kind === "video") {
+ if (task.kind === "transcode") {
+ const size = await runTranscode(task, slot);
+ await post(`/transcodes/${task.taskId.slice(3)}/done`, {
+ worker: WORKER_ID,
+ attempt: task.attempt,
+ size,
+ });
+ } else if (task.kind === "video") {
const result = await runVideo(task, engine, 0, prefetchNext);
await post(`/tasks/${encodeURIComponent(task.taskId)}/done`, result);
const vram = (
@@ -792,11 +871,17 @@ async function slotLoop(slot: number) {
setTimeout(() => process.exit(75), 500);
}
}
- await post(`/tasks/${encodeURIComponent(task.taskId)}/fail`, {
+ const failure = {
worker: WORKER_ID,
attempt: task.attempt,
error: String(error instanceof Error ? error.message : error),
- }).catch(() => {});
+ };
+ await post(
+ task.kind === "transcode"
+ ? `/transcodes/${task.taskId.slice(3)}/fail`
+ : `/tasks/${encodeURIComponent(task.taskId)}/fail`,
+ failure,
+ ).catch(() => {});
} finally {
busy.delete(slot);
busySince.delete(slot);
@@ -859,6 +944,10 @@ function cancel(taskIds: string[]) {
for (const [slot, task] of busy) {
if (!taskIds.includes(task.taskId)) continue;
console.log(`cancelling ${task.taskId}`);
+ if (task.kind === "transcode") {
+ transcoders.get(slot)?.kill("SIGKILL");
+ continue;
+ }
// SIGKILL: a stopped or wedged engine never acts on SIGTERM and would
// hold its slot until the watchdog gave up on it too.
engines[slot]?.kill("SIGKILL");
@@ -868,6 +957,16 @@ function cancel(taskIds: string[]) {
setInterval(() => {
const now = Date.now();
for (const [slot, entry] of progress) {
+ if (entry.kind === "transcode") {
+ // Decoding a long source can start slowly; a minute without any
+ // output means a wedged ffmpeg.
+ if (now - entry.lastProgressAt >= Math.max(STALL_MS, 60_000)) {
+ console.error(`${entry.taskId}: no progress, killing ffmpeg`);
+ entry.lastProgressAt = now;
+ transcoders.get(slot)?.kill("SIGKILL");
+ }
+ continue;
+ }
if (entry.kind !== "video" || now - entry.lastProgressAt < STALL_MS)
continue;
console.error(