Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(render-farm): parallel GPU export farm with progressive HLS output

Richie McIlroyfa5d55736d48
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2acda9504..d0d6e27d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -99,6 +99,11 @@ jobs:
bun test scripts/emails scripts/loops/profile.test.ts scripts/loops/lifecycle.test.ts scripts/loops/watchdog.test.ts
bun run tsc --noEmit --strict --jsx react-jsx --allowImportingTsExtensions --target ESNext --module ESNext --moduleResolution bundler --resolveJsonModule --types bun --skipLibCheck scripts/loops/*.ts scripts/emails/*.ts emails/*.ts emails/marketing/*.ts
+ - name: Test render farm orchestration
+ run: |
+ bun test apps/render-farm
+ bun run --cwd apps/render-farm typecheck
+
- name: Test web React compatibility
run: >-
bun run --cwd apps/web test
diff --git a/.github/workflows/sync-tests.yml b/.github/workflows/sync-tests.yml
index 6367e4c7b..cb63034c8 100644
--- a/.github/workflows/sync-tests.yml
+++ b/.github/workflows/sync-tests.yml
@@ -23,6 +23,7 @@ on:
- "crates/enc-mediafoundation/**"
- "crates/timestamp/**"
- "crates/rendering/**"
+ - "crates/render-farm/**"
- "crates/editor/**"
- "crates/export/**"
- "crates/audio/**"
@@ -157,6 +158,10 @@ jobs:
cargo test --locked -p cap-editor --lib audio_output::tests::
cargo test --locked -p cap-editor --lib playback::tests::
+ - name: Render farm engine
+ shell: bash
+ run: cargo test --locked -p cap-render-farm
+
# Real encoders + DASH muxer + remux/validation over full instant-mode
# scenarios: pause/resume excision, stall-recovery bursts with
# same-microsecond timestamps, segment assembly and A/V alignment.
diff --git a/Cargo.lock b/Cargo.lock
index 4d08eb8dd..e56c17c25 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1980,11 +1980,33 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "cap-render-farm"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "base64 0.22.1",
+ "cap-audio",
+ "cap-editor",
+ "cap-export",
+ "cap-project",
+ "cap-rendering",
+ "ffmpeg-next",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "wgpu",
+ "workspace-hack",
+]
+
[[package]]
name = "cap-rendering"
version = "0.1.0"
dependencies = [
"anyhow",
+ "ash",
"bezier_easing",
"build-time",
"bytemuck",
@@ -2005,6 +2027,7 @@ dependencies = [
"futures-intrusive",
"glyphon",
"image 0.25.8",
+ "libloading 0.8.8",
"log",
"metal 0.31.0",
"objc2 0.6.2",
diff --git a/apps/render-farm/Dockerfile b/apps/render-farm/Dockerfile
new file mode 100644
index 000000000..0d9562c88
--- /dev/null
+++ b/apps/render-farm/Dockerfile
@@ -0,0 +1,54 @@
+# Build from the repository root:
+# docker build -f apps/render-farm/Dockerfile -t cap-render-farm .
+FROM rust:1.90-trixie AS engine
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ clang libclang-dev libssl-dev libasound2-dev libx11-dev libvulkan-dev \
+ pkg-config ffmpeg libavcodec-dev libavformat-dev libavfilter-dev \
+ libavdevice-dev libavutil-dev libswscale-dev libswresample-dev \
+ libpostproc-dev \
+ && rm -rf /var/lib/apt/lists/*
+WORKDIR /source
+COPY Cargo.toml Cargo.lock ./
+COPY crates ./crates
+COPY vendor ./vendor
+COPY apps/cli ./apps/cli
+COPY apps/desktop/src-tauri ./apps/desktop/src-tauri
+# The hot loops run on the GPU (NVDEC, Vulkan compositing, NVENC); fat LTO
+# costs minutes per build for no measurable export speed.
+ENV CARGO_PROFILE_RELEASE_LTO=false \
+ CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 \
+ CARGO_PROFILE_RELEASE_DEBUG=0
+RUN cargo build --release --locked -p cap-render-farm \
+ && install -Dm755 target/release/cap-render-farm /out/cap-render-farm
+
+FROM oven/bun:1.4.0 AS bun
+
+FROM debian:trixie-slim
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ ffmpeg libasound2t64 libvulkan1 mesa-vulkan-drivers fontconfig \
+ fonts-dejavu-core ca-certificates libx11-6 libxext6 libgl1 libegl1 \
+ libglvnd0 \
+ && rm -rf /var/lib/apt/lists/*
+# The NVIDIA container toolkit mounts the driver libraries but not the
+# manifests. NVIDIA's headless Vulkan goes through EGL, so without the glvnd
+# EGL vendor file the ICD fails to initialise and wgpu silently falls back to
+# llvmpipe.
+RUN mkdir -p /usr/share/vulkan/icd.d /usr/share/glvnd/egl_vendor.d \
+ && printf '{"file_format_version":"1.0.0","ICD":{"library_path":"libGLX_nvidia.so.0","api_version":"1.3"}}\n' \
+ > /usr/share/vulkan/icd.d/nvidia_icd.json \
+ && printf '{"file_format_version":"1.0.0","ICD":{"library_path":"libEGL_nvidia.so.0"}}\n' \
+ > /usr/share/glvnd/egl_vendor.d/10_nvidia.json
+ENV NVIDIA_VISIBLE_DEVICES=all \
+ NVIDIA_DRIVER_CAPABILITIES=all \
+ CAP_LINUX_GPU_FRAMES=1 \
+ CAP_LINUX_HW_DECODE=cuda \
+ RF_ENCODER=h264_nvenc \
+ RF_NVENC_PRESET=p1 \
+ RF_REQUIRE_GPU=1
+COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun
+COPY --from=engine /out/cap-render-farm /usr/local/bin/cap-render-farm
+WORKDIR /app
+COPY apps/render-farm/src ./src
+CMD ["bun", "/app/src/boot.ts"]
diff --git a/apps/render-farm/Dockerfile.dockerignore b/apps/render-farm/Dockerfile.dockerignore
new file mode 100644
index 000000000..3886a6b91
--- /dev/null
+++ b/apps/render-farm/Dockerfile.dockerignore
@@ -0,0 +1,10 @@
+*
+!Cargo.toml
+!Cargo.lock
+!crates
+!vendor
+!apps/cli
+!apps/desktop/src-tauri
+!apps/render-farm/src
+**/target
+**/node_modules
diff --git a/apps/render-farm/README.md b/apps/render-farm/README.md
new file mode 100644
index 000000000..db517c47f
--- /dev/null
+++ b/apps/render-farm/README.md
@@ -0,0 +1,81 @@
+# Render farm
+
+Server-side Studio export, split across a fleet of NVIDIA GPU workers. An export
+is cut into chunks that render in parallel; each chunk streams playable HLS
+segments while it renders and uploads its share of the final MP4 directly into
+one S3 multipart upload.
+
+- **Coordinator** (`RF_ROLE=coordinator`): plans chunks and audio sections,
+ schedules them fairly across exports, assembles the MP4 header, keeps the HLS
+ playlist, and journals state to S3 so a restart resumes in-flight exports.
+- **Worker** (`RF_ROLE=worker`, one per GPU): runs render slots (`cap-render-farm`
+ engine processes from `crates/render-farm`) and CPU audio lanes.
+
+## How an export flows
+
+1. `POST /jobs {recording, resolution, fps, compression}` indexes the source
+ MP4s (cached per recording), probes the project with the engine, and plans
+ chunks sized by render work (~6 s per chunk) plus a short lead-in chunk so the
+ first HLS segment never waits on a large download.
+2. Workers fetch only the byte ranges their chunk needs into sparse local files,
+ render with frames kept on the GPU end to end (NVDEC → CUDA → Vulkan
+ compositing → CUDA → NVENC), publish 2 s fMP4 segments per finished GOP, and
+ upload the chunk's MP4 bytes as multipart parts.
+3. Audio (Studio Sound) renders in sections split on clip boundaries, on the
+ coordinator's and workers' spare CPU cores.
+4. When every chunk is in, the coordinator writes the `moov` as part 1 and
+ completes the upload. `hlsUrl` is playable within a few seconds of the
+ request; the MP4 is ready when the job reports `ready`.
+
+## Reliability
+
+- Chunks that fail retry with backoff; slow or stuck chunks are hedged on another
+ slot, and a worker-side watchdog kills engines that stop reporting progress.
+- A worker that restarts or stops heartbeating has its tasks requeued; `SIGTERM`
+ drains a worker (finishes running tasks, takes no new ones) before it exits.
+- With the S3 journal a restarted coordinator reloads unfinished jobs and
+ re-attaches chunks that workers are still rendering.
+- `RF_REQUIRE_GPU=1` refuses a chunk whose engine fell back to software decoding
+ or rendering, so it is retried on a healthy engine instead of slowing the job.
+- Finished jobs keep a summary for `RF_JOB_RETENTION_MS`; a job with no progress
+ for `RF_JOB_STALL_MS` fails and releases its upload.
+
+## Deployment
+
+```sh
+docker build -f apps/render-farm/Dockerfile -t cap-render-farm .
+```
+
+Run workers with the NVIDIA container toolkit (`--gpus all`) and `--init`.
+Give the coordinator a bucket-scoped IAM role (or keys), a shared `RF_TOKEN`,
+and a lifecycle rule on the bucket that aborts incomplete multipart uploads and
+expires `hls/` and `jobs/` objects.
+
+| Variable | Default | Role |
+| --- | --- | --- |
+| `RF_ROLE` | `worker` | `coordinator` or `worker` |
+| `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_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 |
+| `RF_CHUNK_WORK_SECONDS` | `6` | Target render work per chunk |
+| `RF_SLOT_MEGAPIXELS_PER_SEC` | `450` | Planning estimate of one slot's throughput |
+| `RF_HLS` / `RF_HLS_SEGMENT_SECONDS` | on / `2` | Progressive HLS output |
+| `RF_LEAD_IN_SECONDS` | `4` | Length of the lead-in chunk |
+| `RF_JOURNAL` | on | Resume unfinished jobs after a coordinator restart |
+| `RF_MAX_ACTIVE_JOBS` | `32` | Further `POST /jobs` get `429` |
+| `RF_JOB_STALL_MS` / `RF_JOB_RETENTION_MS` | 10 min / 1 h | Job watchdog and summary retention |
+| `RF_STALL_MS` | `30000` | Worker engine watchdog |
+| `RF_DRAIN_MS` | 15 min | Longest a `SIGTERM` drain may take |
+| `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 |
+
+## Development
+
+```sh
+bun test apps/render-farm
+bun run --cwd apps/render-farm typecheck
+cargo test -p cap-render-farm
+```
diff --git a/apps/render-farm/package.json b/apps/render-farm/package.json
new file mode 100644
index 000000000..6a9f8bfe7
--- /dev/null
+++ b/apps/render-farm/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@cap/render-farm",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "bun build src/main.ts --target bun --outfile dist/app.js",
+ "start": "bun src/boot.ts",
+ "test": "bun test",
+ "typecheck": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@types/bun": "latest"
+ }
+}
diff --git a/apps/render-farm/src/boot.ts b/apps/render-farm/src/boot.ts
new file mode 100644
index 000000000..5da7a6d4f
--- /dev/null
+++ b/apps/render-farm/src/boot.ts
@@ -0,0 +1,139 @@
+import { chmodSync, mkdirSync, renameSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { S3, s3ConfigFromEnv } from "./s3";
+
+// With RF_HOT_SWAP=1 the engine binary, app bundle and tuning are pulled from
+// the bucket's bin/ pointers and swapped in place when they change (fast fleet
+// iteration). Anyone who can write that prefix can run code on the fleet, so
+// production images run the app and engine they were built with instead.
+const HOT_SWAP = process.env.RF_HOT_SWAP === "1";
+const DRAIN_MS = Number(process.env.RF_DRAIN_MS ?? 15 * 60_000);
+
+const s3 = new S3(s3ConfigFromEnv());
+const DIR = process.env.RF_BIN_DIR ?? "/opt/rf";
+
+type Pointer = { key: string };
+
+async function pointer(name: string) {
+ try {
+ return JSON.parse(
+ new TextDecoder().decode(await s3.get(`bin/${name}.json`)),
+ ) as Pointer;
+ } catch {
+ return null;
+ }
+}
+
+async function download(key: string, path: string, executable: boolean) {
+ const bytes = await s3.get(key);
+ writeFileSync(`${path}.tmp`, bytes);
+ if (executable) chmodSync(`${path}.tmp`, 0o755);
+ renameSync(`${path}.tmp`, path);
+}
+
+let current = "";
+let child: ReturnType<typeof Bun.spawn> | null = null;
+let tuning: Record<string, string> = {};
+let stopping = false;
+
+async function loadTuning() {
+ try {
+ const all = JSON.parse(
+ new TextDecoder().decode(await s3.get("bin/env.json")),
+ ) as Record<string, Record<string, string>>;
+ return { ...(all["*"] ?? {}), ...(all[process.env.RF_ROLE ?? ""] ?? {}) };
+ } catch {
+ return {};
+ }
+}
+
+async function sync() {
+ const [engine, app, nextTuning] = await Promise.all([
+ pointer("engine"),
+ pointer("app"),
+ loadTuning(),
+ ]);
+ if (!engine || !app) return false;
+ const version = `${engine.key}|${app.key}|${JSON.stringify(nextTuning)}`;
+ if (version === current) return false;
+ await Promise.all([
+ download(engine.key, `${DIR}/cap-render-farm`, true),
+ download(app.key, `${DIR}/app.js`, false),
+ ]);
+ current = version;
+ tuning = nextTuning;
+ return true;
+}
+
+function command() {
+ if (HOT_SWAP) {
+ return {
+ argv: ["bun", `${DIR}/app.js`],
+ engine: `${DIR}/cap-render-farm`,
+ };
+ }
+ return {
+ argv: ["bun", fileURLToPath(new URL("./main.ts", import.meta.url))],
+ engine: process.env.RF_ENGINE_BIN ?? "cap-render-farm",
+ };
+}
+
+async function start() {
+ child?.kill();
+ await child?.exited;
+ const { argv, engine } = command();
+ child = Bun.spawn(argv, {
+ stdout: "inherit",
+ stderr: "inherit",
+ env: { ...process.env, ...tuning, RF_ENGINE_BIN: engine },
+ });
+ console.log(`[boot] started ${HOT_SWAP ? current : "bundled app"}`);
+ const started = child;
+ started.exited.then((code) => {
+ console.log(`[boot] app exited ${code}`);
+ if (stopping) process.exit(0);
+ setTimeout(() => {
+ if (child === started) start();
+ }, 2000);
+ });
+}
+
+// Deploys and instance retirement send SIGTERM: pass it on so a worker can
+// finish the chunks it is rendering instead of dropping them mid-export.
+for (const signal of ["SIGTERM", "SIGINT"] as const) {
+ process.on(signal, () => {
+ if (stopping) return;
+ stopping = true;
+ console.log(`[boot] ${signal}: draining`);
+ if (!child) process.exit(0);
+ child.kill(signal);
+ setTimeout(() => {
+ child?.kill("SIGKILL");
+ process.exit(0);
+ }, DRAIN_MS);
+ });
+}
+
+if (HOT_SWAP) {
+ mkdirSync(DIR, { recursive: true });
+ while (
+ !(await sync().catch((error) => {
+ console.error(`[boot] ${error}`);
+ return false;
+ }))
+ ) {
+ console.log("[boot] waiting for bin/engine.json and bin/app.json");
+ await Bun.sleep(5000);
+ }
+ await start();
+ setInterval(async () => {
+ if (stopping) return;
+ try {
+ if (await sync()) await start();
+ } catch (error) {
+ console.error(`[boot] sync failed: ${error}`);
+ }
+ }, 10_000);
+} else {
+ await start();
+}
diff --git a/apps/render-farm/src/boxes.test-util.ts b/apps/render-farm/src/boxes.test-util.ts
new file mode 100644
index 000000000..62a01fda8
--- /dev/null
+++ b/apps/render-farm/src/boxes.test-util.ts
@@ -0,0 +1,81 @@
+export type ParsedBox = {
+ type: string;
+ start: number;
+ size: number;
+ body: Uint8Array;
+};
+
+export function parseBoxes(data: Uint8Array, start = 0, end = data.byteLength) {
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
+ const boxes: ParsedBox[] = [];
+ let offset = start;
+ while (offset + 8 <= end) {
+ let size = view.getUint32(offset);
+ const type = new TextDecoder().decode(
+ data.subarray(offset + 4, offset + 8),
+ );
+ let header = 8;
+ if (size === 1) {
+ size = Number(view.getBigUint64(offset + 8));
+ header = 16;
+ }
+ boxes.push({
+ type,
+ start: offset,
+ size,
+ body: data.subarray(offset + header, Math.min(end, offset + size)),
+ });
+ offset += size;
+ }
+ return boxes;
+}
+
+export function child(box: ParsedBox, type: string, skip = 0) {
+ return parseBoxes(box.body, skip).find((entry) => entry.type === type);
+}
+
+export function u32(bytes: Uint8Array, offset: number) {
+ return new DataView(
+ bytes.buffer,
+ bytes.byteOffset,
+ bytes.byteLength,
+ ).getUint32(offset);
+}
+
+export function u64(bytes: Uint8Array, offset: number) {
+ return Number(
+ new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getBigUint64(
+ offset,
+ ),
+ );
+}
+
+// SPS (High profile) + PPS in Annex B, enough for avcC().
+export const ANNEX_B_PARAMETER_SETS = Uint8Array.of(
+ 0,
+ 0,
+ 0,
+ 1,
+ 0x67,
+ 0x64,
+ 0x00,
+ 0x28,
+ 0xac,
+ 0xd9,
+ 0x40,
+ 0x78,
+ 0x02,
+ 0x27,
+ 0xe5,
+ 0x84,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0x68,
+ 0xeb,
+ 0xe3,
+ 0xcb,
+ 0x22,
+ 0xc0,
+);
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
new file mode 100644
index 000000000..40da7446f
--- /dev/null
+++ b/apps/render-farm/src/coordinator.ts
@@ -0,0 +1,2099 @@
+import { randomUUID, timingSafeEqual } from "node:crypto";
+import { mkdirSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { Engine } from "./engine";
+import { initSegment, playlist } from "./fmp4";
+import { segmentCuts } from "./hls";
+import { type FileSpec, ProjectCache } from "./materialize";
+import {
+ avcC,
+ buildHeader,
+ byteRangeFor,
+ indexVideoTrack,
+ locateMoov,
+ type Run,
+ type TrackIndex,
+} from "./mp4";
+import { planChunkBoundaries } from "./planning";
+import {
+ type AudioResultMeta,
+ type AudioTask,
+ COMPRESSION_BPP,
+ type JobRequest,
+ MIN_PART,
+ type SegmentReport,
+ type Task,
+ type VideoResult,
+ type VideoTask,
+} from "./protocol";
+import { S3, s3ConfigFromEnv } from "./s3";
+import { pickQueued as pickQueuedTask } from "./scheduler";
+import { validateJobRequest } from "./validate";
+
+const s3 = 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);
+const PUBLIC_URL = process.env.RF_COORDINATOR_URL ?? `http://127.0.0.1:${PORT}`;
+const TOKEN = process.env.RF_TOKEN ?? "";
+if (!TOKEN && process.env.RF_ALLOW_NO_TOKEN !== "1") {
+ throw new Error(
+ "RF_TOKEN is required (set RF_ALLOW_NO_TOKEN=1 for local use)",
+ );
+}
+const MAX_ACTIVE_JOBS = Number(process.env.RF_MAX_ACTIVE_JOBS ?? 32);
+// A job whose tasks stop completing (every attempt failing slowly, a lost
+// dependency) would otherwise hold its upload and waiters forever.
+const JOB_STALL_MS = Number(process.env.RF_JOB_STALL_MS ?? 10 * 60_000);
+// Finished jobs stay queryable this long, as a summary without media data.
+const JOB_RETENTION_MS = Number(process.env.RF_JOB_RETENTION_MS ?? 60 * 60_000);
+const SAMPLE_RATE = 48_000;
+const PACKET = 1024;
+
+const probeEngine = new Engine(ENGINE_BIN, {}, "coordinator-engine");
+
+// Audio sections (Studio Sound) are CPU work. These lanes render them on the
+// coordinator's cores, pulling from the same queue as workers' audio lanes.
+const LOCAL_AUDIO_SLOTS = Number(process.env.RF_LOCAL_AUDIO_SLOTS ?? 2);
+// Stores that accept completing with a subset of uploaded parts (AWS S3) give
+// hedge copies their own part range: NVENC output is not bit-identical across
+// GPUs, so a copy overwriting the original's parts would break the header.
+const SPLIT_HEDGE_PARTS = process.env.RF_SPLIT_HEDGE_PARTS !== "0";
+// Progressive playback: chunks stream fMP4 segments while rendering and the
+// coordinator keeps an HLS EVENT playlist of the contiguous prefix, so an
+// export is watchable seconds after the request whatever its length. The
+// flat MP4 is still assembled for download.
+const HLS = process.env.RF_HLS !== "0";
+const HLS_SEGMENT_SECONDS = Number(process.env.RF_HLS_SEGMENT_SECONDS ?? 2);
+/** Unfinished chunks per job (from the front) that outrank other work. */
+const HEAD_CHUNKS = Number(process.env.RF_HEAD_CHUNKS ?? 2);
+const LEAD_IN_SECONDS = Number(process.env.RF_LEAD_IN_SECONDS ?? 4);
+const SLOT_MEGAPIXELS_PER_SEC = Number(
+ process.env.RF_SLOT_MEGAPIXELS_PER_SEC ?? 450,
+);
+const CHUNK_WORK_SECONDS = Number(process.env.RF_CHUNK_WORK_SECONDS ?? 6);
+const audioEngines = Array.from(
+ { length: LOCAL_AUDIO_SLOTS },
+ (_, index) => new Engine(ENGINE_BIN, {}, `audio${index}`),
+);
+const idleAudioEngines = [...audioEngines];
+const localAudioQueue: (() => void)[] = [];
+async function withAudioEngine<T>(fn: (engine: Engine) => Promise<T>) {
+ while (idleAudioEngines.length === 0) {
+ await new Promise<void>((resolve) => localAudioQueue.push(resolve));
+ }
+ let engine = idleAudioEngines.pop() as Engine;
+ if (!engine.alive) engine = new Engine(ENGINE_BIN, {}, engine.label);
+ try {
+ return await fn(engine);
+ } finally {
+ idleAudioEngines.push(engine);
+ localAudioQueue.shift()?.();
+ }
+}
+
+/**
+ * Local audio lanes pull from the shared queue like any fleet audio lane, so
+ * sections spread over the coordinator's cores and the workers' idle CPUs.
+ */
+let localAudioRunning = 0;
+function pumpLocalAudio() {
+ while (localAudioRunning < LOCAL_AUDIO_SLOTS) {
+ const index = pickQueued((kind) => kind === "audio");
+ if (index < 0) return;
+ const state = queue.splice(index, 1)[0] as TaskState;
+ const job = jobs.get(state.task.jobId);
+ if (!job || job.status !== "rendering") continue;
+ state.attempts++;
+ job.t.firstTaskStarted ??= now();
+ localAudioRunning++;
+ runAudioLocally(job, state).finally(() => {
+ localAudioRunning--;
+ pumpLocalAudio();
+ });
+ }
+}
+
+async function runAudioLocally(job: Job, state: TaskState) {
+ const task = state.task;
+ if (task.kind !== "audio") return;
+ state.state = "running";
+ state.startedAt = now();
+ state.worker = "coordinator";
+ try {
+ const started = performance.now();
+ if (!job.audioCache) {
+ job.audioCache = new ProjectCache(s3, join(WORK_DIR, job.id, "audio"));
+ }
+ const cache = job.audioCache;
+ mkdirSync(cache.root, { recursive: true });
+ const fetch = await cache.materialize(task.files);
+ const out = join(cache.root, `a${task.section}.aac`);
+ const engineStarted = performance.now();
+ const result = await withAudioEngine((engine) =>
+ engine.request<{
+ first_packet: number;
+ sizes: number[];
+ extradata: string;
+ timings: Record<string, number>;
+ }>("audio", {
+ project: cache.root,
+ fps: task.fps,
+ section: task.range,
+ preroll: task.preroll,
+ out,
+ }),
+ );
+ const data = new Uint8Array(await Bun.file(out).arrayBuffer());
+ rmSync(out, { force: true });
+ const meta: AudioResultMeta = {
+ taskId: task.taskId,
+ worker: "coordinator",
+ firstPacket: result.first_packet,
+ sizes: result.sizes,
+ extradata: result.extradata,
+ timings: {
+ queuedMs: 0,
+ fetch,
+ engine: result.timings,
+ engineMs: performance.now() - engineStarted,
+ audioWaitMs: 0,
+ uploadMs: 0,
+ totalMs: performance.now() - started,
+ cpuSeconds: 0,
+ },
+ };
+ if (job.status === "rendering") onAudioDone(job, state, meta, data);
+ } catch (error) {
+ if (state.attempts >= 3) failJob(job, error);
+ else
+ setTimeout(() => {
+ state.state = "queued";
+ state.worker = undefined;
+ queue.unshift(state);
+ pumpLocalAudio();
+ dispatch();
+ }, 1000 * state.attempts);
+ }
+}
+
+type Usage = { cpuSeconds: number; memoryBytes: number; at: number };
+
+type Worker = {
+ id: string;
+ slots: number;
+ cpus: number;
+ lastSeen: number;
+ service: string;
+ audioSlots?: number;
+ usage?: Usage | null;
+};
+
+type Section = {
+ index: number;
+ range: [number, number];
+ preroll: number;
+ exact: boolean;
+ packets: [number, number];
+};
+
+type Chunk = {
+ index: number;
+ frames: [number, number];
+ packets: [number, number];
+ files: FileSpec[];
+ firstPart: number;
+ partLimit: number;
+};
+
+type TaskState = {
+ task: Task;
+ state: "queued" | "running" | "done";
+ worker?: string;
+ startedAt?: number;
+ attempts: number;
+ duplicateOf?: string;
+ duplicated?: boolean;
+ /** Reserved by a busy slot ahead of time; not started until it reports progress. */
+ prefetched?: boolean;
+ /**
+ * Resumed after a coordinator restart: a worker may still be running it.
+ * Held back until then so its heartbeat can re-attach it instead of the
+ * chunk being rendered twice.
+ */
+ heldUntil?: number;
+ progress?: { frames: number; total: number; elapsedMs: number; at: number };
+};
+
+type HlsState = {
+ prefix: string;
+ url: string;
+ initUrl?: string;
+ extradata?: string;
+ segments: Map<number, Map<number, SegmentReport>>;
+ listed: { url: string; duration: number }[];
+ cursor: { chunk: number; index: number };
+ writing: boolean;
+ dirty: boolean;
+ ended: boolean;
+};
+
+type Job = {
+ verified?: boolean;
+ /** Summary frozen when the job ends; the job's media data is released then. */
+ final?: ReturnType<typeof summary>;
+ hls?: HlsState;
+ id: string;
+ request: JobRequest;
+ status: "planning" | "rendering" | "assembling" | "ready" | "error";
+ error?: string;
+ key: string;
+ uploadId?: string;
+ t: Record<string, number>;
+ fps: number;
+ bpp: number;
+ resolution: [number, number];
+ totalFrames: number;
+ totalSamples: number;
+ width: number;
+ height: number;
+ chunks: Chunk[];
+ sections: Section[];
+ tasks: Map<string, TaskState>;
+ videoResults: Map<number, VideoResult>;
+ audioSections: Map<number, { meta: AudioResultMeta; data: Uint8Array }>;
+ audioWaiters: (() => void)[];
+ cpuSeconds: number;
+ fetchedBytes: number;
+ workersUsed: Set<string>;
+ url?: string;
+ outputBytes?: number;
+ probe?: Record<string, unknown>;
+ plan?: Record<string, unknown>;
+ waiters: (() => void)[];
+ taskStats: Record<string, unknown>[];
+ audioCache?: ProjectCache;
+};
+
+const workers = new Map<string, Worker>();
+const jobs = new Map<string, Job>();
+const queue: TaskState[] = [];
+type Poller = {
+ worker: string;
+ kinds?: string[];
+ /** A busy slot reserving its next task: queued work only, never a hedge. */
+ prefetch?: boolean;
+ resolve: (task: Task | null) => void;
+};
+const pollers: Poller[] = [];
+const finishedJobs: string[] = [];
+
+function now() {
+ return performance.timeOrigin + performance.now();
+}
+
+function liveSlots() {
+ const cutoff = Date.now() - 30_000;
+ let slots = 0;
+ let audioSlots = 0;
+ let count = 0;
+ for (const worker of workers.values()) {
+ if (worker.lastSeen >= cutoff) {
+ slots += worker.slots;
+ audioSlots += worker.audioSlots ?? 0;
+ count++;
+ }
+ }
+ return { slots, audioSlots, workers: count };
+}
+
+// ---------------------------------------------------------------- planning ---
+
+type Manifest = { files: { path: string; size: number; key?: string }[] };
+
+type RecordingMeta = {
+ segments?: {
+ display: { path: string; start_time?: number };
+ camera?: { path: string; start_time?: number };
+ mic?: { path: string };
+ system_audio?: { path: string };
+ }[];
+ display?: { path: string };
+ camera?: { path: string };
+ audio?: { path: string };
+};
+
+async function mp4MetaRanges(key: string, size: number) {
+ const headEnd = Math.min(size, 128 * 1024);
+ const head = await s3.getRange(key, 0, headEnd - 1);
+ const location = locateMoov(head, size);
+ let moovStart: number;
+ let moovBytes: Uint8Array;
+ if (location && "start" in location && location.start !== undefined) {
+ moovStart = location.start;
+ moovBytes =
+ location.start + location.size <= head.byteLength
+ ? head.subarray(location.start, location.start + location.size)
+ : await s3.getRange(
+ key,
+ location.start,
+ location.start + location.size - 1,
+ );
+ } else if (location && "next" in location && location.next !== undefined) {
+ // Moov after mdat (Cap's recorder): fetch the tail in one request.
+ const tail = await s3.getRange(key, location.next, size - 1);
+ const found = locateMoov(tail, tail.byteLength);
+ if (!found || !("start" in found) || found.start === undefined) {
+ throw new Error(`no moov in ${key}`);
+ }
+ moovStart = location.next + found.start;
+ moovBytes = tail.subarray(found.start, found.start + found.size);
+ } else {
+ throw new Error(`no moov in ${key}`);
+ }
+ return {
+ head: [0, headEnd] as [number, number],
+ moov: [moovStart, moovStart + moovBytes.byteLength] as [number, number],
+ index: indexVideoTrack(moovBytes),
+ };
+}
+
+function mergeRanges(ranges: [number, number][]) {
+ const sorted = ranges
+ .filter(([start, end]) => end > start)
+ .sort((a, b) => a[0] - b[0]);
+ const merged: [number, number][] = [];
+ for (const range of sorted) {
+ const last = merged[merged.length - 1];
+ if (last && range[0] <= last[1] + 256 * 1024)
+ last[1] = Math.max(last[1], range[1]);
+ else merged.push([range[0], range[1]]);
+ }
+ return merged;
+}
+
+type SourceIndex = {
+ manifest: Manifest;
+ recordingMeta: RecordingMeta;
+ mediaMeta: Map<
+ string,
+ {
+ head: [number, number];
+ moov: [number, number];
+ index: TrackIndex;
+ size: number;
+ key: string;
+ }
+ >;
+};
+// Stand-in for an index built once at upload time: recordings are immutable
+// once uploaded, so their moov indexes never need re-reading per export.
+const sourceIndexes = new Map<string, SourceIndex>();
+
+async function sourceIndex(prefix: string): Promise<SourceIndex> {
+ const cached =
+ process.env.RF_INDEX_CACHE !== "0" ? sourceIndexes.get(prefix) : undefined;
+ if (cached) return cached;
+ const manifest = JSON.parse(
+ new TextDecoder().decode(await s3.get(`${prefix}/manifest.json`)),
+ ) as Manifest;
+ const keyOf = (file: { path: string; key?: string }) =>
+ file.key ?? `${prefix}/${file.path}`;
+ const metaFile = manifest.files.find(
+ (file) => file.path === "recording-meta.json",
+ );
+ if (!metaFile) throw new Error("recording has no recording-meta.json");
+ const recordingMeta = JSON.parse(
+ new TextDecoder().decode(await s3.get(keyOf(metaFile))),
+ ) as RecordingMeta;
+ const mediaMeta: SourceIndex["mediaMeta"] = new Map();
+ await Promise.all(
+ manifest.files
+ .filter((file) => file.path.endsWith(".mp4"))
+ .map(async (file) => {
+ const meta = await mp4MetaRanges(keyOf(file), file.size);
+ mediaMeta.set(file.path, {
+ ...meta,
+ size: file.size,
+ key: keyOf(file),
+ });
+ }),
+ );
+ const index = { manifest, recordingMeta, mediaMeta };
+ sourceIndexes.set(prefix, index);
+ if (sourceIndexes.size > 32)
+ sourceIndexes.delete(sourceIndexes.keys().next().value as string);
+ return index;
+}
+
+async function planJob(job: Job) {
+ const request = job.request;
+ const prefix = request.recording.replace(/\/$/, "");
+ const { manifest, recordingMeta, mediaMeta } = await sourceIndex(prefix);
+
+ const keyOf = (file: { path: string; key?: string }) =>
+ file.key ?? `${prefix}/${file.path}`;
+
+ const mediaFiles = manifest.files.filter((file) =>
+ file.path.endsWith(".mp4"),
+ );
+ const audioFiles = manifest.files.filter((file) =>
+ /\.(ogg|m4a|wav|mp3|aac|opus|flac)$/i.test(file.path),
+ );
+ const smallFiles = manifest.files.filter(
+ (file) => !mediaFiles.includes(file) && !audioFiles.includes(file),
+ );
+
+ job.t.indexed = now();
+
+ const baseSpecs = (audioMode: "probe" | "all"): FileSpec[] => [
+ ...smallFiles.map((file) => ({
+ path: file.path,
+ key: keyOf(file),
+ size: file.size,
+ ranges: "all" as const,
+ })),
+ ...audioFiles.map((file) => ({
+ path: file.path,
+ key: keyOf(file),
+ size: file.size,
+ ranges:
+ audioMode === "all"
+ ? ("all" as const)
+ : mergeRanges([
+ [0, Math.min(file.size, 256 * 1024)],
+ [Math.max(0, file.size - 256 * 1024), file.size],
+ ]),
+ })),
+ ];
+ const mediaSpec = (path: string, extra: [number, number][]): FileSpec => {
+ const meta = mediaMeta.get(path);
+ if (!meta) throw new Error(`no index for ${path}`);
+ return {
+ path,
+ key: meta.key,
+ size: meta.size,
+ ranges: mergeRanges([meta.head, meta.moov, ...extra]),
+ };
+ };
+
+ const probeDir = join(WORK_DIR, job.id);
+ mkdirSync(probeDir, { recursive: true });
+ const cache = new ProjectCache(s3, probeDir);
+ await cache.materialize([
+ ...baseSpecs("probe"),
+ ...mediaFiles.map((file) => mediaSpec(file.path, [])),
+ ]);
+ job.t.materialized = now();
+
+ const gop = job.fps * 2;
+ type Probe = {
+ total_frames: number;
+ total_samples: number;
+ width: number;
+ height: number;
+ span_step: number;
+ spans: { clip: number; start: number; end: number }[][];
+ audio_cuts: number[];
+ clips: { index: number; camera: number; mic: number }[];
+ };
+ const probe = await probeEngine.request<Probe>("probe", {
+ project: probeDir,
+ fps: job.fps,
+ resolution: job.resolution,
+ span_step: gop,
+ });
+ cache.close();
+ job.t.probed = now();
+ if (request.frameLimit && request.frameLimit < probe.total_frames) {
+ probe.total_frames = request.frameLimit;
+ probe.total_samples = Math.round(
+ (request.frameLimit * SAMPLE_RATE) / job.fps,
+ );
+ }
+ job.totalFrames = probe.total_frames;
+ job.totalSamples = probe.total_samples;
+ job.width = probe.width;
+ job.height = probe.height;
+ job.probe = {
+ totalFrames: probe.total_frames,
+ width: probe.width,
+ height: probe.height,
+ audioCuts: probe.audio_cuts.length,
+ };
+
+ // Which media files belong to which recording clip.
+ const clipMedia: { display?: string; camera?: string; offset: number }[] = [];
+ const segments: NonNullable<RecordingMeta["segments"]> =
+ recordingMeta.segments ?? [
+ {
+ display: recordingMeta.display ?? { path: "" },
+ camera: recordingMeta.camera,
+ },
+ ];
+ segments.forEach((segment, index) => {
+ const cameraOffset =
+ probe.clips.find((clip) => clip.index === index)?.camera ?? 0;
+ const starts = [
+ segment.display.start_time ?? 0,
+ segment.camera?.start_time ?? 0,
+ ];
+ clipMedia[index] = {
+ display: segment.display.path,
+ camera: segment.camera?.path,
+ offset:
+ Math.abs(cameraOffset) + Math.max(...starts) - Math.min(...starts),
+ };
+ });
+
+ // ---- video chunks
+ const { slots } = liveSlots();
+ const minChunkFrames = Math.max(
+ 1,
+ Math.round((request.minChunkSeconds ?? 1) * job.fps),
+ );
+ // Chunks are sized by render work, not video length, so 4K gets shorter
+ // chunks than 1080p. ~6 s of work per chunk measured the same single-job
+ // speed as 12 s while freeing slots twice as often for exports that arrive
+ // during a long one.
+ const megapixels = (probe.width * probe.height) / 1e6;
+ const slotFps = SLOT_MEGAPIXELS_PER_SEC / megapixels;
+ const targetFrames = Math.max(
+ minChunkFrames,
+ Math.round(slotFps * (request.chunkWorkSeconds ?? CHUNK_WORK_SECONDS)),
+ );
+ const boundaries = planChunkBoundaries({
+ totalFrames: probe.total_frames,
+ fps: job.fps,
+ slots,
+ targetFrames,
+ minChunkFrames,
+ chunks: request.chunks,
+ chunksPerSlot: request.chunksPerSlot,
+ maxChunks: request.maxChunks,
+ leadInFrames: job.hls ? LEAD_IN_SECONDS * job.fps : 0,
+ });
+ const chunkCount = boundaries.length - 1;
+ const partsPerChunk = Math.floor(9998 / chunkCount);
+ if (partsPerChunk < (SPLIT_HEDGE_PARTS ? 8 : 4)) {
+ throw new Error("too many chunks for one multipart upload");
+ }
+ const partLimit = SPLIT_HEDGE_PARTS
+ ? Math.floor(partsPerChunk / 2)
+ : partsPerChunk;
+ const samplesPerFrame = SAMPLE_RATE / job.fps;
+ const totalPackets = Math.ceil(probe.total_samples / PACKET) + 1;
+ const packetAt = (frame: number, isStart: boolean, isEnd: boolean) => {
+ if (isStart) return 0;
+ if (isEnd) return totalPackets;
+ return Math.ceil((frame * samplesPerFrame) / PACKET) + 1;
+ };
+ const margin = 2;
+ job.chunks = [];
+ for (let index = 0; index < chunkCount; index++) {
+ const f0 = boundaries[index] ?? 0;
+ const f1 = boundaries[index + 1] ?? probe.total_frames;
+ const perFile = new Map<string, [number, number][]>();
+ for (let step = Math.floor(f0 / gop); step < Math.ceil(f1 / gop); step++) {
+ for (const span of probe.spans[step] ?? []) {
+ const media = clipMedia[span.clip];
+ if (!media) continue;
+ const pad = margin + media.offset;
+ for (const path of [media.display, media.camera]) {
+ if (!path) continue;
+ const meta = mediaMeta.get(path);
+ if (!meta) continue;
+ const range = byteRangeFor(
+ meta.index,
+ span.start - pad,
+ span.end + pad,
+ );
+ if (!range) continue;
+ const list = perFile.get(path) ?? [];
+ list.push([range.start, range.end]);
+ perFile.set(path, list);
+ }
+ }
+ }
+ job.chunks.push({
+ index,
+ frames: [f0, f1],
+ packets: [
+ packetAt(f0, index === 0, false),
+ packetAt(f1, false, index === chunkCount - 1),
+ ],
+ files: [
+ ...baseSpecs("probe"),
+ ...mediaFiles.map((file) =>
+ mediaSpec(file.path, perFile.get(file.path) ?? []),
+ ),
+ ],
+ firstPart: 2 + index * partsPerChunk,
+ partLimit,
+ });
+ }
+
+ // ---- audio sections, split on clip boundaries where Studio Sound resets
+ const hasAudio = audioFiles.length > 0 && !request.frameLimit;
+ job.sections = [];
+ if (hasAudio) {
+ const total = probe.total_samples;
+ // One wave of sections across whoever renders audio (the coordinator's
+ // local slots, or the fleet).
+ const fleetAudio = liveSlots().audioSlots;
+ const audioLanes =
+ LOCAL_AUDIO_SLOTS + fleetAudio > 0
+ ? LOCAL_AUDIO_SLOTS + fleetAudio
+ : Math.max(8, slots);
+ const target = Math.max(
+ 20 * SAMPLE_RATE,
+ Math.ceil(total / Math.min(64, audioLanes)),
+ );
+ const cuts = probe.audio_cuts;
+ let start = 0;
+ let preroll = 0;
+ let exact = true;
+ // With HLS the first segment waits on section 0's audio: keep it short
+ // so playback can start well before the long sections finish.
+ const firstTarget = job.hls ? Math.min(target, 6 * SAMPLE_RATE) : target;
+ while (start < total) {
+ const size = job.sections.length === 0 ? firstTarget : target;
+ const ideal = start + size;
+ if (ideal >= total - size / 2) {
+ job.sections.push({
+ index: job.sections.length,
+ range: [start, total],
+ preroll,
+ exact,
+ packets: [start === 0 ? 0 : (start + PACKET) / PACKET, totalPackets],
+ });
+ break;
+ }
+ const cut = cuts.find(
+ (value) => value >= ideal - size / 2 && value <= ideal + size / 2,
+ );
+ let end: number;
+ let nextPreroll: number;
+ let nextExact: boolean;
+ if (cut !== undefined) {
+ end = Math.ceil((cut + PACKET) / PACKET) * PACKET;
+ const inputStart = Math.max(
+ 0,
+ Math.floor((cut - 2 * SAMPLE_RATE) / PACKET) * PACKET,
+ );
+ nextPreroll = end - inputStart;
+ nextExact = true;
+ } else {
+ end = Math.floor(ideal / PACKET) * PACKET;
+ nextPreroll = Math.min(
+ end,
+ Math.floor((10 * SAMPLE_RATE) / PACKET) * PACKET,
+ );
+ nextExact = false;
+ }
+ job.sections.push({
+ index: job.sections.length,
+ range: [start, end],
+ preroll,
+ exact,
+ packets: [
+ start === 0 ? 0 : (start + PACKET) / PACKET,
+ (end + PACKET) / PACKET,
+ ],
+ });
+ start = end;
+ preroll = nextPreroll;
+ exact = nextExact;
+ }
+ }
+
+ job.uploadId = await s3.createMultipart(job.key, "video/mp4");
+ job.t.planned = now();
+
+ const bitrate =
+ job.width * job.height * (30 + Math.max(0, job.fps - 30) * 0.6) * job.bpp;
+ // Sized for the largest chunk, with 2.5x headroom for bitrate peaks.
+ const largestChunkFrames = Math.max(
+ ...job.chunks.map((chunk) => chunk.frames[1] - chunk.frames[0]),
+ );
+ const largestChunkBytes = (bitrate / 8) * (largestChunkFrames / job.fps);
+ const partTarget = Math.max(
+ 16 << 20,
+ Math.ceil((largestChunkBytes * 2.5) / Math.max(1, partLimit - 2)),
+ );
+ job.plan = {
+ chunks: chunkCount,
+ sections: job.sections.length,
+ exactSeams: job.sections.filter((section) => section.exact).length,
+ slots,
+ partsPerChunk,
+ partTarget,
+ sourceBytesPerChunk: Math.round(
+ job.chunks.reduce(
+ (sum, chunk) =>
+ sum +
+ chunk.files.reduce(
+ (fileSum, file) =>
+ fileSum +
+ (file.ranges === "all"
+ ? file.size
+ : file.ranges.reduce((r, [a, b]) => r + b - a, 0)),
+ 0,
+ ),
+ 0,
+ ) / chunkCount,
+ ),
+ };
+
+ for (const section of job.sections) {
+ const task: AudioTask = {
+ kind: "audio",
+ taskId: `${job.id}:a${section.index}`,
+ jobId: job.id,
+ section: section.index,
+ fps: job.fps,
+ range: section.range,
+ preroll: section.preroll,
+ files: [
+ ...baseSpecs("all"),
+ ...mediaFiles.map((file) => mediaSpec(file.path, [])),
+ ],
+ };
+ enqueue(job, task);
+ }
+ for (const chunk of job.chunks) {
+ const task: VideoTask = {
+ kind: "video",
+ taskId: `${job.id}:v${chunk.index}`,
+ jobId: job.id,
+ chunk: chunk.index,
+ fps: job.fps,
+ resolution: job.resolution,
+ bpp: job.bpp,
+ frames: chunk.frames,
+ threads: 8,
+ files: chunk.files,
+ upload: {
+ key: job.key,
+ uploadId: job.uploadId,
+ firstPart: chunk.firstPart,
+ partLimit: chunk.partLimit,
+ partTarget,
+ isLast: chunk.index === job.chunks.length - 1,
+ },
+ audio: hasAudio
+ ? {
+ first: chunk.packets[0],
+ end: chunk.packets[1],
+ coordinator: PUBLIC_URL,
+ }
+ : null,
+ hls: job.hls
+ ? {
+ prefix: job.hls.prefix,
+ segmentFrames: Math.round(job.fps * HLS_SEGMENT_SECONDS),
+ }
+ : null,
+ };
+ enqueue(job, task);
+ }
+ job.status = "rendering";
+ journalJob(job);
+ dispatch();
+}
+
+// ----------------------------------------------------------------- journal ---
+// With RF_JOURNAL=1 a coordinator restart (crash, deploy) resumes in-flight
+// exports instead of losing them: the plan is written before dispatch, each
+// accepted chunk/audio result as it lands, and a marker when the job ends.
+// On boot, unfinished jobs are rebuilt and only their missing work re-queued;
+// the multipart upload and every uploaded part are reused.
+
+const JOURNAL = process.env.RF_JOURNAL !== "0";
+// Workers heartbeat every 3 s; this is enough for all of them to report in.
+const RESUME_HOLD_MS = 10_000;
+const journalKey = (id: string, name: string) => `jobs/${id}/${name}`;
+
+function journalPut(key: string, body: Uint8Array | string) {
+ if (!JOURNAL) return;
+ s3.put(key, body).catch((error) => console.error(`journal ${key}: ${error}`));
+}
+
+type JournaledJob = Pick<
+ Job,
+ | "id"
+ | "request"
+ | "key"
+ | "uploadId"
+ | "t"
+ | "fps"
+ | "bpp"
+ | "resolution"
+ | "totalFrames"
+ | "totalSamples"
+ | "width"
+ | "height"
+ | "chunks"
+ | "sections"
+ | "plan"
+ | "probe"
+> & { tasks: Task[]; hls: { prefix: string } | null };
+
+function journalJob(job: Job) {
+ const record: JournaledJob = {
+ id: job.id,
+ request: job.request,
+ key: job.key,
+ uploadId: job.uploadId,
+ t: job.t,
+ fps: job.fps,
+ bpp: job.bpp,
+ resolution: job.resolution,
+ totalFrames: job.totalFrames,
+ totalSamples: job.totalSamples,
+ width: job.width,
+ height: job.height,
+ chunks: job.chunks,
+ sections: job.sections,
+ plan: job.plan,
+ probe: job.probe,
+ tasks: [...job.tasks.values()]
+ .filter((state) => !state.duplicateOf)
+ .map((state) => state.task),
+ hls: job.hls ? { prefix: job.hls.prefix } : null,
+ };
+ journalPut(journalKey(job.id, "job.json"), JSON.stringify(record));
+}
+
+function audioFrame(meta: AudioResultMeta, data: Uint8Array) {
+ const json = new TextEncoder().encode(JSON.stringify(meta));
+ const body = new Uint8Array(4 + json.byteLength + data.byteLength);
+ new DataView(body.buffer).setUint32(0, json.byteLength);
+ body.set(json, 4);
+ body.set(data, 4 + json.byteLength);
+ return body;
+}
+
+function newHlsState(prefix: string): HlsState {
+ return {
+ prefix,
+ url: s3.presign("GET", `${prefix}/index.m3u8`, 6 * 3600),
+ segments: new Map(),
+ listed: [],
+ cursor: { chunk: 0, index: 0 },
+ writing: false,
+ dirty: false,
+ ended: false,
+ };
+}
+
+/**
+ * The segments a worker published for a finished chunk, re-derived from its
+ * keyframes with the worker's own cut rule (a segment closes at the first
+ * GOP boundary at or past `segmentFrames`), so the playlist can be rebuilt.
+ */
+function segmentsFromResult(
+ job: Job,
+ chunk: Chunk,
+ result: VideoResult,
+): SegmentReport[] {
+ if (!job.hls) return [];
+ const cuts = segmentCuts(
+ result.keyframes,
+ result.sizes.length,
+ Math.round(job.fps * HLS_SEGMENT_SECONDS),
+ );
+ return cuts.map(([a, b], index) => ({
+ chunk: chunk.index,
+ index,
+ frames: [chunk.frames[0] + a, chunk.frames[0] + b],
+ key: `${job.hls?.prefix}/c${chunk.index}-${index}.m4s`,
+ last: index === cuts.length - 1,
+ extradata: result.extradata,
+ }));
+}
+
+async function resumeJobs() {
+ if (!JOURNAL) return;
+ const keys = await s3.list("jobs/");
+ const byJob = new Map<string, Set<string>>();
+ for (const { key } of keys) {
+ const [, id, ...rest] = key.split("/");
+ if (!id) continue;
+ const names = byJob.get(id) ?? new Set<string>();
+ names.add(rest.join("/"));
+ byJob.set(id, names);
+ }
+ for (const [id, names] of byJob) {
+ if (names.has("done") || !names.has("job.json") || jobs.has(id)) continue;
+ try {
+ const record = JSON.parse(
+ new TextDecoder().decode(await s3.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) {
+ journalPut(journalKey(id, "done"), "expired");
+ continue;
+ }
+ const job: Job = {
+ ...record,
+ status: "rendering",
+ tasks: new Map(),
+ videoResults: new Map(),
+ audioSections: new Map(),
+ audioWaiters: [],
+ cpuSeconds: 0,
+ fetchedBytes: 0,
+ workersUsed: new Set(),
+ waiters: [],
+ taskStats: [],
+ hls: record.hls ? newHlsState(record.hls.prefix) : undefined,
+ };
+ job.t.resumed = now();
+ for (const name of names) {
+ const video = name.match(/^v\/(\d+)\.json$/);
+ if (video) {
+ const result = JSON.parse(
+ new TextDecoder().decode(await s3.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 length = new DataView(bytes.buffer, bytes.byteOffset).getUint32(
+ 0,
+ );
+ const meta = JSON.parse(
+ new TextDecoder().decode(bytes.subarray(4, 4 + length)),
+ ) as AudioResultMeta;
+ job.audioSections.set(Number(audio[1]), {
+ meta,
+ data: bytes.slice(4 + length),
+ });
+ }
+ }
+ jobs.set(id, job);
+ let requeued = 0;
+ for (const task of record.tasks) {
+ const done =
+ task.kind === "video"
+ ? job.videoResults.has(task.chunk)
+ : job.audioSections.has(task.section);
+ const state: TaskState = {
+ task,
+ state: done ? "done" : "queued",
+ attempts: 0,
+ heldUntil: done ? undefined : Date.now() + RESUME_HOLD_MS,
+ };
+ job.tasks.set(task.taskId, state);
+ if (!done) {
+ queue.push(state);
+ requeued++;
+ }
+ }
+ if (job.hls) {
+ for (const chunk of job.chunks) {
+ const result = job.videoResults.get(chunk.index);
+ if (!result) continue;
+ job.hls.extradata ??= result.extradata;
+ job.hls.segments.set(
+ chunk.index,
+ new Map(
+ segmentsFromResult(job, chunk, result).map((segment) => [
+ segment.index,
+ segment,
+ ]),
+ ),
+ );
+ }
+ publishPlaylist(job);
+ }
+ console.log(
+ `resumed job ${id}: ${job.videoResults.size}/${job.chunks.length} chunks, ${job.audioSections.size}/${job.sections.length} audio done, ${requeued} tasks held for re-attach`,
+ );
+ setTimeout(dispatch, RESUME_HOLD_MS + 50);
+ if (audioReady(job)) job.t.audioDone ??= now();
+ if (job.videoResults.size === job.chunks.length)
+ job.t.videoDone ??= now();
+ maybeAssemble(job);
+ } catch (error) {
+ console.error(`resume ${id} failed: ${error}`);
+ }
+ }
+ dispatch();
+}
+
+// ---------------------------------------------------------------- dispatch ---
+
+function enqueue(job: Job, task: Task, duplicateOf?: string) {
+ const state: TaskState = { task, state: "queued", attempts: 0, duplicateOf };
+ job.tasks.set(task.taskId, state);
+ queue.push(state);
+}
+
+function pickQueued(accepts: (kind: string) => boolean) {
+ const schedulable = [...jobs.values()].map((job) => {
+ let runningTasks = 0;
+ for (const state of job.tasks.values()) {
+ if (state.state === "running") runningTasks++;
+ }
+ return {
+ id: job.id,
+ status: job.status,
+ requestedAt: job.t.requested ?? 0,
+ chunks: job.chunks.map((chunk) => chunk.index),
+ finishedChunks: job.videoResults,
+ runningTasks,
+ };
+ });
+ return pickQueuedTask(queue, schedulable, accepts, {
+ headChunks: HEAD_CHUNKS,
+ fifo: process.env.RF_SCHEDULER === "fifo",
+ now: Date.now(),
+ });
+}
+
+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);
+ const next = pickQueued(accepts);
+ let state: TaskState | undefined;
+ if (next >= 0) {
+ state = queue.splice(next, 1)[0];
+ } else if (accepts("video") && !poller.prefetch) {
+ state = straggler();
+ }
+ if (!state) {
+ p++;
+ continue;
+ }
+ pollers.splice(p, 1);
+ state.prefetched = poller.prefetch;
+ state.progress = undefined;
+ state.state = "running";
+ state.worker = poller.worker;
+ state.startedAt = now();
+ state.attempts++;
+ const job = jobs.get(state.task.jobId);
+ if (job) {
+ job.t.firstTaskStarted ??= now();
+ if (state.task.kind === "video") job.t.firstVideoStarted ??= now();
+ job.workersUsed.add(poller.worker);
+ }
+ poller.resolve(state.task);
+ }
+}
+
+/**
+ * Speculative execution: once the queue has drained, hedge the running chunk
+ * whose projected finish is furthest behind what a fresh slot could do. Slow
+ * replicas (noisy neighbours) otherwise set the whole export's tail.
+ */
+function straggler(): TaskState | undefined {
+ let best: { state: TaskState; gain: number } | undefined;
+ for (const job of jobs.values()) {
+ if (job.status !== "rendering" || job.request.duplicateStragglers === false)
+ continue;
+ const rates = job.taskStats
+ .filter(
+ (stat) => stat.kind === "video" && Number(stat.engineRenderMs) > 0,
+ )
+ .map((stat) => Number(stat.frames) / Number(stat.engineRenderMs));
+ for (const state of job.tasks.values()) {
+ if (state.state !== "running" || state.task.kind !== "video") continue;
+ const frames = state.progress?.frames ?? 0;
+ if (frames > 0)
+ rates.push(frames / Math.max(1, state.progress?.elapsedMs ?? 1));
+ }
+ if (rates.length < 3) continue;
+ rates.sort((a, b) => a - b);
+ const typicalRate = rates[Math.floor(rates.length / 2)] ?? 0;
+ if (typicalRate <= 0) continue;
+ for (const state of job.tasks.values()) {
+ if (
+ state.task.kind !== "video" ||
+ state.state !== "running" ||
+ state.duplicated ||
+ state.duplicateOf ||
+ (state.prefetched && !state.progress) ||
+ job.videoResults.has(state.task.chunk)
+ ) {
+ continue;
+ }
+ const total = state.task.frames[1] - state.task.frames[0];
+ const elapsed =
+ state.progress?.elapsedMs ?? now() - (state.startedAt ?? now());
+ const frames = state.progress?.frames ?? 0;
+ const expected = total / typicalRate + 2500;
+ // A copy with no frames long past its expected time is stuck (not
+ // merely slow): its remaining time is unknown, so always hedge it.
+ const remaining =
+ frames > 0
+ ? ((total - frames) * (state.progress?.elapsedMs ?? elapsed)) / frames
+ : elapsed > expected * 2
+ ? Number.POSITIVE_INFINITY
+ : Math.max(0, expected - elapsed) * 2;
+ const fresh = 2500 + total / typicalRate;
+ const gain = remaining - fresh;
+ if (gain > 3000 && (!best || gain > best.gain)) best = { state, gain };
+ }
+ }
+ if (!best || best.state.task.kind !== "video") return undefined;
+ best.state.duplicated = true;
+ const job = jobs.get(best.state.task.jobId);
+ if (!job) return undefined;
+ // Without RF_SPLIT_HEDGE_PARTS the copy reuses the original's part numbers,
+ // which stores that reject completions omitting uploaded parts require. That
+ // is only safe when both copies produce identical bytes (x264 with pinned
+ // threads); NVENC output differs across GPUs, so NVENC fleets need the split.
+ const original = best.state.task;
+ const task: VideoTask = {
+ ...original,
+ taskId: `${original.taskId}:dup`,
+ upload: SPLIT_HEDGE_PARTS
+ ? {
+ ...original.upload,
+ firstPart: original.upload.firstPart + original.upload.partLimit,
+ }
+ : original.upload,
+ };
+ const state: TaskState = {
+ task,
+ state: "queued",
+ attempts: 0,
+ duplicateOf: best.state.task.taskId,
+ };
+ job.tasks.set(task.taskId, state);
+ return state;
+}
+
+/** Running tasks whose result is already in (hedge losers) or whose job ended. */
+function cancellations(worker: string) {
+ const out: string[] = [];
+ for (const job of jobs.values()) {
+ const ended = job.status !== "rendering";
+ if (ended && Date.now() - (job.t.ready ?? job.t.failed ?? now()) > 120_000)
+ continue;
+ for (const state of job.tasks.values()) {
+ if (state.state !== "running" || state.worker !== worker) continue;
+ if (
+ ended ||
+ (state.task.kind === "video" && job.videoResults.has(state.task.chunk))
+ ) {
+ out.push(state.task.taskId);
+ }
+ }
+ }
+ return out;
+}
+
+/**
+ * A worker process restarted on the same host (crash, app hot-swap): its old
+ * id is dead, so hand its tasks back now instead of waiting for the timeout.
+ */
+function supersede(id: string) {
+ const host = id.slice(0, id.lastIndexOf("-"));
+ for (const old of [...workers.keys()]) {
+ if (old === id || old.slice(0, old.lastIndexOf("-")) !== host) continue;
+ workers.delete(old);
+ for (const job of jobs.values()) {
+ if (job.status !== "rendering") continue;
+ for (const state of job.tasks.values()) {
+ if (state.state !== "running" || state.worker !== old) continue;
+ console.warn(`requeue ${state.task.taskId}: worker ${old} restarted`);
+ state.state = "queued";
+ state.worker = undefined;
+ queue.unshift(state);
+ }
+ }
+ }
+}
+
+setInterval(() => {
+ // Requeue work held by workers that stopped heartbeating (they beat every
+ // 3 s). Local audio lanes run in this process and never heartbeat.
+ const cutoff = Date.now() - 12_000;
+ for (const job of jobs.values()) {
+ if (job.status !== "rendering") continue;
+ const lastProgress = job.t.lastProgress ?? job.t.planned ?? now();
+ if (now() - lastProgress > JOB_STALL_MS) {
+ failJob(
+ job,
+ new Error(
+ `no progress for ${Math.round((now() - lastProgress) / 1000)} s`,
+ ),
+ );
+ continue;
+ }
+ for (const state of job.tasks.values()) {
+ if (
+ state.state !== "running" ||
+ !state.worker ||
+ state.worker === "coordinator"
+ )
+ continue;
+ const worker = workers.get(state.worker);
+ if (worker && worker.lastSeen >= cutoff) continue;
+ console.warn(
+ `requeue ${state.task.taskId}: worker ${state.worker} went away`,
+ );
+ state.state = "queued";
+ state.worker = undefined;
+ queue.unshift(state);
+ }
+ }
+ dispatch();
+}, 5_000);
+
+// ---------------------------------------------------------------- results ---
+
+function failJob(job: Job, error: unknown) {
+ if (job.status === "error" || job.status === "ready") return;
+ job.status = "error";
+ job.error = error instanceof Error ? error.message : String(error);
+ job.t.failed = now();
+ console.error(`job ${job.id} failed: ${job.error}`);
+ for (const state of job.tasks.values()) {
+ const index = queue.indexOf(state);
+ if (index >= 0) queue.splice(index, 1);
+ }
+ if (job.uploadId) s3.abortMultipart(job.key, job.uploadId).catch(() => {});
+ finish(job);
+}
+
+async function writeInit(job: Job, hls: HlsState) {
+ if (!hls.extradata) return false;
+ let asc: Uint8Array | null = null;
+ if (job.sections.length > 0) {
+ const section = job.audioSections.values().next().value;
+ if (!section) return false;
+ asc = Buffer.from(section.meta.extradata, "base64");
+ }
+ const key = `${hls.prefix}/init.mp4`;
+ await s3.put(
+ key,
+ initSegment({
+ width: job.width,
+ height: job.height,
+ fps: job.fps,
+ avcC: avcC(Buffer.from(hls.extradata, "base64")),
+ asc,
+ }),
+ "video/mp4",
+ );
+ hls.initUrl = s3.presign("GET", key, 6 * 3600);
+ return true;
+}
+
+/** Rewrites the playlist whenever the contiguous run of segments grows. */
+async function publishPlaylist(job: Job) {
+ const hls = job.hls;
+ if (!hls || hls.ended) return;
+ if (hls.writing) {
+ hls.dirty = true;
+ return;
+ }
+ hls.writing = true;
+ try {
+ do {
+ hls.dirty = false;
+ if (!hls.initUrl && !(await writeInit(job, hls))) return;
+ let grew = false;
+ for (;;) {
+ const segment = hls.segments
+ .get(hls.cursor.chunk)
+ ?.get(hls.cursor.index);
+ if (!segment) break;
+ hls.listed.push({
+ url: s3.presign("GET", segment.key, 6 * 3600),
+ duration: (segment.frames[1] - segment.frames[0]) / job.fps,
+ });
+ grew = true;
+ hls.cursor = segment.last
+ ? { chunk: hls.cursor.chunk + 1, index: 0 }
+ : { chunk: hls.cursor.chunk, index: hls.cursor.index + 1 };
+ }
+ const ended = hls.cursor.chunk >= job.chunks.length;
+ if (!grew && !ended) continue;
+ await s3.put(
+ `${hls.prefix}/index.m3u8`,
+ playlist(hls.listed, {
+ initUrl: hls.initUrl as string,
+ targetDuration: HLS_SEGMENT_SECONDS + 2,
+ ended,
+ }),
+ "application/vnd.apple.mpegurl",
+ );
+ if (hls.listed.length > 0) job.t.firstSegment ??= now();
+ if (ended) {
+ hls.ended = true;
+ job.t.hlsEnded = now();
+ }
+ } while (hls.dirty && !hls.ended);
+ } catch (error) {
+ console.error(`job ${job.id} playlist: ${error}`);
+ } finally {
+ hls.writing = false;
+ }
+}
+
+function finish(job: Job) {
+ journalPut(journalKey(job.id, "done"), job.status);
+ 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.
+ job.final = summary(job);
+ job.audioSections.clear();
+ job.videoResults.clear();
+ job.taskStats = [];
+ for (const [taskId, state] of job.tasks) {
+ const index = queue.indexOf(state);
+ if (index >= 0) queue.splice(index, 1);
+ // Running copies stay so their workers are told to cancel them.
+ if (state.state !== "running") job.tasks.delete(taskId);
+ }
+ setTimeout(() => jobs.delete(job.id), JOB_RETENTION_MS).unref();
+ for (const waiter of job.waiters.splice(0)) waiter();
+ for (const waiter of job.audioWaiters.splice(0)) waiter();
+ finishedJobs.push(job.id);
+ if (finishedJobs.length > 50) finishedJobs.shift();
+ rmSync(join(WORK_DIR, job.id), { recursive: true, force: true });
+}
+
+function recordStat(
+ job: Job,
+ kind: string,
+ index: number,
+ worker: string,
+ timings: object,
+) {
+ job.taskStats.push({ kind, index, worker, ...timings });
+}
+
+function onVideoDone(job: Job, state: TaskState, result: VideoResult) {
+ if (state.task.kind !== "video") return;
+ state.state = "done";
+ const chunk = state.task.chunk;
+ recordStat(job, "video", chunk, result.worker, {
+ ...result.timings,
+ fetchBytes: result.timings.fetch.bytes,
+ fetchMs: result.timings.fetch.ms,
+ engineRenderMs: result.timings.engine.render_ms,
+ frames: result.sizes.length,
+ bytes: result.bytes,
+ duplicate: Boolean(state.duplicateOf),
+ });
+ job.cpuSeconds += result.timings.cpuSeconds;
+ job.fetchedBytes += result.timings.fetch.bytes;
+ if (job.videoResults.has(chunk)) return;
+ for (const other of job.tasks.values()) {
+ // The sibling copy (original or hedge) is now redundant.
+ if (
+ other !== state &&
+ other.task.kind === "video" &&
+ other.task.chunk === chunk &&
+ other.state === "queued"
+ ) {
+ other.state = "done";
+ const index = queue.indexOf(other);
+ if (index >= 0) queue.splice(index, 1);
+ }
+ }
+ job.videoResults.set(chunk, result);
+ job.t.lastProgress = now();
+ journalPut(journalKey(job.id, `v/${chunk}.json`), JSON.stringify(result));
+ if (job.videoResults.size === job.chunks.length) {
+ job.t.videoDone = now();
+ maybeAssemble(job);
+ }
+}
+
+function onAudioDone(
+ job: Job,
+ state: TaskState,
+ meta: AudioResultMeta,
+ data: Uint8Array,
+) {
+ if (state.task.kind !== "audio") return;
+ state.state = "done";
+ if (!job.audioSections.has(state.task.section)) {
+ journalPut(
+ journalKey(job.id, `a/${state.task.section}.bin`),
+ audioFrame(meta, data),
+ );
+ }
+ job.audioSections.set(state.task.section, { meta, data });
+ job.t.lastProgress = now();
+ if (job.hls && !job.hls.initUrl) publishPlaylist(job);
+ recordStat(job, "audio", state.task.section, meta.worker, {
+ ...meta.timings,
+ fetchMs: meta.timings.fetch.ms,
+ fetchBytes: meta.timings.fetch.bytes,
+ });
+ job.cpuSeconds += meta.timings.cpuSeconds;
+ job.fetchedBytes += meta.timings.fetch.bytes;
+ if (audioReady(job)) job.t.audioDone = now();
+ for (const waiter of job.audioWaiters.splice(0)) waiter();
+ if (audioReady(job)) maybeAssemble(job);
+}
+
+function audioReady(job: Job) {
+ return job.audioSections.size === job.sections.length;
+}
+
+function maybeAssemble(job: Job) {
+ if (job.status !== "rendering") return;
+ if (job.videoResults.size !== job.chunks.length || !audioReady(job)) return;
+ job.status = "assembling";
+ assemble(job).catch((error) => failJob(job, error));
+}
+
+async function assemble(job: Job) {
+ const results = job.chunks.map((chunk) => {
+ const result = job.videoResults.get(chunk.index);
+ if (!result) throw new Error(`missing chunk ${chunk.index}`);
+ return result;
+ });
+ const extradata = results[0]?.extradata ?? "";
+ for (const result of results) {
+ if (result.extradata !== extradata) {
+ throw new Error("chunks disagree on SPS/PPS; cannot join them");
+ }
+ }
+ const sizes = new Uint32Array(job.totalFrames);
+ const keyframes: number[] = [];
+ const videoRuns: Run[] = [];
+ const audioRuns: Run[] = [];
+ const parts: { partNumber: number; etag: string }[] = [];
+ let base = 0;
+ job.chunks.forEach((chunk, index) => {
+ const result = results[index] as VideoResult;
+ sizes.set(result.sizes, chunk.frames[0]);
+ for (const key of result.keyframes) keyframes.push(chunk.frames[0] + key);
+ for (const run of result.videoRuns)
+ videoRuns.push({ ...run, offset: run.offset + base });
+ for (const run of result.audioRuns)
+ audioRuns.push({ ...run, offset: run.offset + base });
+ for (const part of result.parts) parts.push(part);
+ base += result.bytes + result.paddedBytes;
+ });
+ const payloadSize = base;
+
+ let audio: Parameters<typeof buildHeader>[0]["audio"] = null;
+ if (job.sections.length > 0) {
+ const totalPackets = Math.ceil(job.totalSamples / PACKET) + 1;
+ const audioSizes = new Uint32Array(totalPackets);
+ let asc = "";
+ for (const { meta } of job.audioSections.values()) {
+ audioSizes.set(meta.sizes, meta.firstPacket);
+ asc = meta.extradata;
+ }
+ audio = {
+ sizes: audioSizes,
+ runs: audioRuns,
+ asc: Buffer.from(asc, "base64"),
+ totalSamples: job.totalSamples,
+ priming: PACKET,
+ };
+ const covered = audioRuns.reduce((sum, run) => sum + run.count, 0);
+ if (covered !== totalPackets) {
+ throw new Error(`audio runs cover ${covered}/${totalPackets} packets`);
+ }
+ }
+ const videoCovered = videoRuns.reduce((sum, run) => sum + run.count, 0);
+ if (videoCovered !== job.totalFrames) {
+ throw new Error(
+ `video runs cover ${videoCovered}/${job.totalFrames} frames`,
+ );
+ }
+
+ const header = buildHeader({
+ width: results[0]?.width ?? job.width,
+ height: results[0]?.height ?? job.height,
+ fps: job.fps,
+ video: {
+ sizes,
+ runs: videoRuns,
+ keyframes: Uint32Array.from(keyframes),
+ avcC: avcC(Buffer.from(extradata, "base64")),
+ },
+ audio,
+ payloadSize,
+ minimumSize: MIN_PART + 64 * 1024,
+ });
+ job.t.headerBuilt = now();
+ if (!job.uploadId) throw new Error("no upload");
+ const etag = await s3.uploadPart(job.key, job.uploadId, 1, header);
+ parts.push({ partNumber: 1, etag });
+ // Complete from what the bucket actually holds, after checking it is
+ // exactly the layout the header describes (retries and straggler copies
+ // overwrite parts in place; any stray part would corrupt the offsets).
+ const expected = new Map(parts.map((part) => [part.partNumber, part]));
+ const expectedSizes = new Map<number, number>([[1, header.byteLength]]);
+ for (const result of results) {
+ for (const part of result.parts)
+ expectedSizes.set(part.partNumber, part.size);
+ }
+ if (SPLIT_HEDGE_PARTS && process.env.RF_TRUST_ETAGS !== "0") {
+ // S3 checks every listed part's ETag on completion, so a part that
+ // was overwritten with other bytes fails the call instead of
+ // corrupting the file; the ListParts round trip adds nothing.
+ await s3.completeMultipart(
+ job.key,
+ job.uploadId,
+ parts.sort((a, b) => a.partNumber - b.partNumber),
+ );
+ } else {
+ const listed = await s3.listParts(job.key, job.uploadId);
+ if (SPLIT_HEDGE_PARTS) {
+ // Complete with exactly the winners' parts; hedge losers' parts in
+ // their own ranges are discarded by the store.
+ const byNumber = new Map(listed.map((part) => [part.partNumber, part]));
+ for (const [partNumber, size] of expectedSizes) {
+ const part = byNumber.get(partNumber);
+ if (!part) throw new Error(`part ${partNumber} missing from upload`);
+ if (part.size !== size) {
+ throw new Error(
+ `part ${partNumber} is ${part.size} bytes, expected ${size}`,
+ );
+ }
+ }
+ await s3.completeMultipart(
+ job.key,
+ job.uploadId,
+ parts.sort((a, b) => a.partNumber - b.partNumber),
+ );
+ } else {
+ for (const part of listed) {
+ const size = expectedSizes.get(part.partNumber);
+ if (size === undefined)
+ throw new Error(`unexpected part ${part.partNumber} in upload`);
+ if (size !== part.size) {
+ throw new Error(
+ `part ${part.partNumber} is ${part.size} bytes, expected ${size}`,
+ );
+ }
+ }
+ if (listed.length !== expected.size) {
+ throw new Error(
+ `upload has ${listed.length} parts, expected ${expected.size}`,
+ );
+ }
+ await s3.completeMultipart(job.key, job.uploadId, listed);
+ }
+ }
+ job.t.completed = now();
+ job.outputBytes = payloadSize + header.byteLength;
+
+ await s3.ready();
+ job.url = s3.presign("GET", job.key, s3.config.imds ? 6 * 3600 : 24 * 3600);
+ if (process.env.RF_VERIFY_ASYNC !== "0") {
+ // Watchable as soon as the object exists; the ffprobe check still
+ // runs and is reported on the job, it just isn't on the user's path.
+ verifyPlayable(job).then(
+ () => {
+ job.verified = true;
+ },
+ (error) => {
+ job.verified = false;
+ console.error(`job ${job.id} FAILED verification: ${error}`);
+ },
+ );
+ } else {
+ await verifyPlayable(job);
+ job.verified = true;
+ }
+ job.t.ready = now();
+ job.status = "ready";
+ console.log(
+ `job ${job.id} ready in ${Math.round(job.t.ready - (job.t.requested ?? 0))}ms (${job.chunks.length} chunks)`,
+ );
+ finish(job);
+}
+
+async function verifyPlayable(job: Job) {
+ if (!job.url) return;
+ const probe = Bun.spawn(
+ [
+ "ffprobe",
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration:stream=codec_name,nb_frames",
+ "-of",
+ "json",
+ job.url,
+ ],
+ { stdout: "pipe", stderr: "pipe" },
+ );
+ const [out, err, code] = await Promise.all([
+ new Response(probe.stdout).text(),
+ new Response(probe.stderr).text(),
+ probe.exited,
+ ]);
+ if (code !== 0) throw new Error(`ffprobe failed: ${err.slice(0, 300)}`);
+ const parsed = JSON.parse(out) as {
+ format?: { duration?: string };
+ streams?: { codec_name?: string; nb_frames?: string }[];
+ };
+ const duration = Number(parsed.format?.duration ?? 0);
+ const expected = job.totalFrames / job.fps;
+ if (Math.abs(duration - expected) > 0.5) {
+ throw new Error(`output duration ${duration}s, expected ${expected}s`);
+ }
+ const frames = Number(
+ parsed.streams?.find((stream) => stream.codec_name === "h264")?.nb_frames ??
+ 0,
+ );
+ if (frames !== job.totalFrames) {
+ throw new Error(`output has ${frames} frames, expected ${job.totalFrames}`);
+ }
+}
+
+// ---------------------------------------------------------------- summary ---
+
+function percentile(values: number[], p: number) {
+ if (values.length === 0) return 0;
+ const sorted = [...values].sort((a, b) => a - b);
+ return (
+ sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))] ?? 0
+ );
+}
+
+function summary(job: Job) {
+ const start = job.t.requested ?? 0;
+ const rel = Object.fromEntries(
+ Object.entries(job.t).map(([name, value]) => [
+ name,
+ Math.round(value - start),
+ ]),
+ );
+ const video = job.taskStats.filter(
+ (stat) => stat.kind === "video" && !stat.duplicate,
+ );
+ const audio = job.taskStats.filter((stat) => stat.kind === "audio");
+ const pick = (list: Record<string, unknown>[], field: string) =>
+ list.map((stat) => Number(stat[field] ?? 0));
+ const describe = (list: Record<string, unknown>[], field: string) => ({
+ p50: Math.round(percentile(pick(list, field), 0.5)),
+ p95: Math.round(percentile(pick(list, field), 0.95)),
+ max: Math.round(Math.max(0, ...pick(list, field))),
+ });
+ return {
+ id: job.id,
+ label: job.request.label,
+ status: job.status,
+ error: job.error,
+ recording: job.request.recording,
+ fps: job.fps,
+ resolution: job.resolution,
+ output: {
+ width: job.width,
+ height: job.height,
+ frames: job.totalFrames,
+ bytes: job.outputBytes,
+ },
+ url: job.status === "ready" ? job.url : undefined,
+ timeline: rel,
+ plan: job.plan,
+ probe: job.probe,
+ workersUsed: job.workersUsed.size,
+ verified: job.verified,
+ hlsUrl: job.hls?.url,
+ hlsSegments: job.hls?.listed.length,
+ cpuSeconds: Math.round(job.cpuSeconds * 10) / 10,
+ fetchedBytes: job.fetchedBytes,
+ duplicates: job.taskStats.filter((stat) => stat.duplicate).length,
+ video: {
+ total: describe(video, "totalMs"),
+ fetch: describe(video, "fetchMs"),
+ render: describe(video, "engineRenderMs"),
+ engine: describe(video, "engineMs"),
+ audioWait: describe(video, "audioWaitMs"),
+ upload: describe(video, "uploadMs"),
+ queued: describe(video, "queuedMs"),
+ },
+ audio: {
+ total: describe(audio, "totalMs"),
+ engine: describe(audio, "engineMs"),
+ fetch: describe(audio, "fetchMs"),
+ },
+ tasks: job.taskStats,
+ };
+}
+
+// ------------------------------------------------------------------ server ---
+
+function authorized(request: Request) {
+ if (!TOKEN) return true;
+ const given = Buffer.from(request.headers.get("authorization") ?? "");
+ const expected = Buffer.from(`Bearer ${TOKEN}`);
+ return given.length === expected.length && timingSafeEqual(given, expected);
+}
+
+Bun.serve({
+ port: PORT,
+ hostname: "::",
+ idleTimeout: 120,
+ async fetch(request) {
+ const url = new URL(request.url);
+ if (url.pathname === "/health")
+ return Response.json({ ok: true, ...liveSlots() });
+ if (!authorized(request))
+ return new Response("unauthorized", { status: 401 });
+
+ if (url.pathname === "/work" && request.method === "POST") {
+ const body = (await request.json()) as {
+ worker: string;
+ slots: number;
+ cpus: number;
+ service?: string;
+ kinds?: string[];
+ audioSlots?: number;
+ prefetch?: boolean;
+ };
+ const worker = workers.get(body.worker) ?? {
+ id: body.worker,
+ slots: body.slots,
+ cpus: body.cpus,
+ lastSeen: Date.now(),
+ service: body.service ?? "",
+ };
+ worker.lastSeen = Date.now();
+ worker.slots = body.slots;
+ worker.audioSlots = body.audioSlots ?? 0;
+ if (!workers.has(body.worker)) supersede(body.worker);
+ workers.set(body.worker, worker);
+ const task = await new Promise<Task | null>((resolve) => {
+ const poller: Poller = {
+ worker: body.worker,
+ kinds: body.kinds,
+ prefetch: body.prefetch,
+ resolve,
+ };
+ pollers.push(poller);
+ dispatch();
+ if (poller.prefetch) {
+ const index = pollers.indexOf(poller);
+ if (index >= 0) {
+ pollers.splice(index, 1);
+ resolve(null);
+ }
+ }
+ setTimeout(() => {
+ const index = pollers.indexOf(poller);
+ if (index >= 0) {
+ pollers.splice(index, 1);
+ resolve(null);
+ }
+ }, 20_000);
+ });
+ return Response.json({ task, finished: finishedJobs });
+ }
+
+ if (url.pathname === "/heartbeat" && request.method === "POST") {
+ const body = (await request.json()) as {
+ worker: string;
+ slots: number;
+ cpus: number;
+ usage?: Usage | null;
+ running?: {
+ taskId: string;
+ frames: number;
+ total: number;
+ elapsedMs: number;
+ }[];
+ };
+ for (const entry of body.running ?? []) {
+ const job = jobs.get(entry.taskId.split(":")[0] ?? "");
+ const state = job?.tasks.get(entry.taskId);
+ if (!state) continue;
+ if (state.state === "queued" && state.heldUntil) {
+ // Still running from before a coordinator restart: adopt it.
+ state.state = "running";
+ state.worker = body.worker;
+ state.startedAt = now() - entry.elapsedMs;
+ state.heldUntil = undefined;
+ state.attempts = 1;
+ const index = queue.indexOf(state);
+ if (index >= 0) queue.splice(index, 1);
+ console.log(`re-attached ${entry.taskId} to ${body.worker}`);
+ }
+ if (state.task.kind === "video") {
+ if (entry.frames > (state.progress?.frames ?? 0) && job)
+ job.t.lastProgress = now();
+ state.progress = { ...entry, at: now() };
+ }
+ }
+ const worker = workers.get(body.worker);
+ if (worker) {
+ worker.lastSeen = Date.now();
+ worker.usage = body.usage;
+ } else {
+ supersede(body.worker);
+ workers.set(body.worker, {
+ id: body.worker,
+ slots: body.slots,
+ cpus: body.cpus,
+ lastSeen: Date.now(),
+ service: "",
+ usage: body.usage,
+ });
+ }
+ return Response.json({
+ finished: finishedJobs,
+ cancel: cancellations(body.worker),
+ });
+ }
+
+ const segmentMatch = url.pathname.match(/^\/tasks\/([^/]+)\/segment$/);
+ if (segmentMatch && request.method === "POST") {
+ const taskId = decodeURIComponent(segmentMatch[1] ?? "");
+ const job = jobs.get(taskId.split(":")[0] ?? "");
+ if (!job?.hls) return new Response("unknown job", { status: 404 });
+ const report = (await request.json()) as SegmentReport;
+ job.hls.extradata ??= report.extradata || undefined;
+ let chunk = job.hls.segments.get(report.chunk);
+ if (!chunk) {
+ chunk = new Map();
+ job.hls.segments.set(report.chunk, chunk);
+ }
+ // First copy wins (a hedge writes the same key with equivalent bytes).
+ if (!chunk.has(report.index)) chunk.set(report.index, report);
+ publishPlaylist(job);
+ return Response.json({ ok: true });
+ }
+
+ const taskMatch = url.pathname.match(
+ /^\/tasks\/([^/]+)\/(done|fail|audio)$/,
+ );
+ if (taskMatch && request.method === "POST") {
+ const taskId = decodeURIComponent(taskMatch[1] ?? "");
+ const jobId = taskId.split(":")[0] ?? "";
+ const job = jobs.get(jobId);
+ const state = job?.tasks.get(taskId);
+ if (!job || !state) return new Response("unknown task", { status: 404 });
+ if (taskMatch[2] === "fail") {
+ const body = (await request.json()) as {
+ error: string;
+ worker: string;
+ };
+ console.warn(`task ${taskId} failed on ${body.worker}: ${body.error}`);
+ if (job.status !== "rendering") return Response.json({ ok: true });
+ if (
+ state.task.kind === "video" &&
+ job.videoResults.has(state.task.chunk)
+ ) {
+ state.state = "done";
+ return Response.json({ ok: true });
+ }
+ if (state.duplicateOf) {
+ state.state = "done";
+ return Response.json({ ok: true });
+ }
+ if (state.attempts >= 5)
+ failJob(job, new Error(`${taskId}: ${body.error}`));
+ else {
+ // Back off before retrying so a transient storage hiccup
+ // can't burn every attempt within a second.
+ state.state = "queued";
+ state.worker = undefined;
+ setTimeout(() => {
+ if (job.status !== "rendering" || state.state !== "queued") return;
+ queue.unshift(state);
+ dispatch();
+ }, 1000 * state.attempts);
+ }
+ return Response.json({ ok: true });
+ }
+ if (taskMatch[2] === "done") {
+ const result = (await request.json()) as VideoResult;
+ if (job.status === "rendering") onVideoDone(job, state, result);
+ return Response.json({ ok: true });
+ }
+ // audio: [u32 json length][json][packet bytes]
+ const bytes = new Uint8Array(await request.arrayBuffer());
+ const length = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);
+ const meta = JSON.parse(
+ new TextDecoder().decode(bytes.subarray(4, 4 + length)),
+ ) as AudioResultMeta;
+ const data = bytes.slice(4 + length);
+ if (state.task.kind === "audio" && job.status === "rendering") {
+ onAudioDone(job, state, meta, data);
+ }
+ return Response.json({ ok: true });
+ }
+
+ const audioMatch = url.pathname.match(/^\/jobs\/([^/]+)\/audio$/);
+ if (audioMatch && request.method === "GET") {
+ const job = jobs.get(audioMatch[1] ?? "");
+ if (!job) return new Response("unknown job", { status: 404 });
+ const from = Number(url.searchParams.get("from"));
+ const to = Number(url.searchParams.get("to"));
+ const collect = () => {
+ const sizes: number[] = [];
+ const pieces: Uint8Array[] = [];
+ let packet = from;
+ while (packet < to) {
+ let found = false;
+ for (const { meta, data } of job.audioSections.values()) {
+ const end = meta.firstPacket + meta.sizes.length;
+ if (packet < meta.firstPacket || packet >= end) continue;
+ let offset = 0;
+ for (let index = 0; index < packet - meta.firstPacket; index++) {
+ offset += meta.sizes[index] ?? 0;
+ }
+ const last = Math.min(to, end);
+ for (
+ let index = packet - meta.firstPacket;
+ index < last - meta.firstPacket;
+ index++
+ ) {
+ const size = meta.sizes[index] ?? 0;
+ sizes.push(size);
+ pieces.push(data.subarray(offset, offset + size));
+ offset += size;
+ }
+ packet = last;
+ found = true;
+ break;
+ }
+ if (!found) return null;
+ }
+ return { sizes, pieces };
+ };
+ let collected = collect();
+ while (!collected) {
+ if (job.status !== "rendering" && job.status !== "planning")
+ return new Response("job finished", { status: 410 });
+ await new Promise<void>((resolve) => {
+ job.audioWaiters.push(resolve);
+ setTimeout(resolve, 10_000);
+ });
+ collected = collect();
+ }
+ const header = new Uint8Array(4 + collected.sizes.length * 4);
+ const view = new DataView(header.buffer);
+ view.setUint32(0, collected.sizes.length);
+ for (const [index, size] of collected.sizes.entries()) {
+ view.setUint32(4 + index * 4, size);
+ }
+ return new Response(
+ new Blob([header, ...collected.pieces] as BlobPart[]),
+ );
+ }
+
+ if (url.pathname === "/index" && request.method === "POST") {
+ // Upload-time hook: index a recording's sources before any export.
+ const body = (await request.json()) as { recording: string };
+ const started = performance.now();
+ await sourceIndex(body.recording.replace(/\/$/, ""));
+ return Response.json({ ms: Math.round(performance.now() - started) });
+ }
+
+ if (url.pathname === "/jobs" && request.method === "POST") {
+ const parsed = validateJobRequest(await request.json().catch(() => null));
+ if (typeof parsed === "string")
+ return new Response(parsed, { status: 400 });
+ const body = parsed;
+ const active = [...jobs.values()].filter(
+ (job) => job.status !== "ready" && job.status !== "error",
+ ).length;
+ if (active >= MAX_ACTIVE_JOBS) {
+ return new Response("too many active exports", {
+ status: 429,
+ headers: { "retry-after": "10" },
+ });
+ }
+ const id = randomUUID().slice(0, 12);
+ const compression = body.compression ?? "Maximum";
+ const job: Job = {
+ id,
+ request: body,
+ status: "planning",
+ key: `out/${id}.mp4`,
+ t: { requested: now() },
+ fps: body.fps ?? 30,
+ bpp: COMPRESSION_BPP[compression],
+ resolution: body.resolution ?? [1920, 1080],
+ totalFrames: 0,
+ totalSamples: 0,
+ width: 0,
+ height: 0,
+ chunks: [],
+ sections: [],
+ tasks: new Map(),
+ videoResults: new Map(),
+ audioSections: new Map(),
+ audioWaiters: [],
+ cpuSeconds: 0,
+ fetchedBytes: 0,
+ workersUsed: new Set(),
+ waiters: [],
+ taskStats: [],
+ };
+ if (HLS) job.hls = newHlsState(`hls/${id}`);
+ jobs.set(id, job);
+ planJob(job).catch((error) => failJob(job, error));
+ return Response.json({ id, hlsUrl: job.hls?.url });
+ }
+
+ const jobMatch = url.pathname.match(/^\/jobs\/([^/]+)(\/wait)?$/);
+ if (jobMatch && request.method === "GET") {
+ const job = jobs.get(jobMatch[1] ?? "");
+ if (!job) return new Response("unknown job", { status: 404 });
+ if (jobMatch[2] && job.status !== "ready" && job.status !== "error") {
+ await new Promise<void>((resolve) => {
+ job.waiters.push(resolve);
+ setTimeout(resolve, 100_000);
+ });
+ }
+ return Response.json(
+ job.final ? { ...job.final, verified: job.verified } : summary(job),
+ );
+ }
+
+ if (url.pathname === "/usage") {
+ // Fleet totals for cost accounting: diff two snapshots around a job.
+ const live = [...workers.values()].filter(
+ (worker) => Date.now() - worker.lastSeen < 30_000,
+ );
+ return Response.json({
+ at: Date.now(),
+ workers: live.length,
+ cpuSeconds: live.reduce(
+ (sum, worker) => sum + (worker.usage?.cpuSeconds ?? 0),
+ 0,
+ ),
+ memoryBytes: live.reduce(
+ (sum, worker) => sum + (worker.usage?.memoryBytes ?? 0),
+ 0,
+ ),
+ perWorker: live.map((worker) => ({ id: worker.id, ...worker.usage })),
+ });
+ }
+
+ if (url.pathname === "/workers") {
+ return Response.json({
+ ...liveSlots(),
+ workers: [...workers.values()].map((worker) => ({
+ ...worker,
+ ageMs: Date.now() - worker.lastSeen,
+ })),
+ queue: queue.length,
+ });
+ }
+
+ return new Response("not found", { status: 404 });
+ },
+});
+
+console.log(`render-farm coordinator on :${PORT} (${PUBLIC_URL})`);
+
+// Pick up exports a previous coordinator process left unfinished.
+resumeJobs().catch((error) => console.error(`resume failed: ${error}`));
diff --git a/apps/render-farm/src/engine.ts b/apps/render-farm/src/engine.ts
new file mode 100644
index 000000000..59a8c6381
--- /dev/null
+++ b/apps/render-farm/src/engine.ts
@@ -0,0 +1,216 @@
+import { type Subprocess, spawn } from "bun";
+
+// A warm `cap-render-farm` process. One per render slot: requests are
+// serialized per process, and the process stays alive between tasks so its
+// GPU device, compiled layer pipelines and ffmpeg state are reused.
+
+type Pending = {
+ resolve: (value: unknown) => void;
+ reject: (error: Error) => void;
+};
+
+export class Engine {
+ private process: Subprocess<"pipe", "pipe", "pipe">;
+ private pending = new Map<number, Pending>();
+ private nextId = 1;
+ private buffer = "";
+ private exited = false;
+ readonly stderrTail: string[] = [];
+ /** Latest progress value per in-flight request (frames rendered). */
+ onProgress: ((value: number) => void) | null = null;
+ /** Streaming events for the request in flight (`gop`, `extradata`). */
+ onEvent: ((event: Record<string, unknown>) => void) | null = null;
+
+ constructor(
+ readonly binary: string,
+ readonly env: Record<string, string> = {},
+ readonly label = "engine",
+ /** Scheduling niceness: background lanes yield the CPU to render slots. */
+ readonly nice = 0,
+ ) {
+ this.process = spawn(
+ nice > 0 ? ["nice", "-n", String(nice), binary] : [binary],
+ {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...process.env, ...env },
+ },
+ );
+ this.pump();
+ this.pumpErrors();
+ this.process.exited.then((code) => {
+ this.exited = true;
+ const error = new Error(
+ `${label} exited with ${code}: ${this.stderrTail.slice(-5).join(" | ")}`,
+ );
+ for (const pending of this.pending.values()) pending.reject(error);
+ this.pending.clear();
+ });
+ }
+
+ get pid() {
+ return this.process.pid;
+ }
+
+ get alive() {
+ return !this.exited;
+ }
+
+ private async pump() {
+ const decoder = new TextDecoder();
+ for await (const chunk of this.process.stdout) {
+ this.buffer += decoder.decode(chunk, { stream: true });
+ let newline = this.buffer.indexOf("\n");
+ while (newline >= 0) {
+ const line = this.buffer.slice(0, newline);
+ this.buffer = this.buffer.slice(newline + 1);
+ newline = this.buffer.indexOf("\n");
+ if (!line.trim()) continue;
+ let message: {
+ id?: number;
+ ok: boolean;
+ result?: unknown;
+ error?: string;
+ progress?: number;
+ };
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (message.progress !== undefined) {
+ this.onProgress?.(message.progress);
+ continue;
+ }
+ if (message.ok === undefined && message.error === undefined) {
+ this.onEvent?.(message as Record<string, unknown>);
+ continue;
+ }
+ const pending =
+ message.id === undefined ? undefined : this.pending.get(message.id);
+ if (!pending || message.id === undefined) continue;
+ this.pending.delete(message.id);
+ if (message.ok) pending.resolve(message.result);
+ else pending.reject(new Error(message.error ?? "engine error"));
+ }
+ }
+ }
+
+ private async pumpErrors() {
+ const decoder = new TextDecoder();
+ let partial = "";
+ for await (const chunk of this.process.stderr) {
+ partial += decoder.decode(chunk, { stream: true });
+ const lines = partial.split("\n");
+ partial = lines.pop() ?? "";
+ for (const line of lines) {
+ if (!line.trim() || line.startsWith("[libx264")) continue;
+ this.stderrTail.push(line.slice(0, 400));
+ if (this.stderrTail.length > 50) this.stderrTail.shift();
+ if (process.env.RF_ENGINE_LOG === "1")
+ console.error(`[${this.label}] ${line}`);
+ }
+ }
+ }
+
+ request<T>(op: string, body: Record<string, unknown>): Promise<T> {
+ if (this.exited)
+ return Promise.reject(new Error(`${this.label} is not running`));
+ const id = this.nextId++;
+ return new Promise<T>((resolve, reject) => {
+ this.pending.set(id, {
+ resolve: resolve as (value: unknown) => void,
+ reject,
+ });
+ this.process.stdin.write(`${JSON.stringify({ id, op, ...body })}\n`);
+ this.process.stdin.flush();
+ });
+ }
+
+ kill() {
+ this.process.kill();
+ }
+}
+
+/** CPU seconds a process (and its threads) has used, from /proc. */
+export async function processCpuSeconds(pid: number) {
+ try {
+ const stat = await Bun.file(`/proc/${pid}/stat`).text();
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ const ticks = Number(fields[11]) + Number(fields[12]);
+ return ticks / 100;
+ } catch {
+ return 0;
+ }
+}
+
+/** CPU seconds per thread name, for profiling (RF_PROFILE_THREADS=1). */
+export async function threadCpu(pid: number) {
+ const out: Record<string, number> = {};
+ try {
+ const { readdirSync } = await import("node:fs");
+ for (const tid of readdirSync(`/proc/${pid}/task`)) {
+ try {
+ const stat = await Bun.file(`/proc/${pid}/task/${tid}/stat`).text();
+ const name = stat
+ .slice(stat.indexOf("(") + 1, stat.lastIndexOf(")"))
+ .replace(/[-_:]?\d+$/, "");
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ out[name] =
+ (out[name] ?? 0) + (Number(fields[11]) + Number(fields[12])) / 100;
+ } catch {}
+ }
+ } catch {}
+ return out;
+}
+
+export function diffThreads(
+ before: Record<string, number>,
+ after: Record<string, number>,
+) {
+ const out: Record<string, number> = {};
+ for (const [name, value] of Object.entries(after)) {
+ const delta = value - (before[name] ?? 0);
+ if (delta > 0.05) out[name] = Math.round(delta * 10) / 10;
+ }
+ return out;
+}
+
+/**
+ * Samples every thread of `pid` until `until` settles; returns CPU seconds by
+ * thread name. Render threads exit with the task, so a before/after diff
+ * would miss them.
+ */
+export async function sampleThreads(pid: number, until: Promise<unknown>) {
+ const { readdirSync } = await import("node:fs");
+ const seen = new Map<string, { name: string; first: number; last: number }>();
+ let done = false;
+ until.finally(() => {
+ done = true;
+ });
+ while (!done) {
+ try {
+ for (const tid of readdirSync(`/proc/${pid}/task`)) {
+ try {
+ const stat = await Bun.file(`/proc/${pid}/task/${tid}/stat`).text();
+ const name = stat
+ .slice(stat.indexOf("(") + 1, stat.lastIndexOf(")"))
+ .replace(/[-_:. ]?\d+$/, "");
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ const cpu = (Number(fields[11]) + Number(fields[12])) / 100;
+ const entry = seen.get(tid);
+ if (entry) entry.last = cpu;
+ else seen.set(tid, { name, first: cpu, last: cpu });
+ } catch {}
+ }
+ } catch {}
+ await Bun.sleep(500);
+ }
+ const out: Record<string, number> = {};
+ for (const entry of seen.values()) {
+ out[entry.name] =
+ Math.round(((out[entry.name] ?? 0) + entry.last - entry.first) * 10) / 10;
+ }
+ return out;
+}
diff --git a/apps/render-farm/src/fmp4.test.ts b/apps/render-farm/src/fmp4.test.ts
new file mode 100644
index 000000000..64ddf0671
--- /dev/null
+++ b/apps/render-farm/src/fmp4.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, test } from "bun:test";
+import {
+ ANNEX_B_PARAMETER_SETS,
+ child,
+ parseBoxes,
+ u32,
+ u64,
+} from "./boxes.test-util";
+import { initSegment, playlist, segmentHeader } from "./fmp4";
+import { avcC } from "./mp4";
+
+describe("initSegment", () => {
+ test("declares both tracks as fragmented", () => {
+ const init = initSegment({
+ width: 1664,
+ height: 1080,
+ fps: 30,
+ avcC: avcC(ANNEX_B_PARAMETER_SETS),
+ asc: Uint8Array.of(0x11, 0x90),
+ });
+ const [ftyp, moov] = parseBoxes(init);
+ expect(ftyp?.type).toBe("ftyp");
+ expect(moov?.type).toBe("moov");
+ if (!moov) throw new Error("no moov");
+ const children = parseBoxes(moov.body).map((box) => box.type);
+ expect(children).toEqual(["mvhd", "trak", "trak", "mvex"]);
+ const mvex = child(moov, "mvex");
+ expect(mvex && parseBoxes(mvex.body).map((box) => box.type)).toEqual([
+ "trex",
+ "trex",
+ ]);
+ });
+
+ test("video only when there is no audio", () => {
+ const init = initSegment({
+ width: 1920,
+ height: 1080,
+ fps: 60,
+ avcC: avcC(ANNEX_B_PARAMETER_SETS),
+ asc: null,
+ });
+ const moov = parseBoxes(init)[1];
+ if (!moov) throw new Error("no moov");
+ expect(
+ parseBoxes(moov.body).filter((box) => box.type === "trak"),
+ ).toHaveLength(1);
+ });
+});
+
+describe("segmentHeader", () => {
+ test("trun offsets point at the video then audio bytes after the header", () => {
+ const videoSizes = [100, 50, 50];
+ const audioSizes = [20, 30];
+ const header = segmentHeader({
+ sequence: 121,
+ firstFrame: 120,
+ videoSizes,
+ firstPacket: 10,
+ audioSizes,
+ });
+ const [styp, moof, mdat] = parseBoxes(header);
+ expect([styp?.type, moof?.type, mdat?.type]).toEqual([
+ "styp",
+ "moof",
+ "mdat",
+ ]);
+ if (!moof || !mdat) throw new Error("missing boxes");
+ expect(u32(header, mdat.start)).toBe(8 + 200 + 50);
+ expect(mdat.start + 8).toBe(header.byteLength);
+
+ const mfhd = child(moof, "mfhd");
+ expect(mfhd && u32(mfhd.body, 4)).toBe(121);
+ const [videoTraf, audioTraf] = parseBoxes(moof.body).filter(
+ (box) => box.type === "traf",
+ );
+ if (!videoTraf || !audioTraf) throw new Error("missing trafs");
+
+ const videoTfdt = child(videoTraf, "tfdt");
+ expect(videoTfdt && u64(videoTfdt.body, 4)).toBe(120 * 1000);
+ const videoTrun = child(videoTraf, "trun");
+ if (!videoTrun) throw new Error("no video trun");
+ expect(u32(videoTrun.body, 4)).toBe(3);
+ expect(u32(videoTrun.body, 8)).toBe(moof.size + 8);
+ expect(u32(videoTrun.body, 12 + 8)).toBe(0x02000000);
+ expect(u32(videoTrun.body, 24 + 8)).toBe(0x01010000);
+
+ const audioTfdt = child(audioTraf, "tfdt");
+ expect(audioTfdt && u64(audioTfdt.body, 4)).toBe(10 * 1024);
+ const audioTrun = child(audioTraf, "trun");
+ if (!audioTrun) throw new Error("no audio trun");
+ expect(u32(audioTrun.body, 4)).toBe(2);
+ expect(u32(audioTrun.body, 8)).toBe(moof.size + 8 + 200);
+ });
+
+ test("video-only segments carry one traf", () => {
+ const header = segmentHeader({
+ sequence: 1,
+ firstFrame: 0,
+ videoSizes: [10],
+ firstPacket: 0,
+ audioSizes: [],
+ });
+ const moof = parseBoxes(header)[1];
+ if (!moof) throw new Error("no moof");
+ expect(
+ parseBoxes(moof.body).filter((box) => box.type === "traf"),
+ ).toHaveLength(1);
+ });
+});
+
+describe("playlist", () => {
+ test("lists segments in order and ends only when told to", () => {
+ const segments = [
+ { url: "a.m4s", duration: 2 },
+ { url: "b.m4s", duration: 1.5 },
+ ];
+ const open = playlist(segments, {
+ initUrl: "init.mp4",
+ targetDuration: 4,
+ ended: false,
+ });
+ expect(open).toContain('#EXT-X-MAP:URI="init.mp4"');
+ expect(open).toContain("#EXT-X-PLAYLIST-TYPE:EVENT");
+ expect(open.indexOf("a.m4s")).toBeLessThan(open.indexOf("b.m4s"));
+ expect(open).toContain("#EXTINF:1.500,");
+ expect(open).not.toContain("#EXT-X-ENDLIST");
+ expect(
+ playlist(segments, {
+ initUrl: "init.mp4",
+ targetDuration: 4,
+ ended: true,
+ }),
+ ).toContain("#EXT-X-ENDLIST");
+ });
+});
diff --git a/apps/render-farm/src/fmp4.ts b/apps/render-farm/src/fmp4.ts
new file mode 100644
index 000000000..984bf3c75
--- /dev/null
+++ b/apps/render-farm/src/fmp4.ts
@@ -0,0 +1,285 @@
+import {
+ avc1,
+ box,
+ build,
+ dinf,
+ fullBox,
+ hdlr,
+ MATRIX,
+ mdhd,
+ mp4a,
+ tkhd,
+} from "./mp4";
+
+// Fragmented MP4 for HLS: one init segment per export, then self-contained
+// media segments (moof + mdat) that chunk workers upload while they render.
+// Timescales match the flat MP4 (video fps*1000 with 1000 per frame, audio
+// 48 kHz with 1024 per AAC packet), so both outputs carry identical samples.
+
+export const VIDEO_TRACK = 1;
+export const AUDIO_TRACK = 2;
+const PRIMING = 1024;
+
+function emptyStbl(stsd: Uint8Array) {
+ const empty = (type: string) =>
+ fullBox(
+ type,
+ 0,
+ 0,
+ build((writer) => writer.u32(0)),
+ );
+ return box(
+ "stbl",
+ fullBox(
+ "stsd",
+ 0,
+ 0,
+ build((writer) => writer.u32(1)),
+ stsd,
+ ),
+ empty("stts"),
+ empty("stsc"),
+ fullBox(
+ "stsz",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(0);
+ }),
+ ),
+ empty("stco"),
+ );
+}
+
+export function initSegment(input: {
+ width: number;
+ height: number;
+ fps: number;
+ avcC: Uint8Array;
+ asc: Uint8Array | null;
+}) {
+ const ftyp = box(
+ "ftyp",
+ build((writer) => {
+ writer.ascii("iso6");
+ writer.u32(0);
+ writer.ascii("iso6isomavc1mp41dash");
+ }),
+ );
+ const mvhd = fullBox(
+ "mvhd",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(0);
+ writer.u32(1000);
+ writer.u32(0);
+ writer.u32(0x10000);
+ writer.u16(0x100);
+ writer.zeros(10);
+ for (const value of MATRIX) writer.u32(value);
+ writer.zeros(24);
+ writer.u32(input.asc ? 3 : 2);
+ }),
+ );
+ const tracks = [
+ box(
+ "trak",
+ tkhd(VIDEO_TRACK, 0, false, input.width, input.height),
+ box(
+ "mdia",
+ mdhd(input.fps * 1000, 0),
+ hdlr("vide", "VideoHandler"),
+ box(
+ "minf",
+ fullBox("vmhd", 0, 1, new Uint8Array(8)),
+ dinf(),
+ emptyStbl(avc1(input.width, input.height, input.avcC)),
+ ),
+ ),
+ ),
+ ];
+ const trex = (track: number) =>
+ fullBox(
+ "trex",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(track);
+ writer.u32(1);
+ writer.u32(0);
+ writer.u32(0);
+ writer.u32(0);
+ }),
+ );
+ const trexes = [trex(VIDEO_TRACK)];
+ if (input.asc) {
+ // Same priming skip as the flat file; duration 0 = "the whole track".
+ const edts = box(
+ "edts",
+ fullBox(
+ "elst",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(1);
+ writer.u32(0);
+ writer.u32(PRIMING);
+ writer.u16(1);
+ writer.u16(0);
+ }),
+ ),
+ );
+ tracks.push(
+ box(
+ "trak",
+ tkhd(AUDIO_TRACK, 0, true, 0, 0),
+ edts,
+ box(
+ "mdia",
+ mdhd(48000, 0),
+ hdlr("soun", "SoundHandler"),
+ box(
+ "minf",
+ fullBox("smhd", 0, 0, new Uint8Array(4)),
+ dinf(),
+ emptyStbl(mp4a(input.asc)),
+ ),
+ ),
+ ),
+ );
+ trexes.push(trex(AUDIO_TRACK));
+ }
+ const moov = box("moov", mvhd, ...tracks, box("mvex", ...trexes));
+ const out = new Uint8Array(ftyp.byteLength + moov.byteLength);
+ out.set(ftyp, 0);
+ out.set(moov, ftyp.byteLength);
+ return out;
+}
+
+/**
+ * styp + moof + mdat header for one segment; the caller appends the video
+ * sample bytes, then the audio packet bytes. `firstFrame` and `firstPacket`
+ * are global indices (the decode timeline of the whole export).
+ */
+export function segmentHeader(input: {
+ sequence: number;
+ firstFrame: number;
+ videoSizes: number[];
+ firstPacket: number;
+ audioSizes: number[];
+}) {
+ const videoBytes = input.videoSizes.reduce((sum, size) => sum + size, 0);
+ const audioBytes = input.audioSizes.reduce((sum, size) => sum + size, 0);
+ const styp = box(
+ "styp",
+ build((writer) => {
+ writer.ascii("msdh");
+ writer.u32(0);
+ writer.ascii("msdhmsix");
+ }),
+ );
+ const tfhd = (track: number) =>
+ // default-base-is-moof: data offsets count from the moof's first byte.
+ fullBox(
+ "tfhd",
+ 0,
+ 0x020000,
+ build((writer) => writer.u32(track)),
+ );
+ const tfdt = (time: number) =>
+ fullBox(
+ "tfdt",
+ 1,
+ 0,
+ build((writer) => writer.u64(time)),
+ );
+ const make = (moofSize: number) => {
+ const videoTrun = fullBox(
+ "trun",
+ 0,
+ 0x000001 | 0x000100 | 0x000200 | 0x000400,
+ build((writer) => {
+ writer.u32(input.videoSizes.length);
+ writer.u32(moofSize + 8);
+ input.videoSizes.forEach((size, index) => {
+ writer.u32(1000);
+ writer.u32(size);
+ // Segments always open on an IDR; B-frames are off.
+ writer.u32(index === 0 ? 0x02000000 : 0x01010000);
+ });
+ }),
+ );
+ const trafs = [
+ box("traf", tfhd(VIDEO_TRACK), tfdt(input.firstFrame * 1000), videoTrun),
+ ];
+ if (input.audioSizes.length > 0) {
+ const audioTrun = fullBox(
+ "trun",
+ 0,
+ 0x000001 | 0x000100 | 0x000200,
+ build((writer) => {
+ writer.u32(input.audioSizes.length);
+ writer.u32(moofSize + 8 + videoBytes);
+ for (const size of input.audioSizes) {
+ writer.u32(1024);
+ writer.u32(size);
+ }
+ }),
+ );
+ trafs.push(
+ box(
+ "traf",
+ tfhd(AUDIO_TRACK),
+ tfdt(input.firstPacket * 1024),
+ audioTrun,
+ ),
+ );
+ }
+ return box(
+ "moof",
+ fullBox(
+ "mfhd",
+ 0,
+ 0,
+ build((writer) => writer.u32(input.sequence)),
+ ),
+ ...trafs,
+ );
+ };
+ // trun data offsets are fixed width, so the moof size is known up front.
+ const moof = make(make(0).byteLength);
+ const mdat = build((writer) => {
+ writer.u32(8 + videoBytes + audioBytes);
+ writer.ascii("mdat");
+ });
+ const out = new Uint8Array(
+ styp.byteLength + moof.byteLength + mdat.byteLength,
+ );
+ out.set(styp, 0);
+ out.set(moof, styp.byteLength);
+ out.set(mdat, styp.byteLength + moof.byteLength);
+ return out;
+}
+
+export function playlist(
+ segments: { url: string; duration: number }[],
+ options: { initUrl: string; targetDuration: number; ended: boolean },
+) {
+ const lines = [
+ "#EXTM3U",
+ "#EXT-X-VERSION:7",
+ `#EXT-X-TARGETDURATION:${options.targetDuration}`,
+ "#EXT-X-MEDIA-SEQUENCE:0",
+ "#EXT-X-PLAYLIST-TYPE:EVENT",
+ "#EXT-X-INDEPENDENT-SEGMENTS",
+ `#EXT-X-MAP:URI="${options.initUrl}"`,
+ ];
+ for (const segment of segments) {
+ lines.push(`#EXTINF:${segment.duration.toFixed(3)},`, segment.url);
+ }
+ if (options.ended) lines.push("#EXT-X-ENDLIST");
+ return `${lines.join("\n")}\n`;
+}
diff --git a/apps/render-farm/src/hls.test.ts b/apps/render-farm/src/hls.test.ts
new file mode 100644
index 000000000..4b8577d77
--- /dev/null
+++ b/apps/render-farm/src/hls.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test } from "bun:test";
+import { closesSegment, segmentCuts } from "./hls";
+
+// The worker applies `closesSegment` as each GOP finishes; this replays that
+// incremental rule so it can be compared with the coordinator's re-derivation.
+function workerCuts(keyframes: number[], total: number, segmentFrames: number) {
+ const cuts: [number, number][] = [];
+ let start = 0;
+ for (const boundary of keyframes.filter((key) => key > 0 && key < total)) {
+ if (closesSegment(start, boundary, segmentFrames)) {
+ cuts.push([start, boundary]);
+ start = boundary;
+ }
+ }
+ cuts.push([start, total]);
+ return cuts;
+}
+
+describe("segmentCuts", () => {
+ test("cuts every other GOP for 2 s GOPs and 4 s segments", () => {
+ expect(segmentCuts([0, 60, 120, 180, 240], 300, 120)).toEqual([
+ [0, 120],
+ [120, 240],
+ [240, 300],
+ ]);
+ });
+
+ test("a chunk shorter than one segment is a single segment", () => {
+ expect(segmentCuts([0], 45, 60)).toEqual([[0, 45]]);
+ });
+
+ test("segments cover the chunk exactly and start on keyframes", () => {
+ const keyframes = [0, 60, 120, 150, 210, 300, 330];
+ const cuts = segmentCuts(keyframes, 360, 60);
+ expect(cuts[0]?.[0]).toBe(0);
+ expect(cuts.at(-1)?.[1]).toBe(360);
+ for (const [index, [start, end]] of cuts.entries()) {
+ expect(end).toBeGreaterThan(start);
+ expect(keyframes).toContain(start);
+ if (index > 0) expect(start).toBe(cuts[index - 1]?.[1] ?? -1);
+ }
+ });
+
+ test("matches the worker's incremental rule for irregular keyframes", () => {
+ let seed = 7;
+ const random = () => {
+ seed = (seed * 1_103_515_245 + 12_345) % 2 ** 31;
+ return seed / 2 ** 31;
+ };
+ for (let run = 0; run < 200; run++) {
+ const total = 30 + Math.floor(random() * 2000);
+ const keyframes = [0];
+ while ((keyframes.at(-1) ?? 0) < total) {
+ keyframes.push((keyframes.at(-1) ?? 0) + 1 + Math.floor(random() * 90));
+ }
+ const segmentFrames = 30 + Math.floor(random() * 120);
+ expect(segmentCuts(keyframes, total, segmentFrames)).toEqual(
+ workerCuts(keyframes, total, segmentFrames),
+ );
+ }
+ });
+});
diff --git a/apps/render-farm/src/hls.ts b/apps/render-farm/src/hls.ts
new file mode 100644
index 000000000..08fa67ed6
--- /dev/null
+++ b/apps/render-farm/src/hls.ts
@@ -0,0 +1,31 @@
+/**
+ * Whether a segment that started at frame `start` closes at the GOP boundary
+ * `boundary`. Workers apply this as each GOP finishes encoding; a restarted
+ * coordinator re-derives the same cuts from a chunk's keyframes to rebuild the
+ * playlist, so both must use this one rule.
+ */
+export function closesSegment(
+ start: number,
+ boundary: number,
+ segmentFrames: number,
+) {
+ return boundary - start >= segmentFrames;
+}
+
+/** Chunk-local [start, end) frame ranges of a chunk's HLS segments. */
+export function segmentCuts(
+ keyframes: readonly number[],
+ total: number,
+ segmentFrames: number,
+) {
+ const cuts: [number, number][] = [];
+ let start = 0;
+ for (const key of [...keyframes].sort((a, b) => a - b)) {
+ if (key > 0 && key < total && closesSegment(start, key, segmentFrames)) {
+ cuts.push([start, key]);
+ start = key;
+ }
+ }
+ cuts.push([start, total]);
+ return cuts;
+}
diff --git a/apps/render-farm/src/main.ts b/apps/render-farm/src/main.ts
new file mode 100644
index 000000000..16e04faee
--- /dev/null
+++ b/apps/render-farm/src/main.ts
@@ -0,0 +1,6 @@
+export {};
+
+const role = process.env.RF_ROLE ?? "worker";
+if (role === "coordinator") await import("./coordinator");
+else if (role === "worker") await import("./worker");
+else throw new Error(`unknown RF_ROLE ${role}`);
diff --git a/apps/render-farm/src/materialize.ts b/apps/render-farm/src/materialize.ts
new file mode 100644
index 000000000..c55c5385e
--- /dev/null
+++ b/apps/render-farm/src/materialize.ts
@@ -0,0 +1,170 @@
+import {
+ closeSync,
+ ftruncateSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ writeFileSync,
+ writeSync,
+} from "node:fs";
+import { dirname, join } from "node:path";
+import type { S3 } from "./s3";
+
+// Recreates a recording on local disk with only the bytes a task needs.
+// Media files are created at full size as sparse files, and just the
+// requested byte ranges (the moov, plus the samples around the task's time
+// span) are written in. ffmpeg then opens them like the real recording, with
+// correct timestamps and seeking, so the renderer needs no changes at all.
+
+export type FileSpec = {
+ /** Path inside the project directory. */
+ path: string;
+ key: string;
+ size: number;
+ /** Byte ranges [start, end) to fetch, or "all". */
+ ranges: [number, number][] | "all";
+};
+
+const PIECE = 4 << 20;
+
+type LocalFile = {
+ fd: number;
+ pieces: Map<number, Promise<void>>;
+};
+
+class Limiter {
+ private active = 0;
+ private queue: (() => void)[] = [];
+ constructor(private limit: number) {}
+ async run<T>(fn: () => Promise<T>): Promise<T> {
+ if (this.active >= this.limit) {
+ await new Promise<void>((resolve) => this.queue.push(resolve));
+ }
+ this.active++;
+ try {
+ return await fn();
+ } finally {
+ this.active--;
+ this.queue.shift()?.();
+ }
+ }
+}
+
+export type FetchStats = { bytes: number; requests: number; ms: number };
+
+export class ProjectCache {
+ private files = new Map<string, LocalFile>();
+ private rewritten = false;
+ private limiter: Limiter;
+ bytesFetched = 0;
+
+ constructor(
+ readonly s3: S3,
+ readonly root: string,
+ concurrency = Number(process.env.RF_FETCH_CONCURRENCY ?? 12),
+ ) {
+ this.limiter = new Limiter(concurrency);
+ }
+
+ private open(spec: FileSpec) {
+ const fullPath = join(this.root, spec.path);
+ let file = this.files.get(fullPath);
+ if (!file) {
+ mkdirSync(dirname(fullPath), { recursive: true });
+ const fd = openSync(fullPath, "w+");
+ ftruncateSync(fd, spec.size);
+ file = { fd, pieces: new Map() };
+ this.files.set(fullPath, file);
+ }
+ return file;
+ }
+
+ private fetchPiece(
+ spec: FileSpec,
+ file: LocalFile,
+ piece: number,
+ stats: FetchStats,
+ ) {
+ let pending = file.pieces.get(piece);
+ if (!pending) {
+ const start = piece * PIECE;
+ const end = Math.min(spec.size, start + PIECE);
+ pending = this.limiter.run(async () => {
+ const bytes = await this.s3.getRange(spec.key, start, end - 1);
+ if (bytes.byteLength !== end - start) {
+ throw new Error(
+ `short read ${spec.key} ${start}-${end}: ${bytes.byteLength}`,
+ );
+ }
+ let written = 0;
+ while (written < bytes.byteLength) {
+ written += writeSync(
+ file.fd,
+ bytes,
+ written,
+ bytes.byteLength - written,
+ start + written,
+ );
+ }
+ this.bytesFetched += bytes.byteLength;
+ stats.bytes += bytes.byteLength;
+ stats.requests++;
+ });
+ pending.catch(() => file.pieces.delete(piece));
+ file.pieces.set(piece, pending);
+ }
+ return pending;
+ }
+
+ async materialize(specs: FileSpec[]): Promise<FetchStats> {
+ const started = performance.now();
+ const stats: FetchStats = { bytes: 0, requests: 0, ms: 0 };
+ const work: Promise<void>[] = [];
+ for (const spec of specs) {
+ if (spec.size === 0) {
+ this.open(spec);
+ continue;
+ }
+ const file = this.open(spec);
+ const ranges: [number, number][] =
+ spec.ranges === "all" ? [[0, spec.size]] : spec.ranges;
+ const pieces = new Set<number>();
+ for (const [start, end] of ranges) {
+ const clampedEnd = Math.min(end, spec.size);
+ if (clampedEnd <= start) continue;
+ for (
+ let piece = Math.floor(start / PIECE);
+ piece <= Math.floor((clampedEnd - 1) / PIECE);
+ piece++
+ ) {
+ pieces.add(piece);
+ }
+ }
+ for (const piece of pieces)
+ work.push(this.fetchPiece(spec, file, piece, stats));
+ }
+ await Promise.all(work);
+ if (
+ !this.rewritten &&
+ specs.some((spec) => spec.path === "project-config.json")
+ ) {
+ // Configs reference bundled assets (wallpapers) relative to the
+ // project; the renderer wants absolute paths.
+ const path = join(this.root, "project-config.json");
+ const text = readFileSync(path, "utf8");
+ writeFileSync(path, text.replaceAll("$RF_PROJECT", this.root));
+ this.rewritten = true;
+ }
+ stats.ms = Math.round(performance.now() - started);
+ return stats;
+ }
+
+ close() {
+ for (const file of this.files.values()) {
+ try {
+ closeSync(file.fd);
+ } catch {}
+ }
+ this.files.clear();
+ }
+}
diff --git a/apps/render-farm/src/mp4.test.ts b/apps/render-farm/src/mp4.test.ts
new file mode 100644
index 000000000..711d70b24
--- /dev/null
+++ b/apps/render-farm/src/mp4.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, test } from "bun:test";
+import {
+ ANNEX_B_PARAMETER_SETS,
+ child,
+ parseBoxes,
+ u32,
+ u64,
+} from "./boxes.test-util";
+import { avcC, buildHeader, byteRangeFor, type TrackIndex } from "./mp4";
+
+function syntheticIndex(samples: number, gop: number): TrackIndex {
+ const times = new Float64Array(samples);
+ const offsets = new Float64Array(samples);
+ const sizes = new Uint32Array(samples);
+ const keyframes: number[] = [];
+ let offset = 48;
+ for (let sample = 0; sample < samples; sample++) {
+ times[sample] = sample / 30 + (sample % 7) * 0.0001;
+ sizes[sample] = 1000 + ((sample * 7919) % 5000);
+ offsets[sample] = offset;
+ offset += sizes[sample] ?? 0;
+ if (sample % gop === 0) keyframes.push(sample);
+ }
+ return {
+ timescale: 30_000,
+ times,
+ offsets,
+ sizes,
+ keyframes: Uint32Array.from(keyframes),
+ };
+}
+
+// The linear scan byteRangeFor used before the binary search.
+function referenceRange(index: TrackIndex, from: number, to: number) {
+ const count = index.times.length;
+ let first = 0;
+ for (const key of index.keyframes) {
+ if ((index.times[key] ?? 0) <= from) first = key;
+ else break;
+ }
+ let last = count - 1;
+ for (let sample = first; sample < count; sample++) {
+ if ((index.times[sample] ?? 0) > to) {
+ last = sample;
+ break;
+ }
+ }
+ let start = Number.POSITIVE_INFINITY;
+ let end = 0;
+ for (let sample = first; sample <= last; sample++) {
+ const offset = index.offsets[sample] ?? 0;
+ start = Math.min(start, offset);
+ end = Math.max(end, offset + (index.sizes[sample] ?? 0));
+ }
+ return { start, end };
+}
+
+describe("byteRangeFor", () => {
+ test("matches a linear scan across the whole file", () => {
+ const index = syntheticIndex(6000, 21);
+ for (let from = -1; from < 205; from += 0.37) {
+ for (const span of [0, 0.5, 2, 9]) {
+ expect(byteRangeFor(index, from, from + span)).toEqual(
+ referenceRange(index, from, from + span),
+ );
+ }
+ }
+ });
+
+ test("starts at the keyframe at or before the requested time", () => {
+ const index = syntheticIndex(300, 30);
+ const range = byteRangeFor(index, 2.5, 2.6);
+ expect(range?.start).toBe(index.offsets[60]);
+ });
+
+ test("an empty track has no range", () => {
+ expect(
+ byteRangeFor(
+ {
+ timescale: 1,
+ times: new Float64Array(),
+ offsets: new Float64Array(),
+ sizes: new Uint32Array(),
+ keyframes: new Uint32Array(),
+ },
+ 0,
+ 1,
+ ),
+ ).toBeNull();
+ });
+});
+
+describe("buildHeader", () => {
+ test("lays out ftyp, moov, padding and a 64-bit mdat header", () => {
+ const header = buildHeader({
+ width: 1920,
+ height: 1080,
+ fps: 30,
+ video: {
+ sizes: Uint32Array.from([100, 200, 300]),
+ runs: [{ first: 0, count: 3, offset: 0 }],
+ keyframes: Uint32Array.from([0]),
+ avcC: avcC(ANNEX_B_PARAMETER_SETS),
+ },
+ audio: {
+ sizes: Uint32Array.from([10, 10]),
+ runs: [{ first: 0, count: 2, offset: 600 }],
+ asc: Uint8Array.of(0x11, 0x90),
+ totalSamples: 1024,
+ priming: 1024,
+ },
+ payloadSize: 620,
+ minimumSize: 64 * 1024,
+ });
+ expect(header.byteLength).toBe(64 * 1024);
+ const boxes = parseBoxes(header);
+ expect(boxes.map((box) => box.type)).toEqual([
+ "ftyp",
+ "moov",
+ "free",
+ "mdat",
+ ]);
+ const mdat = boxes[3];
+ expect(u32(header, mdat?.start ?? 0)).toBe(1);
+ expect(u64(header, (mdat?.start ?? 0) + 8)).toBe(16 + 620);
+ const moov = boxes[1];
+ if (!moov) throw new Error("no moov");
+ const traks = parseBoxes(moov.body).filter((box) => box.type === "trak");
+ expect(traks).toHaveLength(2);
+ const stbl = child(
+ child(child(traks[0] ?? moov, "mdia") ?? moov, "minf") ?? moov,
+ "stbl",
+ );
+ const co64 = stbl && child(stbl, "co64");
+ expect(co64 && u64(co64.body, 8)).toBe(header.byteLength);
+ });
+});
diff --git a/apps/render-farm/src/mp4.ts b/apps/render-farm/src/mp4.ts
new file mode 100644
index 000000000..7be9d3062
--- /dev/null
+++ b/apps/render-farm/src/mp4.ts
@@ -0,0 +1,773 @@
+// Just enough ISO BMFF to (1) index a source recording from its moov alone,
+// so chunk workers can download only the bytes their frames need, and (2)
+// write the final export's ftyp+moov once every chunk has reported its
+// sample table. The mdat is assembled by the chunk workers themselves as
+// multipart parts, so this never touches media data.
+
+type Box = { type: string; start: number; headerSize: number; size: number };
+
+function readBoxes(data: Uint8Array, start: number, end: number): Box[] {
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
+ const boxes: Box[] = [];
+ let offset = start;
+ while (offset + 8 <= end) {
+ let size = view.getUint32(offset);
+ const type = String.fromCharCode(...data.subarray(offset + 4, offset + 8));
+ let headerSize = 8;
+ if (size === 1) {
+ size = Number(view.getBigUint64(offset + 8));
+ headerSize = 16;
+ } else if (size === 0) {
+ size = end - offset;
+ }
+ if (size < headerSize || offset + size > end) break;
+ boxes.push({ type, start: offset, headerSize, size });
+ offset += size;
+ }
+ return boxes;
+}
+
+function child(data: Uint8Array, box: Box, type: string, skip = 0) {
+ return readBoxes(
+ data,
+ box.start + box.headerSize + skip,
+ box.start + box.size,
+ ).find((candidate) => candidate.type === type);
+}
+
+function children(data: Uint8Array, box: Box, type: string) {
+ return readBoxes(
+ data,
+ box.start + box.headerSize,
+ box.start + box.size,
+ ).filter((candidate) => candidate.type === type);
+}
+
+/** Top-level layout from the first bytes: where moov lives. */
+export function locateMoov(head: Uint8Array, fileSize: number) {
+ const view = new DataView(head.buffer, head.byteOffset, head.byteLength);
+ let offset = 0;
+ while (offset + 16 <= head.byteLength || offset + 8 <= head.byteLength) {
+ let size = view.getUint32(offset);
+ const type = String.fromCharCode(...head.subarray(offset + 4, offset + 8));
+ if (size === 1) size = Number(view.getBigUint64(offset + 8));
+ else if (size === 0) size = fileSize - offset;
+ if (type === "moov") return { start: offset, size };
+ if (size < 8) break;
+ offset += size;
+ if (offset >= fileSize) break;
+ if (offset + 16 > head.byteLength) {
+ // Past the head we fetched: the next box header is at `offset`.
+ return { next: offset };
+ }
+ }
+ return null;
+}
+
+export type TrackIndex = {
+ timescale: number;
+ /** Per sample, in decode order. */
+ times: Float64Array;
+ offsets: Float64Array;
+ sizes: Uint32Array;
+ keyframes: Uint32Array;
+};
+
+/** Index the first video track of a moov box (bytes = the whole moov). */
+export function indexVideoTrack(moov: Uint8Array): TrackIndex {
+ const root = readBoxes(moov, 0, moov.byteLength).find(
+ (box) => box.type === "moov",
+ );
+ if (!root) throw new Error("not a moov box");
+ const view = new DataView(moov.buffer, moov.byteOffset, moov.byteLength);
+ for (const trak of children(moov, root, "trak")) {
+ const mdia = child(moov, trak, "mdia");
+ if (!mdia) continue;
+ const hdlr = child(moov, mdia, "hdlr");
+ if (!hdlr) continue;
+ const handler = String.fromCharCode(
+ ...moov.subarray(
+ hdlr.start + hdlr.headerSize + 8,
+ hdlr.start + hdlr.headerSize + 12,
+ ),
+ );
+ if (handler !== "vide") continue;
+ const mdhd = child(moov, mdia, "mdhd");
+ const minf = child(moov, mdia, "minf");
+ const stbl = minf && child(moov, minf, "stbl");
+ if (!mdhd || !stbl) continue;
+ const version = moov[mdhd.start + mdhd.headerSize] ?? 0;
+ const timescale = view.getUint32(
+ mdhd.start + mdhd.headerSize + (version === 1 ? 20 : 12),
+ );
+ const body = (type: string) => {
+ const box = child(moov, stbl, type);
+ return box ? box.start + box.headerSize : null;
+ };
+
+ const stsz = body("stsz");
+ if (stsz === null) throw new Error("no stsz");
+ const uniform = view.getUint32(stsz + 4);
+ const count = view.getUint32(stsz + 8);
+ const sizes = new Uint32Array(count);
+ for (let index = 0; index < count; index++) {
+ sizes[index] = uniform || view.getUint32(stsz + 12 + index * 4);
+ }
+
+ const times = new Float64Array(count);
+ const stts = body("stts");
+ if (stts !== null) {
+ let sample = 0;
+ let time = 0;
+ const entries = view.getUint32(stts + 4);
+ for (let entry = 0; entry < entries; entry++) {
+ const sampleCount = view.getUint32(stts + 8 + entry * 8);
+ const delta = view.getUint32(stts + 12 + entry * 8);
+ for (let index = 0; index < sampleCount && sample < count; index++) {
+ times[sample++] = time / timescale;
+ time += delta;
+ }
+ }
+ }
+
+ const chunkOffsets: number[] = [];
+ const stco = body("stco");
+ const co64 = body("co64");
+ if (stco !== null) {
+ const entries = view.getUint32(stco + 4);
+ for (let index = 0; index < entries; index++) {
+ chunkOffsets.push(view.getUint32(stco + 8 + index * 4));
+ }
+ } else if (co64 !== null) {
+ const entries = view.getUint32(co64 + 4);
+ for (let index = 0; index < entries; index++) {
+ chunkOffsets.push(Number(view.getBigUint64(co64 + 8 + index * 8)));
+ }
+ }
+ const stsc = body("stsc");
+ if (stsc === null) throw new Error("no stsc");
+ const stscEntries = view.getUint32(stsc + 4);
+ const offsets = new Float64Array(count);
+ let sample = 0;
+ for (let entry = 0; entry < stscEntries; entry++) {
+ const firstChunk = view.getUint32(stsc + 8 + entry * 12) - 1;
+ const perChunk = view.getUint32(stsc + 12 + entry * 12);
+ const lastChunk =
+ entry + 1 < stscEntries
+ ? view.getUint32(stsc + 8 + (entry + 1) * 12) - 1
+ : chunkOffsets.length;
+ for (let chunk = firstChunk; chunk < lastChunk; chunk++) {
+ let offset = chunkOffsets[chunk] ?? 0;
+ for (let index = 0; index < perChunk && sample < count; index++) {
+ offsets[sample] = offset;
+ offset += sizes[sample] ?? 0;
+ sample++;
+ }
+ }
+ }
+
+ const stss = body("stss");
+ let keyframes: Uint32Array;
+ if (stss === null) {
+ keyframes = Uint32Array.from({ length: count }, (_, index) => index);
+ } else {
+ const entries = view.getUint32(stss + 4);
+ keyframes = new Uint32Array(entries);
+ for (let index = 0; index < entries; index++) {
+ keyframes[index] = view.getUint32(stss + 8 + index * 4) - 1;
+ }
+ }
+ return { timescale, times, offsets, sizes, keyframes };
+ }
+ throw new Error("no video track");
+}
+
+/**
+ * Byte range covering every sample a decoder needs for [from, to] seconds:
+ * back to the keyframe at or before `from`, forward through `to`.
+ */
+export function byteRangeFor(index: TrackIndex, from: number, to: number) {
+ const count = index.times.length;
+ if (count === 0) return null;
+ // Last keyframe at or before `from`. Planning calls this once per 2 s span
+ // per source file, so a linear scan was O(keyframes) each time (~0.5 s of
+ // planning for a 2 h export).
+ let low = 0;
+ let high = index.keyframes.length - 1;
+ let first = 0;
+ while (low <= high) {
+ const middle = (low + high) >> 1;
+ const key = index.keyframes[middle] ?? 0;
+ if ((index.times[key] ?? 0) <= from) {
+ first = key;
+ low = middle + 1;
+ } else {
+ high = middle - 1;
+ }
+ }
+ let last = count - 1;
+ for (let sample = first; sample < count; sample++) {
+ if ((index.times[sample] ?? 0) > to) {
+ last = sample;
+ break;
+ }
+ }
+ let start = Number.POSITIVE_INFINITY;
+ let end = 0;
+ for (let sample = first; sample <= last; sample++) {
+ const offset = index.offsets[sample] ?? 0;
+ start = Math.min(start, offset);
+ end = Math.max(end, offset + (index.sizes[sample] ?? 0));
+ }
+ return { start, end };
+}
+
+// ---------------------------------------------------------------- writer ---
+
+class Writer {
+ private chunks: Uint8Array[] = [];
+ length = 0;
+
+ bytes(value: Uint8Array) {
+ this.chunks.push(value);
+ this.length += value.byteLength;
+ }
+
+ u8(value: number) {
+ this.bytes(Uint8Array.of(value & 0xff));
+ }
+
+ u16(value: number) {
+ const buffer = new Uint8Array(2);
+ new DataView(buffer.buffer).setUint16(0, value);
+ this.bytes(buffer);
+ }
+
+ u32(value: number) {
+ const buffer = new Uint8Array(4);
+ new DataView(buffer.buffer).setUint32(0, value >>> 0);
+ this.bytes(buffer);
+ }
+
+ u64(value: number) {
+ const buffer = new Uint8Array(8);
+ new DataView(buffer.buffer).setBigUint64(0, BigInt(value));
+ this.bytes(buffer);
+ }
+
+ i16(value: number) {
+ const buffer = new Uint8Array(2);
+ new DataView(buffer.buffer).setInt16(0, value);
+ this.bytes(buffer);
+ }
+
+ ascii(value: string) {
+ this.bytes(new TextEncoder().encode(value));
+ }
+
+ zeros(count: number) {
+ this.bytes(new Uint8Array(count));
+ }
+
+ finish() {
+ const out = new Uint8Array(this.length);
+ let offset = 0;
+ for (const chunk of this.chunks) {
+ out.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return out;
+ }
+}
+
+export function box(type: string, ...parts: Uint8Array[]) {
+ const writer = new Writer();
+ const length = parts.reduce((sum, part) => sum + part.byteLength, 8);
+ writer.u32(length);
+ writer.ascii(type);
+ for (const part of parts) writer.bytes(part);
+ return writer.finish();
+}
+
+export function fullBox(
+ type: string,
+ version: number,
+ flags: number,
+ ...parts: Uint8Array[]
+) {
+ const header = new Writer();
+ header.u8(version);
+ header.u8(flags >> 16);
+ header.u16(flags & 0xffff);
+ return box(type, header.finish(), ...parts);
+}
+
+export function build(fn: (writer: Writer) => void) {
+ const writer = new Writer();
+ fn(writer);
+ return writer.finish();
+}
+
+export const MATRIX = [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];
+
+/** Annex B SPS/PPS -> avcC. */
+export function avcC(annexB: Uint8Array) {
+ const nals: Uint8Array[] = [];
+ let index = 0;
+ const starts: [number, number][] = [];
+ while (index + 3 <= annexB.length) {
+ if (annexB[index] === 0 && annexB[index + 1] === 0) {
+ if (annexB[index + 2] === 1) {
+ starts.push([index, 3]);
+ index += 3;
+ continue;
+ }
+ if (annexB[index + 2] === 0 && annexB[index + 3] === 1) {
+ starts.push([index, 4]);
+ index += 4;
+ continue;
+ }
+ }
+ index++;
+ }
+ for (let position = 0; position < starts.length; position++) {
+ const [start, prefix] = starts[position] as [number, number];
+ const end = starts[position + 1]?.[0] ?? annexB.length;
+ nals.push(annexB.subarray(start + prefix, end));
+ }
+ const sps = nals.filter((nal) => ((nal[0] ?? 0) & 0x1f) === 7);
+ const pps = nals.filter((nal) => ((nal[0] ?? 0) & 0x1f) === 8);
+ const first = sps[0];
+ if (!first) throw new Error("no SPS in encoder extradata");
+ return build((writer) => {
+ writer.u8(1);
+ writer.u8(first[1] ?? 0);
+ writer.u8(first[2] ?? 0);
+ writer.u8(first[3] ?? 0);
+ writer.u8(0xff);
+ writer.u8(0xe0 | sps.length);
+ for (const nal of sps) {
+ writer.u16(nal.length);
+ writer.bytes(nal);
+ }
+ writer.u8(pps.length);
+ for (const nal of pps) {
+ writer.u16(nal.length);
+ writer.bytes(nal);
+ }
+ const profile = first[1] ?? 0;
+ if ([100, 110, 122, 144].includes(profile)) {
+ writer.u8(0xfc | 1);
+ writer.u8(0xf8);
+ writer.u8(0xf8);
+ writer.u8(0);
+ }
+ });
+}
+
+export function esds(asc: Uint8Array, bitrate: number) {
+ const descriptor = (tag: number, body: Uint8Array) =>
+ build((writer) => {
+ writer.u8(tag);
+ writer.u8(0x80);
+ writer.u8(0x80);
+ writer.u8(0x80);
+ writer.u8(body.length);
+ writer.bytes(body);
+ });
+ const decoderSpecific = descriptor(0x05, asc);
+ const decoderConfig = descriptor(
+ 0x04,
+ build((writer) => {
+ writer.u8(0x40);
+ writer.u8(0x15);
+ writer.u8(0);
+ writer.u16(0);
+ writer.u32(bitrate);
+ writer.u32(bitrate);
+ writer.bytes(decoderSpecific);
+ }),
+ );
+ const sl = descriptor(0x06, Uint8Array.of(2));
+ const es = descriptor(
+ 0x03,
+ build((writer) => {
+ writer.u16(2);
+ writer.u8(0);
+ writer.bytes(decoderConfig);
+ writer.bytes(sl);
+ }),
+ );
+ return fullBox("esds", 0, 0, es);
+}
+
+/** Consecutive runs of samples in the file ("chunks" in MP4 terms). */
+export type Run = { first: number; count: number; offset: number };
+
+export type TrackTable = {
+ sizes: Uint32Array;
+ runs: Run[];
+};
+
+function sampleTable(
+ table: TrackTable,
+ stsd: Uint8Array,
+ stts: [number, number][],
+ sync: Uint32Array | null,
+) {
+ const parts: Uint8Array[] = [stsd];
+ parts.push(
+ fullBox(
+ "stts",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(stts.length);
+ for (const [count, delta] of stts) {
+ writer.u32(count);
+ writer.u32(delta);
+ }
+ }),
+ ),
+ );
+ if (sync) {
+ parts.push(
+ fullBox(
+ "stss",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(sync.length);
+ for (const sample of sync) writer.u32(sample + 1);
+ }),
+ ),
+ );
+ }
+ const stsc: [number, number][] = [];
+ table.runs.forEach((run, index) => {
+ const last = stsc[stsc.length - 1];
+ if (!last || last[1] !== run.count) stsc.push([index + 1, run.count]);
+ });
+ parts.push(
+ fullBox(
+ "stsc",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(stsc.length);
+ for (const [firstChunk, count] of stsc) {
+ writer.u32(firstChunk);
+ writer.u32(count);
+ writer.u32(1);
+ }
+ }),
+ ),
+ );
+ parts.push(
+ fullBox(
+ "stsz",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(table.sizes.length);
+ for (const size of table.sizes) writer.u32(size);
+ }),
+ ),
+ );
+ parts.push(
+ fullBox(
+ "co64",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(table.runs.length);
+ for (const run of table.runs) writer.u64(run.offset);
+ }),
+ ),
+ );
+ return box("stbl", ...parts);
+}
+
+export function dinf() {
+ return box(
+ "dinf",
+ fullBox(
+ "dref",
+ 0,
+ 0,
+ build((writer) => writer.u32(1)),
+ fullBox("url ", 0, 1),
+ ),
+ );
+}
+
+export const tkhd = (
+ id: number,
+ duration: number,
+ audio: boolean,
+ width: number,
+ height: number,
+) =>
+ fullBox(
+ "tkhd",
+ 0,
+ 3,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(0);
+ writer.u32(id);
+ writer.u32(0);
+ writer.u32(duration);
+ writer.zeros(8);
+ writer.u16(0);
+ writer.u16(audio ? 1 : 0);
+ writer.u16(audio ? 0x100 : 0);
+ writer.u16(0);
+ for (const value of MATRIX) writer.u32(value);
+ writer.u32(audio ? 0 : width << 16);
+ writer.u32(audio ? 0 : height << 16);
+ }),
+ );
+
+export const mdhd = (timescale: number, duration: number) =>
+ fullBox(
+ "mdhd",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(0);
+ writer.u32(timescale);
+ writer.u32(duration);
+ writer.u16(0x55c4);
+ writer.u16(0);
+ }),
+ );
+
+export const hdlr = (type: string, name: string) =>
+ fullBox(
+ "hdlr",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.ascii(type);
+ writer.zeros(12);
+ writer.ascii(name);
+ writer.u8(0);
+ }),
+ );
+
+export const avc1 = (width: number, height: number, avcCBytes: Uint8Array) =>
+ box(
+ "avc1",
+ build((writer) => {
+ writer.zeros(6);
+ writer.u16(1);
+ writer.zeros(16);
+ writer.u16(width);
+ writer.u16(height);
+ writer.u32(0x480000);
+ writer.u32(0x480000);
+ writer.u32(0);
+ writer.u16(1);
+ writer.zeros(32);
+ writer.u16(0x18);
+ writer.i16(-1);
+ }),
+ box("avcC", avcCBytes),
+ box(
+ "colr",
+ build((writer) => {
+ writer.ascii("nclx");
+ writer.u16(1);
+ writer.u16(1);
+ writer.u16(1);
+ writer.u8(0);
+ }),
+ ),
+ box(
+ "pasp",
+ build((writer) => {
+ writer.u32(1);
+ writer.u32(1);
+ }),
+ ),
+ );
+
+export const mp4a = (asc: Uint8Array) =>
+ box(
+ "mp4a",
+ build((writer) => {
+ writer.zeros(6);
+ writer.u16(1);
+ writer.zeros(8);
+ writer.u16(2);
+ writer.u16(16);
+ writer.zeros(4);
+ writer.u32(48000 << 16);
+ }),
+ esds(asc, 320_000),
+ );
+
+export type HeaderInput = {
+ width: number;
+ height: number;
+ fps: number;
+ video: TrackTable & { keyframes: Uint32Array; avcC: Uint8Array };
+ audio:
+ | (TrackTable & { asc: Uint8Array; totalSamples: number; priming: number })
+ | null;
+ /** Bytes of media data that follow the header (sum of all chunk parts). */
+ payloadSize: number;
+ /** Pad the header to at least this many bytes (S3's 5 MiB part minimum). */
+ minimumSize: number;
+};
+
+/**
+ * ftyp + moov + free padding + mdat header. Run offsets in `input` are
+ * relative to the start of the mdat payload; they are rebased here.
+ */
+export function buildHeader(input: HeaderInput) {
+ const videoTimescale = input.fps * 1000;
+ const frameCount = input.video.sizes.length;
+ const videoDuration = frameCount * 1000;
+ const durationMs = Math.round((frameCount / input.fps) * 1000);
+
+ const make = (headerSize: number) => {
+ const rebase = (runs: Run[]) =>
+ runs.map((run) => ({ ...run, offset: run.offset + headerSize }));
+ const ftyp = box(
+ "ftyp",
+ build((writer) => {
+ writer.ascii("isom");
+ writer.u32(0x200);
+ writer.ascii("isomiso2avc1mp41");
+ }),
+ );
+ const mvhd = fullBox(
+ "mvhd",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(0);
+ writer.u32(0);
+ writer.u32(1000);
+ writer.u32(durationMs);
+ writer.u32(0x10000);
+ writer.u16(0x100);
+ writer.zeros(10);
+ for (const value of MATRIX) writer.u32(value);
+ writer.zeros(24);
+ writer.u32(input.audio ? 3 : 2);
+ }),
+ );
+ const videoTrak = box(
+ "trak",
+ tkhd(1, durationMs, false, input.width, input.height),
+ box(
+ "mdia",
+ mdhd(videoTimescale, videoDuration),
+ hdlr("vide", "VideoHandler"),
+ box(
+ "minf",
+ fullBox("vmhd", 0, 1, new Uint8Array(8)),
+ dinf(),
+ sampleTable(
+ { sizes: input.video.sizes, runs: rebase(input.video.runs) },
+ fullBox(
+ "stsd",
+ 0,
+ 0,
+ build((writer) => writer.u32(1)),
+ avc1(input.width, input.height, input.video.avcC),
+ ),
+ [[frameCount, 1000]],
+ input.video.keyframes,
+ ),
+ ),
+ ),
+ );
+
+ const tracks = [videoTrak];
+ if (input.audio) {
+ const audio = input.audio;
+ const packets = audio.sizes.length;
+ const mediaDuration = packets * 1024;
+ // Skip the encoder's priming samples and trim the padded tail, like
+ // ffmpeg's MP4 muxer does for AAC.
+ const elst = box(
+ "edts",
+ fullBox(
+ "elst",
+ 0,
+ 0,
+ build((writer) => {
+ writer.u32(1);
+ writer.u32(Math.round((audio.totalSamples / 48000) * 1000));
+ writer.u32(audio.priming);
+ writer.u16(1);
+ writer.u16(0);
+ }),
+ ),
+ );
+ tracks.push(
+ box(
+ "trak",
+ tkhd(2, Math.round((audio.totalSamples / 48000) * 1000), true, 0, 0),
+ elst,
+ box(
+ "mdia",
+ mdhd(48000, mediaDuration),
+ hdlr("soun", "SoundHandler"),
+ box(
+ "minf",
+ fullBox("smhd", 0, 0, new Uint8Array(4)),
+ dinf(),
+ sampleTable(
+ { sizes: audio.sizes, runs: rebase(audio.runs) },
+ fullBox(
+ "stsd",
+ 0,
+ 0,
+ build((writer) => writer.u32(1)),
+ mp4a(audio.asc),
+ ),
+ [[packets, 1024]],
+ null,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+ const moov = box("moov", mvhd, ...tracks);
+ return { ftyp, moov };
+ };
+
+ // The moov's size doesn't depend on the offsets (co64 is fixed width), so
+ // measure once, then lay out: ftyp, moov, free padding, 16-byte mdat header.
+ const probe = make(0);
+ const natural = probe.ftyp.byteLength + probe.moov.byteLength + 8 + 16;
+ const headerSize = Math.max(natural, input.minimumSize);
+ const final = make(headerSize);
+ const freeSize =
+ headerSize - final.ftyp.byteLength - final.moov.byteLength - 16;
+ const free = new Uint8Array(freeSize);
+ new DataView(free.buffer).setUint32(0, freeSize);
+ free.set(new TextEncoder().encode("free"), 4);
+ const mdat = new Uint8Array(16);
+ const mdatView = new DataView(mdat.buffer);
+ mdatView.setUint32(0, 1);
+ mdat.set(new TextEncoder().encode("mdat"), 4);
+ mdatView.setBigUint64(8, BigInt(16 + input.payloadSize));
+ const out = new Uint8Array(headerSize);
+ let offset = 0;
+ for (const part of [final.ftyp, final.moov, free, mdat]) {
+ out.set(part, offset);
+ offset += part.byteLength;
+ }
+ if (offset !== headerSize) throw new Error("header layout mismatch");
+ return out;
+}
diff --git a/apps/render-farm/src/planning.test.ts b/apps/render-farm/src/planning.test.ts
new file mode 100644
index 000000000..59fc6c336
--- /dev/null
+++ b/apps/render-farm/src/planning.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, test } from "bun:test";
+import { type ChunkPlanInput, planChunkBoundaries } from "./planning";
+
+const base: ChunkPlanInput = {
+ totalFrames: 1800,
+ fps: 30,
+ slots: 15,
+ targetFrames: 1300,
+ minChunkFrames: 30,
+ leadInFrames: 0,
+};
+
+function expectValid(boundaries: number[], totalFrames: number) {
+ expect(boundaries[0]).toBe(0);
+ expect(boundaries.at(-1)).toBe(totalFrames);
+ for (let index = 1; index < boundaries.length; index++) {
+ expect(boundaries[index] ?? 0).toBeGreaterThan(boundaries[index - 1] ?? 0);
+ }
+}
+
+describe("planChunkBoundaries", () => {
+ test("a short export is one wave across every slot, on whole seconds", () => {
+ const boundaries = planChunkBoundaries(base);
+ expectValid(boundaries, 1800);
+ expect(boundaries.length - 1).toBe(15);
+ for (const boundary of boundaries.slice(0, -1))
+ expect(boundary % 30).toBe(0);
+ });
+
+ test("a long export is whole waves of GOP-aligned chunks", () => {
+ const input = { ...base, totalFrames: 216_000 };
+ const boundaries = planChunkBoundaries(input);
+ expectValid(boundaries, 216_000);
+ expect((boundaries.length - 1) % 15).toBe(0);
+ for (const boundary of boundaries.slice(0, -1))
+ expect(boundary % 60).toBe(0);
+ });
+
+ test("the lead-in splits a short first chunk off long exports", () => {
+ const input = { ...base, totalFrames: 216_000, leadInFrames: 120 };
+ const without = planChunkBoundaries({ ...input, leadInFrames: 0 });
+ const boundaries = planChunkBoundaries(input);
+ expectValid(boundaries, 216_000);
+ expect(boundaries[1]).toBe(120);
+ expect(boundaries.length).toBe(without.length + 1);
+ });
+
+ test("no lead-in when the first chunk is already short", () => {
+ const boundaries = planChunkBoundaries({ ...base, leadInFrames: 120 });
+ expect(boundaries).toEqual(planChunkBoundaries(base));
+ });
+
+ test("maxChunks and pinned chunk counts are honoured", () => {
+ expect(planChunkBoundaries({ ...base, maxChunks: 4 }).length - 1).toBe(4);
+ expect(planChunkBoundaries({ ...base, chunks: 6 }).length - 1).toBe(6);
+ });
+
+ test("never plans more chunks than frames", () => {
+ const boundaries = planChunkBoundaries({
+ ...base,
+ totalFrames: 7,
+ minChunkFrames: 1,
+ });
+ expectValid(boundaries, 7);
+ });
+});
diff --git a/apps/render-farm/src/planning.ts b/apps/render-farm/src/planning.ts
new file mode 100644
index 000000000..49f7b0eda
--- /dev/null
+++ b/apps/render-farm/src/planning.ts
@@ -0,0 +1,68 @@
+export type ChunkPlanInput = {
+ totalFrames: number;
+ fps: number;
+ /** Render slots currently live in the fleet. */
+ slots: number;
+ /** Frames of roughly `chunkWorkSeconds` of render work on one slot. */
+ targetFrames: number;
+ minChunkFrames: number;
+ /** Pin the chunk count (profiling). */
+ chunks?: number;
+ chunksPerSlot?: number;
+ maxChunks?: number;
+ /** Split this many frames off the front as their own chunk (0 = off). */
+ leadInFrames: number;
+};
+
+/**
+ * Chunk boundaries [0, ..., totalFrames]. Short exports get one wave of
+ * chunks across every slot; longer ones whole waves of work-sized chunks
+ * (36 chunks on 30 slots would leave 24 slots idle in a second wave).
+ * Boundaries sit on GOP edges when chunks are long enough, else on whole
+ * seconds; every chunk opens with its own IDR either way.
+ */
+export function planChunkBoundaries(input: ChunkPlanInput) {
+ const { totalFrames, fps } = input;
+ const gop = fps * 2;
+ const slots = Math.max(1, input.slots);
+ let chunkCount: number;
+ if (input.chunks) chunkCount = input.chunks;
+ else if (totalFrames / input.targetFrames <= slots) {
+ chunkCount = Math.min(
+ slots,
+ Math.floor(totalFrames / input.minChunkFrames),
+ );
+ } else {
+ const waves = Math.min(
+ input.chunksPerSlot ?? 6,
+ Math.ceil(totalFrames / input.targetFrames / slots),
+ );
+ chunkCount = Math.min(slots * waves, 2000);
+ }
+ const unit = totalFrames / Math.max(1, chunkCount) >= gop ? gop : fps;
+ const units = Math.ceil(totalFrames / unit);
+ chunkCount = Math.max(
+ 1,
+ Math.min(chunkCount, units, input.maxChunks ?? Number.POSITIVE_INFINITY),
+ );
+ const boundaries: number[] = [];
+ for (let index = 0; index <= chunkCount; index++) {
+ boundaries.push(
+ index === chunkCount
+ ? totalFrames
+ : Math.min(
+ totalFrames,
+ Math.round((index * units) / chunkCount) * unit,
+ ),
+ );
+ }
+ // With HLS the first segment waits for chunk 0's sources to download and
+ // its first GOP to render. A full-size chunk 0 on a 2 h export meant
+ // fetching ~80 s of source first; a short lead-in keeps time to first
+ // play independent of export length.
+ const leadIn = Math.round(input.leadInFrames / gop) * gop;
+ if (leadIn > 0 && (boundaries[1] ?? 0) >= leadIn * 2) {
+ boundaries.splice(1, 0, leadIn);
+ }
+ return boundaries;
+}
diff --git a/apps/render-farm/src/protocol.ts b/apps/render-farm/src/protocol.ts
new file mode 100644
index 000000000..663b5905b
--- /dev/null
+++ b/apps/render-farm/src/protocol.ts
@@ -0,0 +1,120 @@
+import type { FetchStats, FileSpec } from "./materialize";
+import type { Run } from "./mp4";
+
+export const COMPRESSION_BPP = {
+ Maximum: 0.3,
+ Social: 0.15,
+ Web: 0.08,
+ Potato: 0.04,
+} as const;
+
+export type Compression = keyof typeof COMPRESSION_BPP;
+
+export const MIN_PART = 5 * 1024 * 1024;
+
+export type VideoTask = {
+ kind: "video";
+ taskId: string;
+ jobId: string;
+ chunk: number;
+ fps: number;
+ resolution: [number, number];
+ bpp: number;
+ frames: [number, number];
+ /** x264 threads, fixed per job: output bytes must not depend on the machine. */
+ threads: number;
+ files: FileSpec[];
+ upload: {
+ key: string;
+ uploadId: string;
+ firstPart: number;
+ partLimit: number;
+ partTarget: number;
+ /** The final chunk may end in a part smaller than S3's minimum. */
+ isLast: boolean;
+ };
+ audio: { first: number; end: number; coordinator: string } | null;
+ /** Stream playable fMP4 segments to `${prefix}/c<chunk>-<n>.m4s` while rendering. */
+ hls: { prefix: string; segmentFrames: number } | null;
+};
+
+export type SegmentReport = {
+ chunk: number;
+ index: number;
+ /** Global output frames [first, end). */
+ frames: [number, number];
+ key: string;
+ /** The chunk's final segment. */
+ last: boolean;
+ /** Base64 Annex B SPS/PPS, for the init segment. */
+ extradata: string;
+};
+
+export type AudioTask = {
+ kind: "audio";
+ taskId: string;
+ jobId: string;
+ section: number;
+ fps: number;
+ range: [number, number];
+ preroll: number;
+ files: FileSpec[];
+};
+
+export type Task = VideoTask | AudioTask;
+
+export type TaskTimings = {
+ queuedMs: number;
+ fetch: FetchStats;
+ engine: Record<string, number>;
+ engineMs: number;
+ audioWaitMs: number;
+ uploadMs: number;
+ totalMs: number;
+ cpuSeconds: number;
+};
+
+export type VideoResult = {
+ taskId: string;
+ worker: string;
+ sizes: number[];
+ keyframes: number[];
+ extradata: string;
+ width: number;
+ height: number;
+ /** Runs relative to the chunk's first byte; `first` is a global sample index. */
+ videoRuns: Run[];
+ audioRuns: Run[];
+ parts: { partNumber: number; etag: string; size: number }[];
+ bytes: number;
+ paddedBytes: number;
+ timings: TaskTimings;
+};
+
+export type AudioResultMeta = {
+ taskId: string;
+ worker: string;
+ firstPacket: number;
+ sizes: number[];
+ extradata: string;
+ timings: TaskTimings;
+};
+
+export type JobRequest = {
+ recording: string;
+ fps?: number;
+ resolution?: [number, number];
+ compression?: Compression;
+ /** Upper bound on video chunks; defaults to one per registered slot. */
+ maxChunks?: number;
+ minChunkSeconds?: number;
+ chunksPerSlot?: number;
+ /** Target render seconds per chunk. */
+ chunkWorkSeconds?: number;
+ duplicateStragglers?: boolean;
+ label?: string;
+ /** Profiling: export only the first N frames, without audio. */
+ frameLimit?: number;
+ /** Pin the chunk count (profiling). */
+ chunks?: number;
+};
diff --git a/apps/render-farm/src/s3.ts b/apps/render-farm/src/s3.ts
new file mode 100644
index 000000000..ab9be72d3
--- /dev/null
+++ b/apps/render-farm/src/s3.ts
@@ -0,0 +1,439 @@
+import { createHash, createHmac } from "node:crypto";
+
+// Minimal SigV4 S3 client. Bun's built-in client can't upload a multipart
+// part under a caller-chosen part number, which is the whole trick here:
+// every chunk worker PUTs its bytes straight into the final object's
+// multipart upload, so assembly never moves video data again.
+
+export type S3Config = {
+ endpoint: string;
+ region: string;
+ bucket: string;
+ accessKeyId: string;
+ secretAccessKey: string;
+ sessionToken?: string;
+ virtualHost: boolean;
+ /** Use the EC2 instance role (IMDSv2) instead of static keys. */
+ imds?: boolean;
+};
+
+export function s3ConfigFromEnv(env = process.env): S3Config {
+ const required = (name: string) => {
+ const value = env[name];
+ if (!value) throw new Error(`${name} is not set`);
+ return value;
+ };
+ const imds = env.RF_S3_IMDS === "1";
+ return {
+ endpoint: required("RF_S3_ENDPOINT"),
+ region: env.RF_S3_REGION || "auto",
+ bucket: required("RF_S3_BUCKET"),
+ accessKeyId: imds ? "" : required("RF_S3_ACCESS_KEY_ID"),
+ secretAccessKey: imds ? "" : required("RF_S3_SECRET_ACCESS_KEY"),
+ virtualHost: env.RF_S3_URL_STYLE !== "path",
+ imds,
+ };
+}
+
+const EMPTY_SHA = createHash("sha256").update("").digest("hex");
+
+function encodeKey(key: string) {
+ return key
+ .split("/")
+ .map((part) => encodeURIComponent(part))
+ .join("/");
+}
+
+function hmac(key: Buffer | string, value: string) {
+ return createHmac("sha256", key).update(value).digest();
+}
+
+export class S3 {
+ private expiresAt = 0;
+ private refreshing: Promise<void> | null = null;
+
+ constructor(readonly config: S3Config) {}
+
+ /** Refresh instance-role credentials from IMDSv2 when close to expiry. */
+ async ready() {
+ if (!this.config.imds || Date.now() < this.expiresAt - 5 * 60_000) return;
+ this.refreshing ??= (async () => {
+ const token = await (
+ await fetch("http://169.254.169.254/latest/api/token", {
+ method: "PUT",
+ headers: { "x-aws-ec2-metadata-token-ttl-seconds": "21600" },
+ })
+ ).text();
+ const headers = { "x-aws-ec2-metadata-token": token };
+ const base =
+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/";
+ const role = (await (await fetch(base, { headers })).text())
+ .trim()
+ .split("\n")[0];
+ const credentials = (await (
+ await fetch(`${base}${role}`, { headers })
+ ).json()) as {
+ AccessKeyId: string;
+ SecretAccessKey: string;
+ Token: string;
+ Expiration: string;
+ };
+ this.config.accessKeyId = credentials.AccessKeyId;
+ this.config.secretAccessKey = credentials.SecretAccessKey;
+ this.config.sessionToken = credentials.Token;
+ this.expiresAt = Date.parse(credentials.Expiration);
+ })().finally(() => {
+ this.refreshing = null;
+ });
+ await this.refreshing;
+ }
+
+ private target(key: string) {
+ const endpoint = new URL(this.config.endpoint);
+ if (this.config.virtualHost) {
+ return {
+ host: `${this.config.bucket}.${endpoint.host}`,
+ path: `/${encodeKey(key)}`,
+ origin: `${endpoint.protocol}//${this.config.bucket}.${endpoint.host}`,
+ };
+ }
+ return {
+ host: endpoint.host,
+ path: `/${this.config.bucket}/${encodeKey(key)}`,
+ origin: `${endpoint.protocol}//${endpoint.host}`,
+ };
+ }
+
+ private signingKey(date: string) {
+ const kDate = hmac(`AWS4${this.config.secretAccessKey}`, date);
+ const kRegion = hmac(kDate, this.config.region);
+ const kService = hmac(kRegion, "s3");
+ return hmac(kService, "aws4_request");
+ }
+
+ private canonicalQuery(query: Record<string, string>) {
+ return Object.keys(query)
+ .sort()
+ .map(
+ (name) =>
+ `${encodeURIComponent(name)}=${encodeURIComponent(query[name] ?? "")}`,
+ )
+ .join("&");
+ }
+
+ sign(
+ method: string,
+ key: string,
+ query: Record<string, string> = {},
+ headers: Record<string, string> = {},
+ payloadHash = "UNSIGNED-PAYLOAD",
+ ) {
+ const { host, path, origin } = this.target(key);
+ const now = new Date();
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
+ const date = amzDate.slice(0, 8);
+ const all: Record<string, string> = {
+ ...Object.fromEntries(
+ Object.entries(headers).map(([name, value]) => [
+ name.toLowerCase(),
+ value,
+ ]),
+ ),
+ host,
+ "x-amz-date": amzDate,
+ "x-amz-content-sha256": payloadHash,
+ ...(this.config.sessionToken
+ ? { "x-amz-security-token": this.config.sessionToken }
+ : {}),
+ };
+ const names = Object.keys(all).sort();
+ const canonicalHeaders = names
+ .map((name) => `${name}:${String(all[name]).trim()}\n`)
+ .join("");
+ const signedHeaders = names.join(";");
+ const canonicalQuery = this.canonicalQuery(query);
+ const canonical = [
+ method,
+ path,
+ canonicalQuery,
+ canonicalHeaders,
+ signedHeaders,
+ payloadHash,
+ ].join("\n");
+ const scope = `${date}/${this.config.region}/s3/aws4_request`;
+ const toSign = [
+ "AWS4-HMAC-SHA256",
+ amzDate,
+ scope,
+ createHash("sha256").update(canonical).digest("hex"),
+ ].join("\n");
+ const signature = createHmac("sha256", this.signingKey(date))
+ .update(toSign)
+ .digest("hex");
+ const { host: _host, ...sendHeaders } = all;
+ return {
+ url: `${origin}${path}${canonicalQuery ? `?${canonicalQuery}` : ""}`,
+ headers: {
+ ...sendHeaders,
+ authorization: `AWS4-HMAC-SHA256 Credential=${this.config.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
+ },
+ };
+ }
+
+ presign(
+ method: string,
+ key: string,
+ expiresSeconds = 3600,
+ query: Record<string, string> = {},
+ ) {
+ const { host, path, origin } = this.target(key);
+ const amzDate = new Date().toISOString().replace(/[:-]|\.\d{3}/g, "");
+ const date = amzDate.slice(0, 8);
+ const scope = `${date}/${this.config.region}/s3/aws4_request`;
+ const all = {
+ ...query,
+ "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
+ "X-Amz-Credential": `${this.config.accessKeyId}/${scope}`,
+ "X-Amz-Date": amzDate,
+ "X-Amz-Expires": String(expiresSeconds),
+ "X-Amz-SignedHeaders": "host",
+ ...(this.config.sessionToken
+ ? { "X-Amz-Security-Token": this.config.sessionToken }
+ : {}),
+ };
+ const canonicalQuery = this.canonicalQuery(all);
+ const canonical = [
+ method,
+ path,
+ canonicalQuery,
+ `host:${host}\n`,
+ "host",
+ "UNSIGNED-PAYLOAD",
+ ].join("\n");
+ const toSign = [
+ "AWS4-HMAC-SHA256",
+ amzDate,
+ scope,
+ createHash("sha256").update(canonical).digest("hex"),
+ ].join("\n");
+ const signature = createHmac("sha256", this.signingKey(date))
+ .update(toSign)
+ .digest("hex");
+ return `${origin}${path}?${canonicalQuery}&X-Amz-Signature=${signature}`;
+ }
+
+ private async send(
+ method: string,
+ key: string,
+ options: {
+ query?: Record<string, string>;
+ headers?: Record<string, string>;
+ body?: Uint8Array | string;
+ expect?: number[];
+ } = {},
+ ) {
+ const payloadHash =
+ options.body === undefined
+ ? EMPTY_SHA
+ : typeof options.body === "string"
+ ? createHash("sha256").update(options.body).digest("hex")
+ : "UNSIGNED-PAYLOAD";
+ await this.ready();
+ for (let attempt = 0; ; attempt++) {
+ const signed = this.sign(
+ method,
+ key,
+ options.query,
+ options.headers,
+ payloadHash,
+ );
+ let response: Response;
+ try {
+ response = await fetch(signed.url, {
+ method,
+ headers: signed.headers,
+ body: options.body as BodyInit | undefined,
+ });
+ } catch (error) {
+ // Object stores drop connections under bursty fan-out; back off
+ // with jitter rather than failing the chunk.
+ if (attempt < 8) {
+ await Bun.sleep(
+ Math.min(8000, 250 * 2 ** attempt) * (0.5 + Math.random()),
+ );
+ continue;
+ }
+ throw error;
+ }
+ const expect = options.expect ?? [200, 204, 206];
+ if (expect.includes(response.status)) return response;
+ const text = await response.text();
+ if (
+ (response.status >= 500 ||
+ response.status === 429 ||
+ response.status === 408) &&
+ attempt < 8
+ ) {
+ await Bun.sleep(
+ Math.min(8000, 250 * 2 ** attempt) * (0.5 + Math.random()),
+ );
+ continue;
+ }
+ throw new Error(
+ `S3 ${method} ${key} -> ${response.status}: ${text.slice(0, 300)}`,
+ );
+ }
+ }
+
+ async head(key: string) {
+ const response = await this.send("HEAD", key, { expect: [200, 404] });
+ if (response.status === 404) return null;
+ return { size: Number(response.headers.get("content-length") ?? 0) };
+ }
+
+ async getRange(key: string, start: number, endInclusive: number) {
+ const response = await this.send("GET", key, {
+ headers: { range: `bytes=${start}-${endInclusive}` },
+ });
+ return new Uint8Array(await response.arrayBuffer());
+ }
+
+ async getStream(key: string, start?: number, endInclusive?: number) {
+ const response = await this.send("GET", key, {
+ headers:
+ start === undefined
+ ? {}
+ : { range: `bytes=${start}-${endInclusive ?? ""}` },
+ });
+ if (!response.body) throw new Error(`S3 GET ${key} returned no body`);
+ return response.body;
+ }
+
+ async get(key: string) {
+ const response = await this.send("GET", key);
+ return new Uint8Array(await response.arrayBuffer());
+ }
+
+ async put(key: string, body: Uint8Array | string, contentType?: string) {
+ await this.send("PUT", key, {
+ body,
+ headers: contentType ? { "content-type": contentType } : {},
+ });
+ }
+
+ async createMultipart(key: string, contentType: string) {
+ const response = await this.send("POST", key, {
+ query: { uploads: "" },
+ headers: { "content-type": contentType },
+ });
+ const text = await response.text();
+ const match = text.match(/<UploadId>([^<]+)<\/UploadId>/);
+ if (!match?.[1]) throw new Error(`no UploadId in ${text.slice(0, 200)}`);
+ return match[1];
+ }
+
+ async uploadPart(
+ key: string,
+ uploadId: string,
+ partNumber: number,
+ body: Uint8Array,
+ ) {
+ const response = await this.send("PUT", key, {
+ query: { partNumber: String(partNumber), uploadId },
+ body,
+ });
+ const etag = response.headers.get("etag");
+ if (!etag) throw new Error(`no ETag for part ${partNumber}`);
+ return etag;
+ }
+
+ async completeMultipart(
+ key: string,
+ uploadId: string,
+ parts: { partNumber: number; etag: string }[],
+ ) {
+ const body = `<CompleteMultipartUpload>${parts
+ .sort((a, b) => a.partNumber - b.partNumber)
+ .map(
+ (part) =>
+ `<Part><PartNumber>${part.partNumber}</PartNumber><ETag>${part.etag}</ETag></Part>`,
+ )
+ .join("")}</CompleteMultipartUpload>`;
+ const response = await this.send("POST", key, {
+ query: { uploadId },
+ body,
+ headers: { "content-type": "application/xml" },
+ });
+ const text = await response.text();
+ if (text.includes("<Error>")) {
+ throw new Error(`complete multipart failed: ${text.slice(0, 300)}`);
+ }
+ }
+
+ async listParts(key: string, uploadId: string) {
+ const parts: { partNumber: number; etag: string; size: number }[] = [];
+ let marker = "0";
+ for (;;) {
+ const response = await this.send("GET", key, {
+ query: { uploadId, "max-parts": "1000", "part-number-marker": marker },
+ });
+ const text = await response.text();
+ for (const match of text.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
+ const body = match[1] ?? "";
+ parts.push({
+ partNumber: Number(
+ body.match(/<PartNumber>(\d+)<\/PartNumber>/)?.[1],
+ ),
+ etag: decodeXml(body.match(/<ETag>([^<]+)<\/ETag>/)?.[1] ?? ""),
+ size: Number(body.match(/<Size>(\d+)<\/Size>/)?.[1]),
+ });
+ }
+ const next = text.match(
+ /<NextPartNumberMarker>(\d+)<\/NextPartNumberMarker>/,
+ )?.[1];
+ if (!/<IsTruncated>true<\/IsTruncated>/.test(text) || !next) break;
+ marker = next;
+ }
+ return parts;
+ }
+
+ async abortMultipart(key: string, uploadId: string) {
+ await this.send("DELETE", key, {
+ query: { uploadId },
+ expect: [204, 200, 404],
+ });
+ }
+
+ async list(prefix: string) {
+ const keys: { key: string; size: number }[] = [];
+ let token: string | undefined;
+ do {
+ const query: Record<string, string> = { "list-type": "2", prefix };
+ if (token) query["continuation-token"] = token;
+ const response = await this.send("GET", "", { query });
+ const text = await response.text();
+ for (const match of text.matchAll(
+ /<Key>([^<]+)<\/Key>[\s\S]*?<Size>(\d+)<\/Size>/g,
+ )) {
+ keys.push({ key: decodeXml(match[1] ?? ""), size: Number(match[2]) });
+ }
+ token = text.match(
+ /<NextContinuationToken>([^<]+)<\/NextContinuationToken>/,
+ )?.[1];
+ } while (token);
+ return keys;
+ }
+
+ async delete(key: string) {
+ await this.send("DELETE", key, { expect: [204, 200, 404] });
+ }
+}
+
+function decodeXml(value: string) {
+ return value
+ .replaceAll("&amp;", "&")
+ .replaceAll("&lt;", "<")
+ .replaceAll("&gt;", ">")
+ .replaceAll("&quot;", '"')
+ .replaceAll("&apos;", "'");
+}
diff --git a/apps/render-farm/src/scheduler.test.ts b/apps/render-farm/src/scheduler.test.ts
new file mode 100644
index 000000000..c447fa60e
--- /dev/null
+++ b/apps/render-farm/src/scheduler.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, test } from "bun:test";
+import {
+ pickQueued,
+ type SchedulableJob,
+ type SchedulableState,
+ type SchedulerOptions,
+} from "./scheduler";
+
+const options: SchedulerOptions = { headChunks: 2, fifo: false, now: 1_000 };
+
+function job(
+ id: string,
+ requestedAt: number,
+ chunks: number,
+ overrides: Partial<SchedulableJob> = {},
+): SchedulableJob {
+ return {
+ id,
+ status: "rendering",
+ requestedAt,
+ chunks: Array.from({ length: chunks }, (_, index) => index),
+ finishedChunks: new Set<number>(),
+ runningTasks: 0,
+ ...overrides,
+ };
+}
+
+function video(
+ jobId: string,
+ chunk: number,
+ heldUntil?: number,
+): SchedulableState {
+ return { task: { kind: "video", jobId, chunk }, state: "queued", heldUntil };
+}
+
+function audio(jobId: string, section: number): SchedulableState {
+ return { task: { kind: "audio", jobId, section }, state: "queued" };
+}
+
+const any = () => true;
+
+describe("pickQueued", () => {
+ test("a new job's first chunks outrank a long job's remaining work", () => {
+ const long = job("long", 0, 40, {
+ runningTasks: 15,
+ finishedChunks: new Set([0, 1, 2]),
+ });
+ const short = job("short", 500, 4);
+ const queue = [
+ video("long", 20),
+ video("long", 21),
+ video("short", 0),
+ video("short", 1),
+ ];
+ expect(pickQueued(queue, [long, short], any, options)).toBe(2);
+ });
+
+ test("among non-gating work the least-served job goes first", () => {
+ const busy = job("busy", 0, 40, {
+ runningTasks: 10,
+ finishedChunks: new Set([0, 1]),
+ });
+ const idle = job("idle", 100, 40, {
+ runningTasks: 1,
+ finishedChunks: new Set([0, 1]),
+ });
+ const queue = [video("busy", 30), video("idle", 30)];
+ expect(pickQueued(queue, [busy, idle], any, options)).toBe(1);
+ });
+
+ test("ties go to the older job, then the earlier chunk", () => {
+ const older = job("older", 0, 10);
+ const newer = job("newer", 50, 10);
+ const queue = [video("newer", 0), video("older", 5), video("older", 0)];
+ expect(pickQueued(queue, [older, newer], any, options)).toBe(2);
+ });
+
+ test("held tasks wait until their hold expires", () => {
+ const resumed = job("resumed", 0, 4);
+ const queue = [video("resumed", 0, 2_000), video("resumed", 1)];
+ expect(pickQueued(queue, [resumed], any, options)).toBe(1);
+ expect(pickQueued(queue, [resumed], any, { ...options, now: 3_000 })).toBe(
+ 0,
+ );
+ });
+
+ test("slots only receive the task kinds they accept", () => {
+ const queue = [video("a", 0), audio("a", 0)];
+ expect(
+ pickQueued(queue, [job("a", 0, 2)], (kind) => kind === "audio", options),
+ ).toBe(1);
+ });
+
+ test("the first audio section of a job is playback-gating", () => {
+ const long = job("long", 0, 40, {
+ runningTasks: 20,
+ finishedChunks: new Set([0, 1]),
+ });
+ const fresh = job("fresh", 900, 4, { runningTasks: 0 });
+ const queue = [audio("long", 7), audio("fresh", 0)];
+ expect(pickQueued(queue, [long, fresh], any, options)).toBe(1);
+ });
+
+ test("fifo mode takes the first eligible task", () => {
+ const queue = [
+ { ...video("a", 3), state: "running" as const },
+ video("a", 4),
+ video("b", 0),
+ ];
+ expect(
+ pickQueued(queue, [job("a", 0, 8), job("b", 1, 2)], any, {
+ ...options,
+ fifo: true,
+ }),
+ ).toBe(1);
+ });
+
+ test("returns -1 when nothing is eligible", () => {
+ expect(pickQueued([], [], any, options)).toBe(-1);
+ });
+});
diff --git a/apps/render-farm/src/scheduler.ts b/apps/render-farm/src/scheduler.ts
new file mode 100644
index 000000000..e1b6b84ab
--- /dev/null
+++ b/apps/render-farm/src/scheduler.ts
@@ -0,0 +1,94 @@
+export type SchedulableTask =
+ | { kind: "video"; jobId: string; chunk: number }
+ | { kind: "audio"; jobId: string; section: number };
+
+export type SchedulableState = {
+ task: SchedulableTask;
+ state: "queued" | "running" | "done";
+ heldUntil?: number;
+};
+
+export type SchedulableJob = {
+ id: string;
+ status: string;
+ requestedAt: number;
+ /** Chunk indices in playback order. */
+ chunks: number[];
+ finishedChunks: { has(chunk: number): boolean };
+ runningTasks: number;
+};
+
+export type SchedulerOptions = {
+ /** Unfinished chunks per job, from the front, that outrank other work. */
+ headChunks: number;
+ fifo: boolean;
+ now: number;
+};
+
+/**
+ * Index into `queue` of the task a free slot should take, or -1.
+ *
+ * FIFO lets one long export hold every slot while a short one (and its first
+ * playable segment) waits minutes. Instead the order is:
+ * 1. playback-gating work: each job's next unfinished chunks in playback
+ * order (an HLS playlist only grows from the front) and its first audio
+ * section;
+ * 2. fairness: the job currently holding the fewest running tasks;
+ * 3. the older job, then the earlier position in the timeline.
+ */
+export function pickQueued(
+ queue: readonly SchedulableState[],
+ jobs: Iterable<SchedulableJob>,
+ accepts: (kind: SchedulableTask["kind"]) => boolean,
+ options: SchedulerOptions,
+) {
+ const eligible = (state: SchedulableState) =>
+ state.state === "queued" &&
+ accepts(state.task.kind) &&
+ !(state.heldUntil && state.heldUntil > options.now);
+ if (options.fifo) return queue.findIndex(eligible);
+
+ const byId = new Map<string, { job: SchedulableJob; head: Set<number> }>();
+ for (const job of jobs) {
+ if (job.status !== "rendering") continue;
+ const head = new Set<number>();
+ for (const chunk of job.chunks) {
+ if (job.finishedChunks.has(chunk)) continue;
+ head.add(chunk);
+ if (head.size >= options.headChunks) break;
+ }
+ byId.set(job.id, { job, head });
+ }
+
+ let best = -1;
+ let bestKey: number[] | null = null;
+ for (const [index, state] of queue.entries()) {
+ if (!eligible(state)) continue;
+ const task = state.task;
+ const entry = byId.get(task.jobId);
+ const position = task.kind === "video" ? task.chunk : task.section;
+ const gating =
+ task.kind === "video"
+ ? entry?.head.has(task.chunk) === true
+ : position === 0;
+ const key = [
+ gating ? 0 : 1,
+ entry?.job.runningTasks ?? 0,
+ entry?.job.requestedAt ?? 0,
+ position,
+ ];
+ if (!bestKey || compareKeys(key, bestKey) < 0) {
+ best = index;
+ bestKey = key;
+ }
+ }
+ return best;
+}
+
+function compareKeys(a: number[], b: number[]) {
+ for (const [index, value] of a.entries()) {
+ const difference = value - (b[index] ?? 0);
+ if (difference !== 0) return difference;
+ }
+ return 0;
+}
diff --git a/apps/render-farm/src/validate.test.ts b/apps/render-farm/src/validate.test.ts
new file mode 100644
index 000000000..9b68a892a
--- /dev/null
+++ b/apps/render-farm/src/validate.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from "bun:test";
+import { validateJobRequest } from "./validate";
+
+describe("validateJobRequest", () => {
+ test("accepts a typical export", () => {
+ const request = {
+ recording: "recordings/abc123",
+ fps: 30,
+ resolution: [1920, 1080] as [number, number],
+ compression: "Maximum" as const,
+ };
+ expect(validateJobRequest(request)).toEqual(request);
+ });
+
+ test.each([
+ [null, "body must be a JSON object"],
+ [{}, "recording must be a bucket prefix"],
+ [{ recording: "../secrets" }, "recording must be a bucket prefix"],
+ [{ recording: "a/../../b" }, "recording must be a bucket prefix"],
+ [{ recording: "rec", fps: 0 }, "fps must be an integer from 1 to 120"],
+ [{ recording: "rec", fps: 29.97 }, "fps must be an integer from 1 to 120"],
+ [{ recording: "rec", resolution: [99999, 1080] }, "resolution"],
+ [{ recording: "rec", resolution: [1920] }, "resolution"],
+ [
+ { recording: "rec", compression: "Lossless" },
+ "compression must be one of",
+ ],
+ [{ recording: "rec", maxChunks: -1 }, "maxChunks"],
+ [{ recording: "rec", chunkWorkSeconds: Number.NaN }, "chunkWorkSeconds"],
+ [{ recording: "rec", label: "x".repeat(201) }, "label"],
+ ])("rejects %j", (body, message) => {
+ const result = validateJobRequest(body);
+ expect(typeof result).toBe("string");
+ expect(result as string).toContain(message);
+ });
+});
diff --git a/apps/render-farm/src/validate.ts b/apps/render-farm/src/validate.ts
new file mode 100644
index 000000000..1dae6b2c6
--- /dev/null
+++ b/apps/render-farm/src/validate.ts
@@ -0,0 +1,79 @@
+import { COMPRESSION_BPP, type JobRequest } from "./protocol";
+
+/** Rejects malformed or out-of-range export requests before any work starts. */
+export function validateJobRequest(body: unknown): JobRequest | string {
+ if (!body || typeof body !== "object") return "body must be a JSON object";
+ const request = body as Record<string, unknown>;
+ const recording = request.recording;
+ if (
+ typeof recording !== "string" ||
+ !/^[A-Za-z0-9._/-]{1,512}$/.test(recording) ||
+ recording.split("/").includes("..")
+ ) {
+ return "recording must be a bucket prefix";
+ }
+ const integer = (value: unknown, min: number, max: number) =>
+ value === undefined ||
+ (typeof value === "number" &&
+ Number.isInteger(value) &&
+ value >= min &&
+ value <= max);
+ const positive = (value: unknown, max: number) =>
+ value === undefined ||
+ (typeof value === "number" &&
+ Number.isFinite(value) &&
+ value > 0 &&
+ value <= max);
+ if (!integer(request.fps, 1, 120))
+ return "fps must be an integer from 1 to 120";
+ const resolution = request.resolution;
+ if (
+ resolution !== undefined &&
+ !(
+ Array.isArray(resolution) &&
+ resolution.length === 2 &&
+ integer(resolution[0], 16, 7680) &&
+ integer(resolution[1], 16, 4320)
+ )
+ ) {
+ return "resolution must be [width, height] within 16..7680 x 16..4320";
+ }
+ if (
+ request.compression !== undefined &&
+ !(
+ typeof request.compression === "string" &&
+ request.compression in COMPRESSION_BPP
+ )
+ ) {
+ return `compression must be one of ${Object.keys(COMPRESSION_BPP).join(", ")}`;
+ }
+ for (const [field, max] of [
+ ["maxChunks", 5000],
+ ["chunks", 5000],
+ ["chunksPerSlot", 64],
+ ["frameLimit", 10_000_000],
+ ] as const) {
+ if (!integer(request[field], 1, max))
+ return `${field} must be an integer from 1 to ${max}`;
+ }
+ for (const [field, max] of [
+ ["minChunkSeconds", 600],
+ ["chunkWorkSeconds", 600],
+ ] as const) {
+ if (!positive(request[field], max))
+ return `${field} must be a positive number up to ${max}`;
+ }
+ if (
+ request.label !== undefined &&
+ (typeof request.label !== "string" || request.label.length > 200)
+ ) {
+ return "label must be a string of at most 200 characters";
+ }
+ if (
+ request.duplicateStragglers !== undefined &&
+ typeof request.duplicateStragglers !== "boolean"
+ ) {
+ return "duplicateStragglers must be a boolean";
+ }
+ return request as JobRequest;
+}
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
new file mode 100644
index 000000000..7fa4f2483
--- /dev/null
+++ b/apps/render-farm/src/worker.ts
@@ -0,0 +1,874 @@
+import { randomUUID } from "node:crypto";
+import { mkdirSync, rmSync } from "node:fs";
+import { availableParallelism, hostname } from "node:os";
+import { join } from "node:path";
+import { Engine, processCpuSeconds, sampleThreads } from "./engine";
+import { segmentHeader } from "./fmp4";
+import { closesSegment } from "./hls";
+import { ProjectCache } from "./materialize";
+import type { Run } from "./mp4";
+import {
+ type AudioResultMeta,
+ type AudioTask,
+ MIN_PART,
+ type SegmentReport,
+ type Task,
+ type TaskTimings,
+ type VideoResult,
+ type VideoTask,
+} from "./protocol";
+import { S3, s3ConfigFromEnv } from "./s3";
+
+const s3 = new S3(s3ConfigFromEnv());
+const COORDINATOR = (
+ process.env.RF_COORDINATOR_URL ?? "http://127.0.0.1:8080"
+).replace(/\/$/, "");
+const TOKEN = process.env.RF_TOKEN ?? "";
+const ENGINE_BIN = process.env.RF_ENGINE_BIN ?? "cap-render-farm";
+const WORK_DIR = process.env.RF_WORK_DIR ?? "/tmp/rf-worker";
+const CPUS = Number(process.env.RF_CPUS ?? availableParallelism());
+// Measured best on one L4 with 8 vCPUs (g6.2xlarge): 5 render slots overlap
+// decode latency; 4 Studio Sound lanes use the otherwise idle cores.
+const SLOTS = Number(process.env.RF_SLOTS ?? 5);
+const THREADS = Math.max(1, Math.floor(CPUS / SLOTS));
+// CPU-only audio lanes next to the GPU slots: with frames kept on the GPU the
+// host cores sit idle, and Studio Sound sections are pure CPU work. When set,
+// the GPU slots only take video.
+const AUDIO_SLOTS = Number(process.env.RF_AUDIO_SLOTS ?? 4);
+const SLOT_KINDS = AUDIO_SLOTS > 0 ? ["video"] : undefined;
+const PREFETCH_LEAD_MS = Number(process.env.RF_PREFETCH_LEAD_MS ?? 2500);
+const AUDIO_NICE = Number(process.env.RF_AUDIO_NICE ?? 10);
+// A video engine that reports no frames for this long is hung (driver or
+// decoder stall): kill it so the chunk fails over instead of waiting forever.
+const STALL_MS = Number(process.env.RF_STALL_MS ?? 30_000);
+// Recycle an engine whose device has less free VRAM than this after a task,
+// so a slow leak can never grow into CUDA_ERROR_OUT_OF_MEMORY mid-export.
+const MIN_FREE_VRAM_MB = Number(process.env.RF_MIN_FREE_VRAM_MB ?? 3000);
+let degradedFailures: number[] = [];
+const WORKER_ID = `${process.env.RF_WORKER_NAME ?? hostname()}-${randomUUID().slice(0, 6)}`;
+const SERVICE = process.env.RF_SERVICE ?? "local";
+const headers = {
+ "content-type": "application/json",
+ ...(TOKEN ? { authorization: `Bearer ${TOKEN}` } : {}),
+};
+
+const engines = Array.from(
+ { length: SLOTS + AUDIO_SLOTS },
+ (_, slot) =>
+ new Engine(
+ ENGINE_BIN,
+ {
+ LP_NUM_THREADS: String(THREADS),
+ RAYON_NUM_THREADS: String(THREADS),
+ CAP_EXPORT_DISABLE_ZERO_COPY: "1",
+ CAP_RENDER_LOOP_STATS: "1",
+ CAP_DECODER_READAHEAD: process.env.CAP_DECODER_READAHEAD ?? "8",
+ },
+ `slot${slot}`,
+ // Studio Sound lanes are CPU-heavy; on a 4 vCPU host they would
+ // otherwise starve the render slots' decode/encode threads.
+ slot >= SLOTS ? AUDIO_NICE : 0,
+ ),
+);
+// GPU slots create their device and a spare layer set at boot, not on the
+// first task.
+function warm(engine: Engine, slot: number) {
+ if (slot < SLOTS) engine.request("warm", {}).catch(() => {});
+ return engine;
+}
+engines.forEach(warm);
+const caches = new Map<string, ProjectCache>();
+
+function cacheFor(jobId: string) {
+ let cache = caches.get(jobId);
+ if (!cache) {
+ const root = join(WORK_DIR, jobId);
+ mkdirSync(root, { recursive: true });
+ cache = new ProjectCache(s3, root);
+ caches.set(jobId, cache);
+ }
+ return cache;
+}
+
+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;
+ cache.close();
+ caches.delete(jobId);
+ rmSync(join(WORK_DIR, jobId), { recursive: true, force: true });
+ }
+}
+
+const busy = new Map<number, Task>();
+const progress = new Map<
+ number,
+ {
+ taskId: string;
+ kind: "video" | "audio";
+ frames: number;
+ total: number;
+ startedAt: number;
+ lastProgressAt: number;
+ }
+>();
+
+async function post(path: string, body: unknown) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await fetch(`${COORDINATOR}${path}`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ if (!response.ok) throw new Error(`${path} -> ${response.status}`);
+ return response;
+ } catch (error) {
+ if (attempt >= 5) throw error;
+ await Bun.sleep(250 * 2 ** attempt);
+ }
+ }
+}
+
+async function fetchAudio(task: VideoTask) {
+ if (!task.audio) return { sizes: [] as number[], data: new Uint8Array() };
+ return fetchAudioRange(task.jobId, task.audio.first, task.audio.end);
+}
+
+/** AAC packets [from, to) on the global grid; waits until they are rendered. */
+async function fetchAudioRange(jobId: string, from: number, to: number) {
+ if (to <= from) return { sizes: [] as number[], data: new Uint8Array() };
+ const url = `${COORDINATOR}/jobs/${jobId}/audio?from=${from}&to=${to}`;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await fetch(url, { headers });
+ if (!response.ok) throw new Error(`audio -> ${response.status}`);
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ const view = new DataView(bytes.buffer, bytes.byteOffset);
+ const count = view.getUint32(0);
+ const sizes = Array.from({ length: count }, (_, index) =>
+ view.getUint32(4 + index * 4),
+ );
+ return { sizes, data: bytes.subarray(4 + count * 4) };
+ } catch (error) {
+ if (attempt >= 5) throw error;
+ await Bun.sleep(500);
+ }
+ }
+}
+
+type Segment = {
+ file?: { path: string; start: number; end: number };
+ bytes?: Uint8Array;
+};
+
+/**
+ * Publishes a chunk as HLS media segments while the engine is still encoding
+ * it: every finished GOP the engine announces is on disk, so once a segment's
+ * worth has accumulated it is wrapped in a moof, muxed with its audio and
+ * uploaded. Players can start on chunk 0 seconds after the request.
+ */
+class SegmentStream {
+ private sizes: number[] = [];
+ private offsets = [0];
+ private start = 0;
+ private index = 0;
+ private extradata = "";
+ private uploads: Promise<void>[] = [];
+ private failed: unknown = null;
+ firstUploadedMs: number | null = null;
+
+ constructor(
+ private task: VideoTask & { hls: NonNullable<VideoTask["hls"]> },
+ private path: string,
+ private started: number,
+ ) {}
+
+ onEvent(event: Record<string, unknown>) {
+ if (typeof event.extradata === "string") this.extradata = event.extradata;
+ const gop = event.gop as { first: number; sizes: number[] } | undefined;
+ if (!gop || gop.first !== this.sizes.length) return;
+ this.append(gop.sizes);
+ if (
+ closesSegment(this.start, this.sizes.length, this.task.hls.segmentFrames)
+ ) {
+ this.cut(this.sizes.length, false);
+ }
+ }
+
+ /** After the engine returns: publish the tail and wait for every upload. */
+ async finish(allSizes: number[], extradata: string) {
+ this.extradata ||= extradata;
+ this.append(allSizes.slice(this.sizes.length));
+ if (this.start < this.sizes.length) this.cut(this.sizes.length, true);
+ await Promise.all(this.uploads);
+ if (this.failed) throw this.failed;
+ return this.index;
+ }
+
+ private append(sizes: number[]) {
+ for (const size of sizes) {
+ this.sizes.push(size);
+ this.offsets.push((this.offsets[this.offsets.length - 1] ?? 0) + size);
+ }
+ }
+
+ private cut(end: number, last: boolean) {
+ const range: [number, number] = [this.start, end];
+ this.start = end;
+ const index = this.index++;
+ this.uploads.push(
+ this.publish(range, index, last).catch((error) => {
+ this.failed ??= error;
+ }),
+ );
+ }
+
+ /** First AAC packet at or after output frame `frame` (the layout() rule). */
+ private packetAt(frame: number) {
+ const audio = this.task.audio;
+ if (!audio) return 0;
+ const sample = frame * (48_000 / this.task.fps);
+ const packet = Math.ceil(sample / 1024) + 1;
+ return Math.min(audio.end, Math.max(audio.first, packet));
+ }
+
+ private async publish(
+ [a, b]: [number, number],
+ index: number,
+ last: boolean,
+ ) {
+ const task = this.task;
+ const first = task.frames[0];
+ const video = new Uint8Array(
+ await Bun.file(this.path)
+ .slice(this.offsets[a] ?? 0, this.offsets[b] ?? 0)
+ .arrayBuffer(),
+ );
+ const packets: [number, number] = task.audio
+ ? [
+ a === 0 ? task.audio.first : this.packetAt(first + a),
+ last ? task.audio.end : this.packetAt(first + b),
+ ]
+ : [0, 0];
+ const audio = await fetchAudioRange(task.jobId, packets[0], packets[1]);
+ const header = segmentHeader({
+ sequence: first + a + 1,
+ firstFrame: first + a,
+ videoSizes: this.sizes.slice(a, b),
+ firstPacket: packets[0],
+ audioSizes: audio.sizes,
+ });
+ const body = new Uint8Array(
+ header.byteLength + video.byteLength + audio.data.byteLength,
+ );
+ body.set(header, 0);
+ body.set(video, header.byteLength);
+ body.set(audio.data, header.byteLength + video.byteLength);
+ const key = `${task.hls.prefix}/c${task.chunk}-${index}.m4s`;
+ await s3.put(key, body, "video/iso.segment");
+ this.firstUploadedMs ??= performance.now() - this.started;
+ const report: SegmentReport = {
+ chunk: task.chunk,
+ index,
+ frames: [first + a, first + b],
+ key,
+ last,
+ extradata: this.extradata,
+ };
+ await post(`/tasks/${encodeURIComponent(task.taskId)}/segment`, report);
+ }
+}
+
+/**
+ * Video samples interleaved with the chunk's audio packets once per second,
+ * the way ffmpeg's muxer lays out a progressive MP4.
+ */
+function layout(
+ task: VideoTask,
+ videoPath: string,
+ videoSizes: number[],
+ audio: { sizes: number[]; data: Uint8Array },
+) {
+ const segments: Segment[] = [];
+ const videoRuns: Run[] = [];
+ const audioRuns: Run[] = [];
+ const samplesPerFrame = 48_000 / task.fps;
+ let offset = 0;
+ let videoFile = 0;
+ let frame = 0;
+ let packet = 0;
+ let audioByte = 0;
+ const flushAudio = (untilSample: number) => {
+ const firstPacket = packet;
+ const startByte = audioByte;
+ while (packet < audio.sizes.length) {
+ const global = (task.audio?.first ?? 0) + packet;
+ if ((global - 1) * 1024 >= untilSample) break;
+ audioByte += audio.sizes[packet] ?? 0;
+ packet++;
+ }
+ if (packet > firstPacket) {
+ audioRuns.push({
+ first: (task.audio?.first ?? 0) + firstPacket,
+ count: packet - firstPacket,
+ offset,
+ });
+ segments.push({ bytes: audio.data.subarray(startByte, audioByte) });
+ offset += audioByte - startByte;
+ }
+ };
+ const total = videoSizes.length;
+ while (frame < total) {
+ const blockEnd = Math.min(total, frame + task.fps);
+ let blockBytes = 0;
+ for (let index = frame; index < blockEnd; index++)
+ blockBytes += videoSizes[index] ?? 0;
+ videoRuns.push({
+ first: task.frames[0] + frame,
+ count: blockEnd - frame,
+ offset,
+ });
+ segments.push({
+ file: { path: videoPath, start: videoFile, end: videoFile + blockBytes },
+ });
+ offset += blockBytes;
+ videoFile += blockBytes;
+ frame = blockEnd;
+ flushAudio((task.frames[0] + frame) * samplesPerFrame);
+ }
+ flushAudio(Number.POSITIVE_INFINITY);
+ return { segments, videoRuns, audioRuns, bytes: offset };
+}
+
+async function uploadLayout(
+ task: VideoTask,
+ segments: Segment[],
+ bytes: number,
+) {
+ const parts: { partNumber: number; etag: string; size: number }[] = [];
+ const { upload } = task;
+ let pending: Uint8Array[] = [];
+ let pendingBytes = 0;
+ let nextPart = upload.firstPart;
+ const inflight = new Set<Promise<void>>();
+ const send = async (body: Uint8Array) => {
+ if (nextPart >= upload.firstPart + upload.partLimit) {
+ throw new Error("chunk needs more parts than reserved");
+ }
+ const partNumber = nextPart++;
+ const promise = s3
+ .uploadPart(upload.key, upload.uploadId, partNumber, body)
+ .then((etag) => {
+ parts.push({ partNumber, etag, size: body.byteLength });
+ });
+ inflight.add(promise);
+ // Handle both outcomes here: a bare .finally() re-rejects unhandled and
+ // kills the whole worker (e.g. a hedge loser hitting NoSuchUpload after
+ // the job completed). The failure still surfaces via race/all below.
+ const forget = () => inflight.delete(promise);
+ promise.then(forget, forget);
+ if (inflight.size >= 4) await Promise.race(inflight);
+ };
+ const take = (count: number) => {
+ const out = new Uint8Array(count);
+ let filled = 0;
+ while (filled < count) {
+ const head = pending[0];
+ if (!head) break;
+ const use = Math.min(head.byteLength, count - filled);
+ out.set(head.subarray(0, use), filled);
+ filled += use;
+ if (use === head.byteLength) pending.shift();
+ else pending[0] = head.subarray(use);
+ }
+ pendingBytes -= count;
+ return out;
+ };
+ const files = new Map<string, ReturnType<typeof Bun.file>>();
+ for (const segment of segments) {
+ let data: Uint8Array;
+ if (segment.bytes) data = segment.bytes;
+ else if (segment.file) {
+ let file = files.get(segment.file.path);
+ if (!file) {
+ file = Bun.file(segment.file.path);
+ files.set(segment.file.path, file);
+ }
+ data = new Uint8Array(
+ await file.slice(segment.file.start, segment.file.end).arrayBuffer(),
+ );
+ } else continue;
+ pending.push(data);
+ pendingBytes += data.byteLength;
+ // Always keep >= 5 MiB back so the chunk's last part is never too small.
+ while (pendingBytes >= upload.partTarget + MIN_PART)
+ await send(take(upload.partTarget));
+ }
+ let padded = 0;
+ if (!upload.isLast && pendingBytes < MIN_PART) {
+ // Unreferenced bytes inside mdat are legal; they keep S3's 5 MiB rule.
+ padded = MIN_PART - pendingBytes;
+ pending.push(new Uint8Array(padded));
+ pendingBytes += padded;
+ }
+ if (pendingBytes > 0) await send(take(pendingBytes));
+ await Promise.all(inflight);
+ pending = [];
+ if (parts.reduce((sum, part) => sum + part.size, 0) !== bytes + padded) {
+ throw new Error("uploaded byte count mismatch");
+ }
+ return { parts: parts.sort((a, b) => a.partNumber - b.partNumber), padded };
+}
+
+async function runVideo(
+ task: VideoTask,
+ engine: Engine,
+ queuedMs: number,
+ nearEnd: () => void = () => {},
+): Promise<VideoResult> {
+ const started = performance.now();
+ const cpuBefore = await processCpuSeconds(engine.pid);
+ const cache = cacheFor(task.jobId);
+ const fetchStats = await cache.materialize(task.files);
+ const audioPromise = fetchAudio(task);
+ const out = join(
+ cache.root,
+ `v${task.chunk}-${randomUUID().slice(0, 6)}.h264`,
+ );
+ const engineStarted = performance.now();
+ const slot = engines.indexOf(engine);
+ const entry = {
+ taskId: task.taskId,
+ kind: "video" as const,
+ frames: 0,
+ total: task.frames[1] - task.frames[0],
+ startedAt: Date.now(),
+ lastProgressAt: Date.now(),
+ };
+ progress.set(slot, entry);
+ const stream = task.hls
+ ? new SegmentStream({ ...task, hls: task.hls }, out, engineStarted)
+ : null;
+ engine.onEvent = stream ? (event) => stream.onEvent(event) : null;
+ // Ask for the next task once this one is ~PREFETCH_LEAD_MS from done, so
+ // its sources download while this one finishes instead of after.
+ engine.onProgress = (frames) => {
+ entry.frames = frames;
+ entry.lastProgressAt = Date.now();
+ const elapsed = performance.now() - engineStarted;
+ const remainingMs =
+ ((entry.total - frames) * elapsed) / Math.max(1, frames);
+ if (frames > 0 && remainingMs <= PREFETCH_LEAD_MS) nearEnd();
+ };
+ const request = engine.request<{
+ width: number;
+ height: number;
+ sizes: number[];
+ keyframes: number[];
+ extradata: string;
+ bytes: number;
+ timings: Record<string, number>;
+ }>("video", {
+ project: cache.root,
+ fps: task.fps,
+ resolution: task.resolution,
+ bpp: task.bpp,
+ frames: task.frames,
+ threads: task.threads,
+ out,
+ });
+ const threadsPromise: Promise<Record<string, number>> =
+ process.env.RF_PROFILE_THREADS === "1"
+ ? sampleThreads(engine.pid, request)
+ : Promise.resolve({});
+ const result = await request.finally(() => {
+ engine.onProgress = null;
+ engine.onEvent = null;
+ progress.delete(slot);
+ });
+ nearEnd();
+ const segmentsDone = stream?.finish(result.sizes, result.extradata);
+ const engineMs = performance.now() - engineStarted;
+ const threads = await threadsPromise;
+ const waitStarted = performance.now();
+ const audio = await audioPromise;
+ const audioWaitMs = performance.now() - waitStarted;
+ const uploadStarted = performance.now();
+ const plan = layout(task, out, result.sizes, audio);
+ const [{ parts, padded }, segments] = await Promise.all([
+ uploadLayout(task, plan.segments, plan.bytes),
+ segmentsDone ?? Promise.resolve(0),
+ ]);
+ const uploadMs = performance.now() - uploadStarted;
+ rmSync(out, { force: true });
+ const timings: TaskTimings = {
+ queuedMs,
+ fetch: fetchStats,
+ engine: {
+ ...result.timings,
+ ...Object.fromEntries(
+ Object.entries(threads).map(([name, value]) => [
+ `thread:${name}`,
+ value,
+ ]),
+ ),
+ ...(stream
+ ? { segments, firstSegmentMs: Math.round(stream.firstUploadedMs ?? -1) }
+ : {}),
+ },
+ engineMs,
+ audioWaitMs,
+ uploadMs,
+ totalMs: performance.now() - started,
+ cpuSeconds: (await processCpuSeconds(engine.pid)) - cpuBefore,
+ };
+ return {
+ taskId: task.taskId,
+ worker: WORKER_ID,
+ sizes: result.sizes,
+ keyframes: result.keyframes,
+ extradata: result.extradata,
+ width: result.width,
+ height: result.height,
+ videoRuns: plan.videoRuns,
+ audioRuns: plan.audioRuns,
+ parts,
+ bytes: plan.bytes,
+ paddedBytes: padded,
+ timings,
+ };
+}
+
+async function runAudio(task: AudioTask, engine: Engine, queuedMs: number) {
+ const started = performance.now();
+ const cpuBefore = await processCpuSeconds(engine.pid);
+ const cache = cacheFor(task.jobId);
+ const fetchStats = await cache.materialize(task.files);
+ const out = join(
+ cache.root,
+ `a${task.section}-${randomUUID().slice(0, 6)}.aac`,
+ );
+ const engineStarted = performance.now();
+ // Reported in heartbeats so a restarted coordinator can re-attach it.
+ const slot = engines.indexOf(engine);
+ progress.set(slot, {
+ taskId: task.taskId,
+ kind: "audio",
+ frames: 0,
+ total: 0,
+ startedAt: Date.now(),
+ lastProgressAt: Date.now(),
+ });
+ // Studio Sound runs ~15x realtime; a section taking longer than a third
+ // of its own length (or a minute) is a hung engine.
+ const seconds = (task.range[1] - task.range[0] + task.preroll) / 48_000;
+ const watchdog = setTimeout(
+ () => {
+ console.error(`${task.taskId}: audio section timed out, killing engine`);
+ engine.kill();
+ },
+ Math.max(60_000, (seconds * 1000) / 3),
+ );
+ const result = await engine
+ .request<{
+ first_packet: number;
+ sizes: number[];
+ extradata: string;
+ timings: Record<string, number>;
+ }>("audio", {
+ project: cache.root,
+ fps: task.fps,
+ section: task.range,
+ preroll: task.preroll,
+ out,
+ })
+ .finally(() => {
+ clearTimeout(watchdog);
+ progress.delete(slot);
+ });
+ const engineMs = performance.now() - engineStarted;
+ const data = new Uint8Array(await Bun.file(out).arrayBuffer());
+ rmSync(out, { force: true });
+ const meta: AudioResultMeta = {
+ taskId: task.taskId,
+ worker: WORKER_ID,
+ firstPacket: result.first_packet,
+ sizes: result.sizes,
+ extradata: result.extradata,
+ timings: {
+ queuedMs,
+ fetch: fetchStats,
+ engine: result.timings,
+ engineMs,
+ audioWaitMs: 0,
+ uploadMs: 0,
+ totalMs: performance.now() - started,
+ cpuSeconds: (await processCpuSeconds(engine.pid)) - cpuBefore,
+ },
+ };
+ const json = new TextEncoder().encode(JSON.stringify(meta));
+ const body = new Uint8Array(4 + json.byteLength + data.byteLength);
+ new DataView(body.buffer).setUint32(0, json.byteLength);
+ body.set(json, 4);
+ body.set(data, 4 + json.byteLength);
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await fetch(
+ `${COORDINATOR}/tasks/${encodeURIComponent(task.taskId)}/audio`,
+ {
+ method: "POST",
+ headers: TOKEN ? { authorization: `Bearer ${TOKEN}` } : {},
+ body,
+ },
+ );
+ if (!response.ok) throw new Error(`audio result -> ${response.status}`);
+ break;
+ } catch (error) {
+ if (attempt >= 5) throw error;
+ await Bun.sleep(500 * 2 ** attempt);
+ }
+ }
+}
+
+async function poll(kinds: string[] | undefined, prefetch = false) {
+ const response = await post("/work", {
+ worker: WORKER_ID,
+ slots: SLOTS,
+ cpus: CPUS,
+ service: SERVICE,
+ kinds,
+ audioSlots: AUDIO_SLOTS,
+ prefetch,
+ });
+ const body = (await response.json()) as {
+ task: Task | null;
+ finished: string[];
+ };
+ dropJobs(body.finished ?? []);
+ return body.task;
+}
+
+let draining = false;
+// Slots holding a prefetched (already reserved) next task.
+const reserved = new Set<number>();
+
+function exitWhenIdle() {
+ if (draining && busy.size === 0 && reserved.size === 0) {
+ console.log("drained; exiting");
+ process.exit(0);
+ }
+}
+
+for (const signal of ["SIGTERM", "SIGINT"] as const) {
+ process.on(signal, () => {
+ if (draining) return;
+ draining = true;
+ console.log(
+ `${signal}: finishing ${busy.size} running task(s), taking no new work`,
+ );
+ exitWhenIdle();
+ });
+}
+
+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;
+ for (;;) {
+ if (draining && !next) {
+ exitWhenIdle();
+ await Bun.sleep(1000);
+ continue;
+ }
+ let task: Task | null = null;
+ try {
+ task = next ? await next : await poll(kinds);
+ } catch (error) {
+ console.error(`poll failed: ${error}`);
+ await Bun.sleep(1000);
+ continue;
+ } finally {
+ next = null;
+ reserved.delete(slot);
+ }
+ if (!task) continue;
+ // Reserve the following task near the end of this one and start its
+ // source download (queued work only; never a hedge).
+ const prefetchNext = () => {
+ if (next || draining || PREFETCH_LEAD_MS <= 0) return;
+ reserved.add(slot);
+ next = poll(kinds, true)
+ .then((upcoming) => {
+ if (upcoming)
+ cacheFor(upcoming.jobId)
+ .materialize(upcoming.files)
+ .catch(() => {});
+ return upcoming;
+ })
+ .catch(() => null);
+ };
+ const received = performance.now();
+ busy.set(slot, task);
+ try {
+ if (!engine.alive) {
+ engine = warm(
+ new Engine(ENGINE_BIN, engine.env, `slot${slot}`, engine.nice),
+ slot,
+ );
+ engines[slot] = engine;
+ }
+ if (task.kind === "video") {
+ const result = await runVideo(task, engine, 0, prefetchNext);
+ await post(`/tasks/${encodeURIComponent(task.taskId)}/done`, result);
+ const vram = (
+ result.timings.engine as unknown as { gpu_mem?: number[][] }
+ ).gpu_mem;
+ const freeMb = vram?.[vram.length - 1]?.[2];
+ if (freeMb !== undefined && freeMb > 0 && freeMb < MIN_FREE_VRAM_MB) {
+ console.warn(
+ `slot${slot}: ${freeMb} MiB VRAM free, recycling engine`,
+ );
+ engine.kill();
+ engine = warm(
+ new Engine(ENGINE_BIN, engine.env, `slot${slot}`),
+ slot,
+ );
+ engines[slot] = engine;
+ }
+ } else {
+ await runAudio(task, engine, 0);
+ }
+ console.log(
+ `${task.taskId} done in ${Math.round(performance.now() - received)}ms`,
+ );
+ } catch (error) {
+ console.error(`${task.taskId} failed: ${error}`);
+ if (String(error).includes("gpu path degraded")) {
+ // A fresh process usually recovers the CUDA/Vulkan state; if
+ // it keeps happening, restart the whole app (boot.ts relaunches).
+ engine.kill();
+ const now = Date.now();
+ degradedFailures = [
+ ...degradedFailures.filter((at) => now - at < 300_000),
+ now,
+ ];
+ if (degradedFailures.length >= 3) {
+ console.error(
+ "GPU path degraded 3 times in 5 min; restarting worker",
+ );
+ setTimeout(() => process.exit(75), 500);
+ }
+ }
+ await post(`/tasks/${encodeURIComponent(task.taskId)}/fail`, {
+ worker: WORKER_ID,
+ error: String(error instanceof Error ? error.message : error),
+ }).catch(() => {});
+ } finally {
+ busy.delete(slot);
+ exitWhenIdle();
+ }
+ }
+}
+
+/** Container CPU seconds and memory (cgroup v2), for per-job cost accounting. */
+async function usage() {
+ try {
+ const stat = await Bun.file("/sys/fs/cgroup/cpu.stat").text();
+ const usec = Number(stat.match(/usage_usec (\d+)/)?.[1] ?? 0);
+ const memory = Number(
+ (await Bun.file("/sys/fs/cgroup/memory.current").text()).trim(),
+ );
+ const throttledUsec = Number(stat.match(/throttled_usec (\d+)/)?.[1] ?? 0);
+ const throttledPeriods = Number(stat.match(/nr_throttled (\d+)/)?.[1] ?? 0);
+ return {
+ cpuSeconds: usec / 1e6,
+ memoryBytes: memory,
+ throttledSeconds: throttledUsec / 1e6,
+ throttledPeriods,
+ cpuMax: (
+ await Bun.file("/sys/fs/cgroup/cpu.max")
+ .text()
+ .catch(() => "")
+ ).trim(),
+ load: (
+ await Bun.file("/proc/loadavg")
+ .text()
+ .catch(() => "")
+ ).trim(),
+ model: (
+ await Bun.file("/proc/cpuinfo")
+ .text()
+ .catch(() => "")
+ ).match(/model name\s*:\s*(.*)/)?.[1],
+ hostCpus: (
+ (
+ await Bun.file("/proc/cpuinfo")
+ .text()
+ .catch(() => "")
+ ).match(/^processor/gm) ?? []
+ ).length,
+ // Host-wide jiffies: user nice system idle iowait irq softirq steal.
+ hostStat: (
+ await Bun.file("/proc/stat")
+ .text()
+ .catch(() => "")
+ ).split("\n")[0],
+ at: Date.now(),
+ };
+ } catch {
+ return null;
+ }
+}
+
+function cancel(taskIds: string[]) {
+ for (const [slot, task] of busy) {
+ if (!taskIds.includes(task.taskId)) continue;
+ console.log(`cancelling ${task.taskId}`);
+ engines[slot]?.kill();
+ }
+}
+
+setInterval(() => {
+ const now = Date.now();
+ for (const [slot, entry] of progress) {
+ if (entry.kind !== "video" || now - entry.lastProgressAt < STALL_MS)
+ continue;
+ console.error(
+ `${entry.taskId}: no progress for ${now - entry.lastProgressAt} ms, killing slot${slot}`,
+ );
+ entry.lastProgressAt = now;
+ engines[slot]?.kill();
+ }
+}, 5_000);
+
+setInterval(async () => {
+ const running = [...progress.values()].map((entry) => ({
+ taskId: entry.taskId,
+ frames: entry.frames,
+ total: entry.total,
+ elapsedMs: Date.now() - entry.startedAt,
+ }));
+ post("/heartbeat", {
+ worker: WORKER_ID,
+ slots: SLOTS,
+ cpus: CPUS,
+ usage: await usage(),
+ running,
+ })
+ .then(async (response) => {
+ const body = (await response.json()) as {
+ finished: string[];
+ cancel?: string[];
+ };
+ cancel(body.cancel ?? []);
+ dropJobs(body.finished ?? []);
+ })
+ .catch(() => {});
+}, 3_000);
+
+console.log(
+ `render-farm worker ${WORKER_ID}: ${SLOTS} slots x ${THREADS} threads, coordinator ${COORDINATOR}`,
+);
+for (let slot = 0; slot < SLOTS + AUDIO_SLOTS; slot++) slotLoop(slot);
diff --git a/apps/render-farm/tsconfig.json b/apps/render-farm/tsconfig.json
new file mode 100644
index 000000000..b204e0594
--- /dev/null
+++ b/apps/render-farm/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "skipLibCheck": true,
+ "types": ["bun-types"],
+ "noEmit": true
+ },
+ "include": ["src"]
+}
diff --git a/bun.lock b/bun.lock
index ad553133f..f3595ec6f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -222,6 +222,12 @@
"vitest": "^3.2.0",
},
},
+ "apps/render-farm": {
+ "name": "@cap/render-farm",
+ "devDependencies": {
+ "@types/bun": "latest",
+ },
+ },
"apps/web": {
"name": "@cap/web",
"version": "0.3.1",
@@ -984,6 +990,8 @@
"@cap/recorder-core": ["@cap/recorder-core@workspace:packages/recorder-core"],
+ "@cap/render-farm": ["@cap/render-farm@workspace:apps/render-farm"],
+
"@cap/sdk-embed": ["@cap/sdk-embed@workspace:packages/sdk-embed"],
"@cap/sdk-recorder": ["@cap/sdk-recorder@workspace:packages/sdk-recorder"],
@@ -5936,6 +5944,8 @@
"@cap/env/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "6.21.0" } }, "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g=="],
+ "@cap/render-farm/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],
+
"@cap/ui/@tauri-apps/cli": ["@tauri-apps/[email protected]", "", { "dependencies": { "semver": "7.8.5" }, "optionalDependencies": { "@tauri-apps/cli-darwin-arm64": "1.6.3", "@tauri-apps/cli-darwin-x64": "1.6.3", "@tauri-apps/cli-linux-arm-gnueabihf": "1.6.3", "@tauri-apps/cli-linux-arm64-gnu": "1.6.3", "@tauri-apps/cli-linux-arm64-musl": "1.6.3", "@tauri-apps/cli-linux-x64-gnu": "1.6.3", "@tauri-apps/cli-linux-x64-musl": "1.6.3", "@tauri-apps/cli-win32-arm64-msvc": "1.6.3", "@tauri-apps/cli-win32-ia32-msvc": "1.6.3", "@tauri-apps/cli-win32-x64-msvc": "1.6.3" }, "bin": { "tauri": "tauri.js" } }, "sha512-q46umd6QLRKDd4Gg6WyZBGa2fWvk0pbeUA5vFomm4uOs1/17LIciHv2iQ4UD+2Yv5H7AO8YiE1t50V0POiEGEw=="],
"@cap/ui/lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0" } }, "sha512-V7o0/VECSGbLHn3/1O67FUgBwWB+hmzshrgDVRJQhMh8uj5D3HBuIvhuAmQTtlupILSplwIZg5FTc4tTKMA2SA=="],
@@ -7254,6 +7264,8 @@
"@cap/discord-bot/vitest/vite-node": ["[email protected]", "", { "dependencies": { "cac": "6.7.14", "debug": "4.4.3", "es-module-lexer": "1.7.0", "pathe": "1.1.2", "vite": "5.4.21" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA=="],
+ "@cap/render-farm/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
+
"@cap/ui/@tauri-apps/cli/@tauri-apps/cli-darwin-arm64": ["@tauri-apps/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-fQN6IYSL8bG4NvkdKE4sAGF4dF/QqqQq4hOAU+t8ksOzHJr0hUlJYfncFeJYutr/MMkdF7hYKadSb0j5EE9r0A=="],
"@cap/ui/@tauri-apps/cli/@tauri-apps/cli-darwin-x64": ["@tauri-apps/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1yTXZzLajKAYINJOJhZfmMhCzweHSgKQ3bEgJSn6t+1vFkOgY8Yx4oFgWcybrrWI5J1ZLZAl47+LPOY81dLcyA=="],
@@ -8598,6 +8610,8 @@
"@cap/discord-bot/vitest/vite/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "3.3.15", "picocolors": "1.1.1", "source-map-js": "1.2.1" } }, "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg=="],
+ "@cap/render-farm/@types/bun/bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "6.21.0" } }, "sha512-QWlFW2wf3nTjC13/DqRnBpR4ZO36VJH/JVBkA/vcnmbTBNQIlnObqyqZE1tUR7+Ni23Lda8R1BxMfbXRpCUx5g=="],
+
"@cap/ui/vite/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="],
"@cap/web/eslint/@eslint/eslintrc/globals": ["[email protected]", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
diff --git a/crates/audio/src/audio_data.rs b/crates/audio/src/audio_data.rs
index 1d025b321..ccd0cb88d 100644
--- a/crates/audio/src/audio_data.rs
+++ b/crates/audio/src/audio_data.rs
@@ -253,6 +253,18 @@ impl AudioData {
&& source_end_sample <= self.covered_source_end_sample
}
+ /// Interleaved 48 kHz samples starting at source sample 0. Used to
+ /// assemble a track from decoded windows (zero elsewhere) when only parts
+ /// of a long recording are needed.
+ pub fn from_samples(samples: Vec<f32>, channels: u16) -> Self {
+ Self {
+ samples,
+ channels,
+ source_start_sample: 0,
+ covered_source_end_sample: usize::MAX,
+ }
+ }
+
#[cfg(any(test, feature = "test-support"))]
pub fn from_raw_f32(samples: Vec<f32>, channels: u16) -> Self {
Self {
diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rs
index 863246473..bb3b8c1cc 100644
--- a/crates/export/src/mp4.rs
+++ b/crates/export/src/mp4.rs
@@ -1685,6 +1685,8 @@ mod tests {
format: GpuOutputFormat::Nv12,
#[cfg(target_os = "macos")]
surface: None,
+ #[cfg(target_os = "linux")]
+ gpu: None,
};
let result = nv12_from_rendered_frame(frame);
diff --git a/crates/ffmpeg-hw-device/src/lib.rs b/crates/ffmpeg-hw-device/src/lib.rs
index 899cf5474..023182e6a 100644
--- a/crates/ffmpeg-hw-device/src/lib.rs
+++ b/crates/ffmpeg-hw-device/src/lib.rs
@@ -8,8 +8,8 @@ use ffmpeg::{
frame::{self, Video},
sys::{
AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX, AVBufferRef, AVCodecContext, AVCodecHWConfig,
- AVHWDeviceType, AVPixelFormat, av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_create,
- av_hwframe_transfer_data, avcodec_get_hw_config,
+ AVHWDeviceType, AVPixelFormat, av_buffer_ref, av_buffer_unref, av_dict_free, av_dict_set,
+ av_hwdevice_ctx_create, av_hwframe_transfer_data, avcodec_get_hw_config,
},
};
@@ -45,8 +45,18 @@ pub struct HwDevice {
ctx: *mut AVBufferRef,
}
+fn linux_gpu_frames() -> bool {
+ static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ENABLED.get_or_init(|| std::env::var("CAP_LINUX_GPU_FRAMES").as_deref() == Ok("1"))
+}
+
impl HwDevice {
pub fn get_hwframe(&self, src: &Video) -> Option<Video> {
+ // Linux GPU render hosts keep CUDA frames on the device; the renderer
+ // copies them device-to-device instead of via system memory.
+ if self.device_type == AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA && linux_gpu_frames() {
+ return None;
+ }
unsafe {
if src.format() == HW_PIX_FMT.get().into() {
let mut sw_frame = frame::Video::empty();
@@ -88,9 +98,26 @@ impl CodecContextExt for codec::decoder::decoder::Decoder {
let mut hw_device_ctx = null_mut();
- if av_hwdevice_ctx_create(&mut hw_device_ctx, device_type, null(), null_mut(), 0) < 0 {
+ let gpu_frames =
+ device_type == AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA && linux_gpu_frames();
+ let mut options = null_mut();
+ if gpu_frames {
+ // Share the device's primary CUDA context with the renderer's
+ // Vulkan interop and NVENC, so device pointers work across all.
+ av_dict_set(&mut options, c"primary_ctx".as_ptr(), c"1".as_ptr(), 0);
+ }
+ let created =
+ av_hwdevice_ctx_create(&mut hw_device_ctx, device_type, null(), options, 0);
+ av_dict_free(&mut options);
+ if created < 0 {
return Err("failed to create hw device context");
}
+ if gpu_frames {
+ // Decoded surfaces now live in the frame cache instead of being
+ // downloaded at once, so NVDEC's pool needs headroom. NVDEC
+ // caps a decoder at 32 surfaces including the DPB (~16).
+ (*self.as_mut_ptr()).extra_hw_frames = 12;
+ }
HW_PIX_FMT.set((*hw_config).pix_fmt);
diff --git a/crates/render-farm/Cargo.toml b/crates/render-farm/Cargo.toml
new file mode 100644
index 000000000..92a5a2b27
--- /dev/null
+++ b/crates/render-farm/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "cap-render-farm"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[[bin]]
+name = "cap-render-farm"
+path = "src/main.rs"
+
+[dependencies]
+cap-audio = { path = "../audio" }
+cap-project = { path = "../project" }
+cap-rendering = { path = "../rendering" }
+cap-editor = { path = "../editor" }
+cap-export = { path = "../export" }
+
+anyhow.workspace = true
+base64 = "0.22.1"
+ffmpeg = { workspace = true }
+serde = { workspace = true }
+serde_json = "1.0.140"
+tokio.workspace = true
+wgpu.workspace = true
+tracing.workspace = true
+tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[lints]
+workspace = true
diff --git a/crates/render-farm/src/audio.rs b/crates/render-farm/src/audio.rs
new file mode 100644
index 000000000..b75fb942d
--- /dev/null
+++ b/crates/render-farm/src/audio.rs
@@ -0,0 +1,389 @@
+use crate::{project::LoadedProject, video::base64_encode};
+use anyhow::{Context, Result, anyhow, bail};
+use cap_editor::AudioRenderer;
+use cap_project::StudioRecordingMeta;
+use ffmpeg::{ChannelLayout, format::Sample, format::sample::Type, frame};
+use serde::{Deserialize, Serialize};
+use std::{
+ fs::File,
+ io::{BufWriter, Write},
+ path::PathBuf,
+ time::Instant,
+};
+
+pub const SAMPLE_RATE: i64 = 48_000;
+pub const PACKET_SAMPLES: i64 = 1024;
+/// The AAC encoder's priming delay. The final MP4's audio edit list skips it,
+/// so global packet `j` presents samples starting at `(j - 1) * 1024`.
+pub const PRIMING: i64 = 1024;
+const AAC_BITRATE: usize = 320_000;
+
+#[derive(Deserialize)]
+pub struct AudioRequest {
+ pub project: PathBuf,
+ pub fps: u32,
+ /// Output-timeline sample range this section owns: every AAC packet whose
+ /// first presented sample falls in `[start, end)`. `start` is a multiple of
+ /// 1024; section 0 also owns the priming packet.
+ pub section: [i64; 2],
+ /// Samples rendered and encoded before `start` and thrown away, so the
+ /// encoder, resampler and Studio Sound state match an unbroken export at
+ /// the seam.
+ pub preroll: i64,
+ pub out: PathBuf,
+}
+
+#[derive(Serialize)]
+pub struct AudioResult {
+ /// Global index of the first packet in `out`.
+ pub first_packet: u64,
+ pub sizes: Vec<u32>,
+ /// AudioSpecificConfig.
+ pub extradata: String,
+ pub total_samples: i64,
+ pub timings: AudioTimings,
+}
+
+#[derive(Serialize, Default)]
+pub struct AudioTimings {
+ pub load_ms: u64,
+ pub decode_ms: u64,
+ pub render_ms: u64,
+ pub total_ms: u64,
+}
+
+pub async fn render(request: AudioRequest) -> Result<AudioResult> {
+ let started = Instant::now();
+ let mut timings = AudioTimings::default();
+ let project = LoadedProject::load(&request.project)?;
+ let total_frames = project.total_frames(request.fps) as i64;
+ let total_samples = total_frames * SAMPLE_RATE / request.fps as i64;
+ let [start, end] = request.section;
+ if start % PACKET_SAMPLES != 0 || request.preroll % PACKET_SAMPLES != 0 || start >= end {
+ bail!("misaligned audio section {:?}", request.section);
+ }
+ let end = end.min(total_samples);
+ let is_last = end >= total_samples;
+ timings.load_ms = started.elapsed().as_millis() as u64;
+
+ let phase = Instant::now();
+ let input_start_secs = ((start - request.preroll).max(0)) as f64 / SAMPLE_RATE as f64;
+ let render_end_secs = (end + 2 * PACKET_SAMPLES) as f64 / SAMPLE_RATE as f64;
+ let windows = source_windows(&project, input_start_secs, render_end_secs);
+ let segments = load_audio_segments(&project, &windows).await?;
+ let music = cap_editor::load_music_tracks_uncached(&project.config, &project.path);
+ timings.decode_ms = phase.elapsed().as_millis() as u64;
+
+ let phase = Instant::now();
+ let input_start = (start - request.preroll).max(0);
+ let keep_from = if start == 0 { -PRIMING } else { start };
+ let render_until = if is_last {
+ end
+ } else {
+ (end + 2 * PACKET_SAMPLES).min(total_samples)
+ };
+
+ let mut renderer = AudioRenderer::new(segments).with_music(music);
+ renderer.set_playhead(input_start as f64 / SAMPLE_RATE as f64, &project.config);
+
+ let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::AAC).context("aac encoder")?;
+ let context = ffmpeg::codec::context::Context::new_with_codec(codec);
+ let mut encoder = context.encoder().audio()?;
+ encoder.set_rate(SAMPLE_RATE as i32);
+ encoder.set_channel_layout(ChannelLayout::STEREO);
+ encoder.set_format(Sample::F32(Type::Planar));
+ encoder.set_bit_rate(AAC_BITRATE);
+ encoder.set_time_base(ffmpeg::Rational::new(1, SAMPLE_RATE as i32));
+ encoder.set_flags(ffmpeg::codec::flag::Flags::GLOBAL_HEADER);
+ let mut encoder = encoder.open_as(codec)?;
+ let extradata = unsafe {
+ let pointer = encoder.as_ptr();
+ std::slice::from_raw_parts((*pointer).extradata, (*pointer).extradata_size as usize)
+ .to_vec()
+ };
+
+ let mut output = BufWriter::with_capacity(4 << 20, File::create(&request.out)?);
+ let mut sizes = Vec::new();
+ let mut first_packet: Option<i64> = None;
+ let mut packet = ffmpeg::Packet::empty();
+ let mut drain = |encoder: &mut ffmpeg::encoder::Audio,
+ sizes: &mut Vec<u32>,
+ first_packet: &mut Option<i64>|
+ -> Result<bool> {
+ while encoder.receive_packet(&mut packet).is_ok() {
+ let pts = packet
+ .pts()
+ .ok_or_else(|| anyhow!("aac packet without pts"))?;
+ let global_start = input_start + pts;
+ if global_start < keep_from {
+ continue;
+ }
+ if global_start >= end {
+ return Ok(true);
+ }
+ let index = (global_start + PRIMING) / PACKET_SAMPLES;
+ match first_packet {
+ None => *first_packet = Some(index),
+ Some(first) if index != *first + sizes.len() as i64 => {
+ bail!("audio packet {index} out of sequence");
+ }
+ _ => {}
+ }
+ let data = packet.data().ok_or_else(|| anyhow!("empty aac packet"))?;
+ output.write_all(data)?;
+ sizes.push(data.len() as u32);
+ }
+ Ok(false)
+ };
+
+ let mut position = input_start;
+ let mut planar = frame::Audio::new(
+ Sample::F32(Type::Planar),
+ PACKET_SAMPLES as usize,
+ ChannelLayout::STEREO,
+ );
+ planar.set_rate(SAMPLE_RATE as u32);
+ let mut done = false;
+ while position < render_until && !done {
+ let count = (render_until - position).min(PACKET_SAMPLES) as usize;
+ let interleaved = renderer
+ .render_frame_raw(count, &project.config)
+ .map(|(_, data)| data)
+ .unwrap_or_default();
+ // The encoder may still hold a reference to the previous frame's buffer.
+ unsafe { ffmpeg::ffi::av_frame_make_writable(planar.as_mut_ptr()) };
+ {
+ let (left, right) = split_planes(&mut planar);
+ for index in 0..PACKET_SAMPLES as usize {
+ let (l, r) = if index < count {
+ (
+ interleaved.get(index * 2).copied().unwrap_or(0.0),
+ interleaved.get(index * 2 + 1).copied().unwrap_or(0.0),
+ )
+ } else {
+ (0.0, 0.0)
+ };
+ left[index] = l;
+ right[index] = r;
+ }
+ }
+ if count < PACKET_SAMPLES as usize {
+ // A partial final frame: the encoder must see its true length.
+ let mut tail =
+ frame::Audio::new(Sample::F32(Type::Planar), count, ChannelLayout::STEREO);
+ tail.set_rate(SAMPLE_RATE as u32);
+ {
+ let (left, right) = split_planes(&mut tail);
+ let (source_left, source_right) = split_planes(&mut planar);
+ left[..count].copy_from_slice(&source_left[..count]);
+ right[..count].copy_from_slice(&source_right[..count]);
+ }
+ tail.set_pts(Some(position - input_start));
+ encoder.send_frame(&tail)?;
+ } else {
+ planar.set_pts(Some(position - input_start));
+ encoder.send_frame(&planar)?;
+ }
+ position += count as i64;
+ done = drain(&mut encoder, &mut sizes, &mut first_packet)?;
+ }
+ if is_last && !done {
+ encoder.send_eof()?;
+ drain(&mut encoder, &mut sizes, &mut first_packet)?;
+ }
+ output.flush()?;
+ timings.render_ms = phase.elapsed().as_millis() as u64;
+
+ let expected_first = if start == 0 {
+ 0
+ } else {
+ (start + PRIMING) / PACKET_SAMPLES
+ };
+ let first = first_packet.ok_or_else(|| anyhow!("audio section produced no packets"))?;
+ if first != expected_first {
+ bail!("audio section starts at packet {first}, expected {expected_first}");
+ }
+ let expected_end = if is_last {
+ (end + PRIMING + PACKET_SAMPLES - 1) / PACKET_SAMPLES
+ } else {
+ (end + PRIMING) / PACKET_SAMPLES
+ };
+ if first + sizes.len() as i64 != expected_end {
+ bail!(
+ "audio section {:?} produced packets {first}..{}, expected ..{expected_end}",
+ request.section,
+ first + sizes.len() as i64
+ );
+ }
+ timings.total_ms = started.elapsed().as_millis() as u64;
+ Ok(AudioResult {
+ first_packet: first as u64,
+ sizes,
+ extradata: base64_encode(&extradata),
+ total_samples,
+ timings,
+ })
+}
+
+fn split_planes(frame: &mut frame::Audio) -> (&mut [f32], &mut [f32]) {
+ let samples = frame.samples();
+ unsafe {
+ let pointer = frame.as_mut_ptr();
+ let left = std::slice::from_raw_parts_mut((*pointer).data[0] as *mut f32, samples);
+ let right = std::slice::from_raw_parts_mut((*pointer).data[1] as *mut f32, samples);
+ (left, right)
+ }
+}
+
+/// Source seconds each recording clip's audio is read over for an output
+/// range, widened for mic offsets and the enhancer/speed pre-roll.
+fn source_windows(project: &LoadedProject, from: f64, to: f64) -> Vec<Option<(f64, f64)>> {
+ let clips = project.recordings.segments.len();
+ let mut windows: Vec<Option<(f64, f64)>> = vec![None; clips];
+ let mut time = from;
+ while time <= to {
+ if let Some((source, segment)) = project.config.get_segment_time(time) {
+ let index = segment.recording_clip as usize;
+ if let Some(window) = windows.get_mut(index) {
+ *window = Some(match *window {
+ Some((low, high)) => (low.min(source), high.max(source)),
+ None => (source, source),
+ });
+ }
+ }
+ time += 0.02;
+ }
+ let margin = 5.0
+ + project
+ .config
+ .clips
+ .iter()
+ .map(|clip| clip.offsets.mic.abs().max(clip.offsets.system_audio.abs()) as f64)
+ .fold(0.0, f64::max);
+ windows
+ .into_iter()
+ .map(|window| window.map(|(low, high)| ((low - margin).max(0.0), high + margin)))
+ .collect()
+}
+
+async fn load_audio_segments(
+ project: &LoadedProject,
+ windows: &[Option<(f64, f64)>],
+) -> Result<Vec<cap_editor::AudioSegment>> {
+ let legacy_log = std::fs::read_to_string(
+ project
+ .recording_meta
+ .project_path
+ .join("recording-logs.log"),
+ )
+ .ok();
+ let repairs =
+ cap_editor::segment_audio_timing_repairs(&project.studio_meta, legacy_log.as_deref());
+ let tracks: Vec<(Option<PathBuf>, Option<PathBuf>)> = match &project.studio_meta {
+ StudioRecordingMeta::SingleSegment { segment } => vec![(
+ segment
+ .audio
+ .as_ref()
+ .map(|audio| project.recording_meta.path(&audio.path)),
+ None,
+ )],
+ StudioRecordingMeta::MultipleSegments { inner } => inner
+ .segments
+ .iter()
+ .map(|segment| {
+ (
+ segment
+ .mic
+ .as_ref()
+ .map(|audio| project.recording_meta.path(&audio.path)),
+ segment
+ .system_audio
+ .as_ref()
+ .map(|audio| project.recording_meta.path(&audio.path)),
+ )
+ })
+ .collect(),
+ };
+ let mut segments = Vec::with_capacity(tracks.len());
+ for (index, (mic, system)) in tracks.into_iter().enumerate() {
+ let window = windows.get(index).copied().flatten();
+ let recorded = project.recordings.segments.get(index);
+ let mic_duration = recorded
+ .and_then(|segment| segment.mic.as_ref())
+ .map(|audio| audio.duration);
+ let system_duration = recorded
+ .and_then(|segment| segment.system_audio.as_ref())
+ .map(|audio| audio.duration);
+ let mic = load_track(mic, "mic", window, mic_duration).await?;
+ let system = load_track(system, "system audio", window, system_duration).await?;
+ segments.push(cap_editor::audio_segment_from_decoded(
+ mic,
+ system,
+ repairs.get(index).copied().unwrap_or_default(),
+ ));
+ }
+ Ok(segments)
+}
+
+/// Decodes only the first `VOICE_PROFILE_SAMPLES` (what Studio Sound's voice
+/// profile reads) plus the section's source window, placed at their true
+/// offsets in a zero-backed buffer. Within the window the renderer sees exactly
+/// the samples a full decode would give it, but a 2 h mic costs seconds of
+/// decode instead of tens, and untouched zero pages cost no memory.
+async fn load_track(
+ path: Option<PathBuf>,
+ label: &str,
+ window: Option<(f64, f64)>,
+ duration: Option<f64>,
+) -> Result<Option<std::sync::Arc<cap_audio::DecodedAudio>>> {
+ let Some(path) = path else {
+ return Ok(None);
+ };
+ let Some((from, to)) = window else {
+ return Ok(None);
+ };
+ let label = label.to_string();
+ tokio::task::spawn_blocking(move || {
+ let rate = SAMPLE_RATE as f64;
+ let profile =
+ cap_audio::AudioData::from_file_range(&path, 0, cap_audio::VOICE_PROFILE_SAMPLES)
+ .map_err(|error| anyhow!("{label} profile: {error}"))?;
+ let start = (from * rate) as usize;
+ let duration_samples = duration.map(|seconds| (seconds * rate).round() as usize);
+ // Near the end of the recording, decode through EOF so the track keeps
+ // its exact decoded length; elsewhere the container length is enough.
+ let near_end = duration_samples.is_none_or(|total| (to * rate) as usize + 48_000 >= total);
+ let end = if near_end {
+ usize::MAX / 4
+ } else {
+ (to * rate) as usize
+ };
+ let section = cap_audio::AudioData::from_file_range(&path, start, end)
+ .map_err(|error| anyhow!("{label} window: {error}"))?;
+ let channels = section.channels().max(profile.channels()) as usize;
+ let section_start = section.source_start_sample();
+ let decoded_end = section_start + section.sample_count();
+ let total = if near_end {
+ decoded_end
+ } else {
+ decoded_end.max(duration_samples.unwrap_or(0))
+ }
+ .max(profile.sample_count());
+ let mut samples = vec![0.0f32; total * channels];
+ let copy = |samples: &mut [f32], data: &cap_audio::AudioData| {
+ let offset = data.source_start_sample() * channels;
+ let source = data.samples();
+ if data.channels() as usize == channels {
+ samples[offset..offset + source.len()].copy_from_slice(source);
+ }
+ };
+ copy(&mut samples, &profile);
+ copy(&mut samples, &section);
+ let data =
+ std::sync::Arc::new(cap_audio::AudioData::from_samples(samples, channels as u16));
+ Ok(Some(std::sync::Arc::new(cap_audio::DecodedAudio::from(
+ data,
+ ))))
+ })
+ .await?
+}
diff --git a/crates/render-farm/src/main.rs b/crates/render-farm/src/main.rs
new file mode 100644
index 000000000..aeb9effed
--- /dev/null
+++ b/crates/render-farm/src/main.rs
@@ -0,0 +1,179 @@
+//! Chunk engine for distributed Studio exports.
+//!
+//! One long-lived process per render slot. It reads one JSON request per line
+//! on stdin and answers with one JSON line on stdout; logs go to stderr. The
+//! orchestration (planning, source byte ranges, uploads, MP4 assembly) lives
+//! in `apps/render-farm`; this binary only does what needs Cap's renderer:
+//!
+//! - `probe`: frame count, output size and the source-time span each chunk
+//! reads, for the coordinator's plan.
+//! - `video`: render + encode one output frame range to raw H.264 samples.
+//! - `audio`: render + encode one output sample range to raw AAC packets on
+//! the global packet grid, with pre-roll so sections join seamlessly.
+
+mod audio;
+mod project;
+mod video;
+
+use anyhow::Result;
+use serde::Deserialize;
+use serde_json::{Value, json};
+use std::{
+ io::{BufRead, Write},
+ path::PathBuf,
+ sync::Mutex,
+ time::Instant,
+};
+
+/// Id of the request being served, so long ops can stream progress lines.
+static CURRENT_REQUEST: Mutex<Option<Value>> = Mutex::new(None);
+
+/// `{"id": .., "progress": frames}` on stdout; the orchestrator uses it to
+/// spot chunks that are running slow and hedge them on another machine.
+pub fn report_progress(frames: u32) {
+ let Ok(current) = CURRENT_REQUEST.lock() else {
+ return;
+ };
+ let Some(id) = current.as_ref() else {
+ return;
+ };
+ let mut stdout = std::io::stdout().lock();
+ let _ = writeln!(stdout, "{}", json!({ "id": id, "progress": frames }));
+ let _ = stdout.flush();
+}
+
+/// `{"id": .., <key>: <value>}` on stdout: streaming events for the request
+/// in flight (e.g. finished GOPs the worker can publish as HLS segments).
+pub fn report_event(key: &str, value: Value) {
+ let Ok(current) = CURRENT_REQUEST.lock() else {
+ return;
+ };
+ let Some(id) = current.as_ref() else {
+ return;
+ };
+ let mut stdout = std::io::stdout().lock();
+ let _ = writeln!(stdout, "{}", json!({ "id": id, key: value }));
+ let _ = stdout.flush();
+}
+
+#[derive(Deserialize)]
+struct Request {
+ #[serde(default)]
+ id: Value,
+ #[serde(flatten)]
+ op: Op,
+}
+
+#[derive(Deserialize)]
+#[serde(tag = "op", rename_all = "snake_case")]
+enum Op {
+ Probe(ProbeRequest),
+ Video(video::VideoRequest),
+ Audio(audio::AudioRequest),
+ Warm,
+ Ping,
+}
+
+#[derive(Deserialize)]
+struct ProbeRequest {
+ project: PathBuf,
+ fps: u32,
+ resolution: [u32; 2],
+ /// Report source spans for every `span_step` output frames, so the
+ /// coordinator can size chunks without another round trip.
+ #[serde(default)]
+ span_step: Option<u32>,
+}
+
+async fn probe(request: ProbeRequest) -> Result<Value> {
+ let project = project::LoadedProject::load(&request.project)?;
+ let total_frames = project.total_frames(request.fps);
+ let (width, height) = project.output_size(request.resolution)?;
+ let step = request.span_step.unwrap_or(request.fps * 2).max(1);
+ let spans = (0..total_frames)
+ .step_by(step as usize)
+ .map(|start| project.source_spans(request.fps, [start, (start + step).min(total_frames)]))
+ .collect::<Vec<_>>();
+ let clips = project
+ .config
+ .clips
+ .iter()
+ .map(|clip| json!({ "index": clip.index, "camera": clip.offsets.camera, "mic": clip.offsets.mic }))
+ .collect::<Vec<_>>();
+ Ok(json!({
+ "total_frames": total_frames,
+ "duration": project.duration(),
+ "width": width,
+ "height": height,
+ "total_samples": total_frames as i64 * audio::SAMPLE_RATE / request.fps as i64,
+ "span_step": step,
+ "spans": spans,
+ "audio_cuts": project.audio_cuts(request.fps, audio::SAMPLE_RATE),
+ "clips": clips,
+ }))
+}
+
+async fn handle(op: Op) -> Result<Value> {
+ Ok(match op {
+ Op::Probe(request) => probe(request).await?,
+ Op::Video(request) => serde_json::to_value(video::render(request).await?)?,
+ Op::Audio(request) => serde_json::to_value(audio::render(request).await?)?,
+ Op::Warm => video::warm().await?,
+ Op::Ping => json!({ "pong": true }),
+ })
+}
+
+fn main() -> Result<()> {
+ tracing_subscriber::fmt()
+ .with_writer(std::io::stderr)
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| "warn,cap_render_farm=info".into()),
+ )
+ .init();
+ ffmpeg::init()?;
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()?;
+
+ let mut args = std::env::args().skip(1);
+ if args.next().as_deref() == Some("once") {
+ let line = args.next().unwrap_or_default();
+ let request: Request = serde_json::from_str(&line)?;
+ let result = runtime.block_on(handle(request.op))?;
+ println!("{}", serde_json::to_string(&result)?);
+ return Ok(());
+ }
+
+ let stdin = std::io::stdin();
+ let mut stdout = std::io::stdout();
+ for line in stdin.lock().lines() {
+ let line = line?;
+ if line.trim().is_empty() {
+ continue;
+ }
+ let started = Instant::now();
+ let response = match serde_json::from_str::<Request>(&line) {
+ Ok(request) => {
+ let id = request.id.clone();
+ if let Ok(mut current) = CURRENT_REQUEST.lock() {
+ *current = Some(id.clone());
+ }
+ let result = runtime.block_on(handle(request.op));
+ if let Ok(mut current) = CURRENT_REQUEST.lock() {
+ *current = None;
+ }
+ match result {
+ Ok(result) => {
+ json!({ "id": id, "ok": true, "result": result, "ms": started.elapsed().as_millis() as u64 })
+ }
+ Err(error) => json!({ "id": id, "ok": false, "error": format!("{error:#}") }),
+ }
+ }
+ Err(error) => json!({ "ok": false, "error": format!("bad request: {error}") }),
+ };
+ writeln!(stdout, "{}", serde_json::to_string(&response)?)?;
+ stdout.flush()?;
+ }
+ Ok(())
+}
diff --git a/crates/render-farm/src/project.rs b/crates/render-farm/src/project.rs
new file mode 100644
index 000000000..52cc07066
--- /dev/null
+++ b/crates/render-farm/src/project.rs
@@ -0,0 +1,167 @@
+use anyhow::{Context, Result, anyhow};
+use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY};
+use cap_rendering::{ProjectRecordingsMeta, ProjectUniforms, RenderOptions};
+use serde::Serialize;
+use std::{
+ path::{Path, PathBuf},
+ sync::Arc,
+};
+
+/// Everything a chunk needs to agree on with every other chunk of the same
+/// export: the prepared config, the recording, and the frame count. Loading
+/// it the same way as `ExporterBase` keeps the timeline identical to a
+/// single-machine export.
+pub struct LoadedProject {
+ pub path: PathBuf,
+ pub config: ProjectConfiguration,
+ pub recording_meta: RecordingMeta,
+ pub studio_meta: StudioRecordingMeta,
+ pub recordings: Arc<ProjectRecordingsMeta>,
+}
+
+impl LoadedProject {
+ pub fn load(path: &Path) -> Result<Self> {
+ let config = ProjectConfiguration::load(path).context("project-config.json")?;
+ let mut config = cap_export::prepare_project_for_export(config);
+ let recording_meta = RecordingMeta::load_for_project(path)
+ .map_err(|error| anyhow!("recording-meta.json: {error}"))?;
+ let studio_meta = recording_meta
+ .studio_meta()
+ .ok_or_else(|| anyhow!("not a studio recording"))?
+ .clone();
+ let recordings = Arc::new(
+ ProjectRecordingsMeta::new(&recording_meta.project_path, &studio_meta)
+ .map_err(|error| anyhow!("recordings: {error}"))?,
+ );
+ cap_export::synthesize_default_timeline(&mut config, &recordings);
+ cap_project::synchronize_legacy_keyboard(&recording_meta, &mut config);
+ cap_project::synchronize_captions(
+ &mut config,
+ &recordings
+ .segments
+ .iter()
+ .map(|segment| segment.display.duration)
+ .collect::<Vec<_>>(),
+ );
+ Ok(Self {
+ path: path.to_path_buf(),
+ config,
+ recording_meta,
+ studio_meta,
+ recordings,
+ })
+ }
+
+ pub fn duration(&self) -> f64 {
+ cap_rendering::get_duration(
+ &self.recordings,
+ &self.recording_meta,
+ &self.studio_meta,
+ &self.config,
+ )
+ }
+
+ pub fn total_frames(&self, fps: u32) -> u32 {
+ (fps as f64 * self.duration()).ceil() as u32
+ }
+
+ pub fn render_options(&self) -> Result<RenderOptions> {
+ let first = self
+ .recordings
+ .segments
+ .first()
+ .ok_or_else(|| anyhow!("recording has no segments"))?;
+ Ok(RenderOptions {
+ screen_size: XY::new(first.display.width, first.display.height),
+ camera_size: first
+ .camera
+ .as_ref()
+ .map(|camera| XY::new(camera.width, camera.height)),
+ preserve_screen_alpha: false,
+ })
+ }
+
+ pub fn output_size(&self, resolution: [u32; 2]) -> Result<(u32, u32)> {
+ Ok(ProjectUniforms::get_output_size(
+ &self.render_options()?,
+ &self.config,
+ XY::new(resolution[0], resolution[1]),
+ ))
+ }
+
+ /// Source-time extent each output frame range reads, per recording clip.
+ /// The coordinator widens these by keyframe distance and clip offsets to
+ /// decide which bytes of each source a chunk worker has to download.
+ pub fn source_spans(&self, fps: u32, frames: [u32; 2]) -> Vec<ClipSpan> {
+ let mut spans: Vec<ClipSpan> = Vec::new();
+ for frame in frames[0]..frames[1] {
+ let time = frame as f64 / fps as f64;
+ let Some((segment_time, segment)) = self.config.get_segment_time(time) else {
+ continue;
+ };
+ let clip = segment.recording_clip;
+ match spans.iter_mut().find(|span| span.clip == clip) {
+ Some(span) => {
+ span.start = span.start.min(segment_time);
+ span.end = span.end.max(segment_time);
+ }
+ None => spans.push(ClipSpan {
+ clip,
+ start: segment_time,
+ end: segment_time,
+ }),
+ }
+ }
+ spans
+ }
+}
+
+fn mapping_key(timeline: &cap_project::TimelineConfiguration, time: f64) -> Option<(u8, usize)> {
+ use cap_project::TimelineFrameMapping;
+ Some(match timeline.get_frame_mapping(time)? {
+ TimelineFrameMapping::Single { source, .. } => (0, source.segment_index),
+ TimelineFrameMapping::Hold { source, .. } => (1, source.segment_index),
+ TimelineFrameMapping::Transition { incoming, .. } => (2, incoming.segment_index),
+ })
+}
+
+impl LoadedProject {
+ /// Output sample positions where the timeline switches clip segment (or
+ /// enters/leaves a hold or transition). The audio renderer starts every
+ /// segment with fresh Studio Sound and speed state, so an audio section
+ /// that begins at one of these points renders bit-identically to an
+ /// unbroken export.
+ pub fn audio_cuts(&self, fps: u32, sample_rate: i64) -> Vec<i64> {
+ let Some(timeline) = &self.config.timeline else {
+ return Vec::new();
+ };
+ let total = self.total_frames(fps);
+ let mut cuts = Vec::new();
+ let mut previous = mapping_key(timeline, 0.0);
+ for frame in 1..total {
+ let time = frame as f64 / fps as f64;
+ let key = mapping_key(timeline, time);
+ if key != previous {
+ let (mut low, mut high) = ((frame - 1) as f64 / fps as f64, time);
+ while high - low > 0.25 / sample_rate as f64 {
+ let middle = (low + high) / 2.0;
+ if mapping_key(timeline, middle) == previous {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ cuts.push((high * sample_rate as f64).ceil() as i64);
+ previous = key;
+ }
+ }
+ cuts
+ }
+}
+
+#[derive(Serialize, Clone, Copy)]
+pub struct ClipSpan {
+ pub clip: u32,
+ pub start: f64,
+ pub end: f64,
+}
diff --git a/crates/render-farm/src/video.rs b/crates/render-farm/src/video.rs
new file mode 100644
index 000000000..9b717f81f
--- /dev/null
+++ b/crates/render-farm/src/video.rs
@@ -0,0 +1,819 @@
+use crate::project::LoadedProject;
+use anyhow::{Context, Result, anyhow, bail};
+use cap_project::XY;
+use cap_rendering::{
+ FrameWindows, GpuOutputFormat, Nv12RenderStartupBreakdownMs, Nv12RenderedFrame, RenderSegment,
+ RenderVideoConstants, SharedWgpuDevice,
+};
+use ffmpeg::{
+ Dictionary, Rational,
+ codec::{self, flag::Flags},
+ color,
+ format::Pixel,
+ frame,
+};
+use serde::{Deserialize, Serialize};
+use std::{
+ fs::File,
+ io::{BufWriter, Write},
+ path::PathBuf,
+ sync::{Arc, Mutex},
+ time::Instant,
+};
+
+/// The wgpu device outlives requests: the engine is one long-lived process per
+/// slot, and creating an instance/adapter/device costs ~150-450 ms per chunk
+/// (more when a GPU's slots all start at once). `RF_REUSE_DEVICE=0` disables.
+type CachedDevice = (
+ wgpu::Instance,
+ wgpu::Adapter,
+ wgpu::Device,
+ wgpu::Queue,
+ bool,
+);
+static DEVICE: Mutex<Option<CachedDevice>> = Mutex::new(None);
+
+/// A slot renders several chunks of the same job back to back; the project
+/// (config prep + probing every source file) is identical for all of them.
+/// Job directories are unique, so the path is a safe key.
+static PROJECT: Mutex<Option<Arc<LoadedProject>>> = Mutex::new(None);
+
+fn load_project(path: &std::path::Path) -> Result<Arc<LoadedProject>> {
+ if let Ok(cached) = PROJECT.lock()
+ && let Some(project) = cached.as_ref().filter(|project| project.path == path)
+ {
+ return Ok(project.clone());
+ }
+ let project = Arc::new(LoadedProject::load(path)?);
+ if let Ok(mut cached) = PROJECT.lock() {
+ *cached = Some(project.clone());
+ }
+ Ok(project)
+}
+
+/// The process-wide device, created on first use.
+async fn shared_device() -> Result<SharedWgpuDevice> {
+ if let Some((instance, adapter, device, queue, is_software_adapter)) =
+ DEVICE.lock().ok().and_then(|device| device.clone())
+ {
+ return Ok(SharedWgpuDevice {
+ instance,
+ adapter,
+ device,
+ queue,
+ is_software_adapter,
+ });
+ }
+ let shared = cap_rendering::create_shared_device()
+ .await
+ .map_err(|error| anyhow!("device: {error}"))?;
+ if let Ok(mut device) = DEVICE.lock() {
+ *device = Some((
+ shared.instance.clone(),
+ shared.adapter.clone(),
+ shared.device.clone(),
+ shared.queue.clone(),
+ shared.is_software_adapter,
+ ));
+ }
+ Ok(shared)
+}
+
+/// Off the next task's critical path: a fresh layer set (no project state)
+/// for whichever project this slot renders next.
+fn prebuild_spare_layers_in_background() {
+ if !reuse_device() {
+ return;
+ }
+ let Some((_, _, device, queue, is_software_adapter)) =
+ DEVICE.lock().ok().and_then(|device| device.clone())
+ else {
+ return;
+ };
+ std::thread::spawn(move || {
+ cap_rendering::prebuild_spare_layers(&device, &queue, is_software_adapter);
+ });
+}
+
+/// Boot-time warmup: CUDA context, wgpu device and one spare layer set, so
+/// the first task after a (re)start pays none of it.
+pub async fn warm() -> Result<serde_json::Value> {
+ let started = Instant::now();
+ #[cfg(target_os = "linux")]
+ if cap_rendering::linux_gpu::enabled() {
+ cap_rendering::linux_gpu::init().map_err(|error| anyhow!("cuda: {error}"))?;
+ }
+ let shared = shared_device().await?;
+ let device_ms = started.elapsed().as_millis() as u64;
+ cap_rendering::prebuild_spare_layers(&shared.device, &shared.queue, shared.is_software_adapter);
+ Ok(serde_json::json!({
+ "device_ms": device_ms,
+ "total_ms": started.elapsed().as_millis() as u64,
+ }))
+}
+
+fn cap_rendering_gpu_frames_expected() -> bool {
+ #[cfg(target_os = "linux")]
+ {
+ cap_rendering::linux_gpu::enabled()
+ && std::env::var("RF_ENCODER").as_deref() == Ok("h264_nvenc")
+ }
+ #[cfg(not(target_os = "linux"))]
+ false
+}
+
+fn reuse_device() -> bool {
+ std::env::var("RF_REUSE_DEVICE").map_or(true, |value| value != "0")
+}
+
+#[derive(Deserialize)]
+pub struct VideoRequest {
+ pub project: PathBuf,
+ pub fps: u32,
+ pub resolution: [u32; 2],
+ pub bpp: f32,
+ pub frames: [u32; 2],
+ pub threads: Option<usize>,
+ pub out: PathBuf,
+}
+
+#[derive(Serialize)]
+pub struct VideoResult {
+ pub width: u32,
+ pub height: u32,
+ pub frames: u32,
+ /// Length-prefixed (4 byte) H.264 samples, in decode order == display
+ /// order because B-frames are off, exactly like the native export.
+ pub sizes: Vec<u32>,
+ pub keyframes: Vec<u32>,
+ /// Annex B SPS/PPS from libx264's global header.
+ pub extradata: String,
+ pub bytes: u64,
+ pub timings: VideoTimings,
+}
+
+#[derive(Serialize, Default)]
+pub struct VideoTimings {
+ pub load_ms: u64,
+ pub constants_ms: u64,
+ pub decoders_ms: u64,
+ pub first_frame_ms: u64,
+ pub render_ms: u64,
+ pub total_ms: u64,
+ pub startup: Option<Nv12RenderStartupBreakdownMs>,
+ /// [allocated shared buffers, pooled, CUDA free MiB] at start and end.
+ pub gpu_mem: Vec<[u64; 3]>,
+ /// Cumulative ms per pipeline stage (render loop, forward hop, encoder).
+ pub pipeline: Option<serde_json::Value>,
+ /// Which parts ran on the GPU (adapter, decoders, CUDA frames to NVENC).
+ pub gpu_path: Option<serde_json::Value>,
+}
+
+fn gpu_mem() -> [u64; 3] {
+ #[cfg(target_os = "linux")]
+ {
+ let (allocated, pooled, free) = cap_rendering::linux_gpu::memory_stats();
+ [allocated as u64, pooled as u64, free]
+ }
+ #[cfg(not(target_os = "linux"))]
+ [0, 0, 0]
+}
+
+/// Same bitrate model as `cap_enc_ffmpeg::h264::get_bitrate`, so a chunked
+/// export spends exactly the bits a desktop export would.
+fn bitrate(width: u32, height: u32, fps: f32, bpp: f32) -> usize {
+ let frame_rate_multiplier = ((fps as f64 - 30.0).max(0.0) * 0.6) + 30.0;
+ (width as f64 * height as f64 * frame_rate_multiplier * bpp as f64) as usize
+}
+
+pub async fn render(request: VideoRequest) -> Result<VideoResult> {
+ let started = Instant::now();
+ #[cfg(target_os = "linux")]
+ if cap_rendering::linux_gpu::enabled() {
+ cap_rendering::linux_gpu::init().map_err(|error| anyhow!("cuda: {error}"))?;
+ }
+ let mut timings = VideoTimings::default();
+ timings.gpu_mem.push(gpu_mem());
+ let project = load_project(&request.project)?;
+ let total_frames = project.total_frames(request.fps);
+ if request.frames[0] >= request.frames[1] || request.frames[1] > total_frames {
+ bail!("frame range {:?} outside 0..{total_frames}", request.frames);
+ }
+ let (width, height) = project.output_size(request.resolution)?;
+ timings.load_ms = started.elapsed().as_millis() as u64;
+
+ let phase = Instant::now();
+ let constants = if reuse_device() {
+ RenderVideoConstants::new_with_device(
+ shared_device().await?,
+ &project.recordings.segments,
+ project.recording_meta.clone(),
+ project.studio_meta.clone(),
+ )
+ .map_err(|error| anyhow!("renderer: {error}"))?
+ } else {
+ RenderVideoConstants::new(
+ &project.recordings.segments,
+ project.recording_meta.clone(),
+ project.studio_meta.clone(),
+ )
+ .await
+ .map_err(|error| anyhow!("renderer: {error}"))?
+ };
+ timings.constants_ms = phase.elapsed().as_millis() as u64;
+
+ let phase = Instant::now();
+ let segments = cap_editor::create_segments_without_audio(
+ &project.recording_meta,
+ &project.studio_meta,
+ false,
+ )
+ .await
+ .map_err(|error| anyhow!("decoders: {error}"))?;
+ timings.decoders_ms = phase.elapsed().as_millis() as u64;
+
+ // A render that silently fell off the GPU (llvmpipe, software decode)
+ // still produces correct frames, just several times slower, and would
+ // set the whole export's finish. With RF_REQUIRE_GPU=1 the chunk fails
+ // fast instead, so the orchestrator retries it on a healthy engine.
+ let screen_hw = segments.iter().all(|segment| {
+ segment
+ .decoders
+ .screen_decoder_status()
+ .decoder_type
+ .is_hardware_accelerated()
+ });
+ let camera_hw = segments.iter().all(|segment| {
+ segment
+ .decoders
+ .camera_decoder_status()
+ .is_none_or(|status| status.decoder_type.is_hardware_accelerated())
+ });
+ timings.gpu_path = Some(serde_json::json!({
+ "software_adapter": constants.is_software_adapter,
+ "screen_hw_decode": screen_hw,
+ "camera_hw_decode": camera_hw,
+ }));
+ if std::env::var("RF_REQUIRE_GPU").as_deref() == Ok("1")
+ && (constants.is_software_adapter || !screen_hw || !camera_hw)
+ {
+ bail!(
+ "gpu path degraded: software_adapter={} screen_hw_decode={screen_hw} camera_hw_decode={camera_hw}",
+ constants.is_software_adapter
+ );
+ }
+
+ let render_segments = segments
+ .iter()
+ .map(|segment| RenderSegment {
+ cursor: segment.cursor.clone(),
+ keyboard: segment.keyboard.clone(),
+ decoders: segment.decoders.clone(),
+ render_display: true,
+ })
+ .collect::<Vec<_>>();
+
+ let expected = request.frames[1] - request.frames[0];
+ let (frame_tx, frame_rx) = tokio::sync::mpsc::channel::<(Nv12RenderedFrame, u32)>(6);
+ let (encode_tx, encode_rx) = std::sync::mpsc::sync_channel::<Nv12RenderedFrame>(6);
+ let fps = request.fps;
+ let bpp = request.bpp;
+ let threads = request.threads;
+ let out = request.out.clone();
+ let encoder = std::thread::spawn(move || {
+ encode(encode_rx, out, width, height, fps, bpp, threads, expected)
+ });
+
+ // Chunks of the same job on this slot share compiled layer pipelines.
+ cap_rendering::set_layers_reuse_key(
+ (std::env::var("RF_REUSE_LAYERS").map_or(true, |value| value != "0"))
+ .then(|| format!("{}@{width}x{height}", request.project.display())),
+ );
+ let startup = Arc::new(Mutex::new(None));
+ let render_started = Instant::now();
+ let windows =
+ FrameWindows::new(std::iter::once(request.frames[0]..request.frames[1]).collect());
+ let render = cap_rendering::render_video_to_channel_nv12(
+ &constants,
+ &project.config,
+ frame_tx,
+ &project.recording_meta,
+ &project.studio_meta,
+ render_segments,
+ request.fps,
+ XY::new(request.resolution[0], request.resolution[1]),
+ &project.recordings,
+ Some(windows),
+ None,
+ Some(startup.clone()),
+ );
+ let forward = async {
+ // Owning the receiver here means an encoder failure drops it, which
+ // makes the renderer's next send fail instead of blocking forever.
+ let mut frame_rx = frame_rx;
+ let mut received = 0u32;
+ let mut forward_blocked_us = 0u64;
+ while let Some((frame, _)) = frame_rx.recv().await {
+ if received == 0 {
+ timings.first_frame_ms = render_started.elapsed().as_millis() as u64;
+ }
+ received += 1;
+ if received % 15 == 0 {
+ crate::report_progress(received);
+ }
+ let blocked = Instant::now();
+ if encode_tx.send(frame).is_err() {
+ break;
+ }
+ forward_blocked_us += blocked.elapsed().as_micros() as u64;
+ }
+ drop(encode_tx);
+ (received, forward_blocked_us)
+ };
+ cap_rendering::loop_stats::take();
+ let (render_result, (received, forward_blocked_us)) = tokio::join!(render, forward);
+ let [decode, render_us, next_decode, join, send, _] = cap_rendering::loop_stats::take();
+ render_result.map_err(|error| anyhow!("render: {error}"))?;
+ timings.render_ms = render_started.elapsed().as_millis() as u64;
+
+ let encoded = encoder
+ .join()
+ .map_err(|_| anyhow!("encoder thread panicked"))??;
+ if received != expected || encoded.sizes.len() as u32 != expected {
+ bail!(
+ "chunk {:?} produced {received} rendered / {} encoded frames, expected {expected}",
+ request.frames,
+ encoded.sizes.len()
+ );
+ }
+ timings.total_ms = started.elapsed().as_millis() as u64;
+ timings.startup = startup.lock().ok().and_then(|slot| slot.clone());
+ if let Some(serde_json::Value::Object(path)) = timings.gpu_path.as_mut() {
+ path.insert("cuda_frames".into(), serde_json::json!(encoded.cuda_input));
+ }
+ if std::env::var("RF_REQUIRE_GPU").as_deref() == Ok("1")
+ && cap_rendering_gpu_frames_expected()
+ && !encoded.cuda_input
+ {
+ bail!("gpu path degraded: frames reached the encoder through system memory");
+ }
+ let ms = |us: u64| us / 1000;
+ timings.pipeline = Some(serde_json::json!({
+ "decode_wait": ms(decode),
+ "render": ms(render_us),
+ "next_decode": ms(next_decode),
+ "render_join": ms(join),
+ "send_wait": ms(send),
+ "forward_blocked": ms(forward_blocked_us),
+ "encoder_wait": ms(encoded.stats[0]),
+ "cuda_copy": ms(encoded.stats[1]),
+ "encode": ms(encoded.stats[2]),
+ }));
+ prebuild_spare_layers_in_background();
+ timings.gpu_mem.push(gpu_mem());
+ Ok(VideoResult {
+ width,
+ height,
+ frames: expected,
+ bytes: encoded.sizes.iter().map(|size| *size as u64).sum(),
+ sizes: encoded.sizes,
+ keyframes: encoded.keyframes,
+ extradata: base64_encode(&encoded.extradata),
+ timings,
+ })
+}
+
+struct Encoded {
+ sizes: Vec<u32>,
+ keyframes: Vec<u32>,
+ extradata: Vec<u8>,
+ /// µs: waiting for the next frame, CUDA copy into the encoder surface,
+ /// send_frame + packet drain.
+ stats: [u64; 3],
+ /// Frames reached NVENC as CUDA surfaces (no CPU round trip).
+ cuda_input: bool,
+}
+
+#[allow(clippy::too_many_arguments)]
+fn encode(
+ frames: std::sync::mpsc::Receiver<Nv12RenderedFrame>,
+ out: PathBuf,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bpp: f32,
+ threads: Option<usize>,
+ expected: u32,
+) -> Result<Encoded> {
+ let encoder_name = std::env::var("RF_ENCODER").unwrap_or_else(|_| "libx264".to_string());
+ let nvenc = encoder_name == "h264_nvenc";
+ // The renderer decides where frames live; the first one tells us whether
+ // NVENC should take CUDA surfaces (GPU-only path) or system memory.
+ let first = frames.recv().ok();
+ #[cfg(target_os = "linux")]
+ let cuda_input = nvenc && first.as_ref().is_some_and(|frame| frame.gpu.is_some());
+ #[cfg(not(target_os = "linux"))]
+ let cuda_input = false;
+ let cuda_frames = if cuda_input {
+ Some(CudaFrames::new(width, height)?)
+ } else {
+ None
+ };
+ let codec = ffmpeg::encoder::find_by_name(&encoder_name)
+ .with_context(|| format!("{encoder_name} unavailable"))?;
+ let mut context = codec::context::Context::new_with_codec(codec);
+ let threads = threads.unwrap_or_else(|| {
+ std::thread::available_parallelism()
+ .map(|value| value.get())
+ .unwrap_or(4)
+ });
+ if !nvenc {
+ context.set_threading(ffmpeg::threading::Config::count(threads));
+ }
+ let mut encoder = context.encoder().video()?;
+ encoder.set_width(width);
+ encoder.set_height(height);
+ encoder.set_format(if cuda_input { Pixel::CUDA } else { Pixel::NV12 });
+ if let Some(cuda_frames) = &cuda_frames {
+ unsafe {
+ (*encoder.as_mut_ptr()).hw_frames_ctx = ffmpeg::ffi::av_buffer_ref(cuda_frames.frames);
+ }
+ }
+ encoder.set_time_base(Rational::new(1, fps as i32));
+ encoder.set_frame_rate(Some(Rational::new(fps as i32, 1)));
+ encoder.set_colorspace(color::Space::BT709);
+ encoder.set_color_range(color::Range::MPEG);
+ unsafe {
+ (*encoder.as_mut_ptr()).color_primaries = ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709;
+ (*encoder.as_mut_ptr()).color_trc =
+ ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
+ }
+ let target = bitrate(width, height, fps as f32, bpp);
+ encoder.set_bit_rate(target);
+ encoder.set_max_bit_rate(target * 3 / 2);
+ encoder.set_flags(Flags::GLOBAL_HEADER);
+
+ let keyint = (fps * cap_enc_ffmpeg_keyframe_secs()).to_string();
+ let mut options = Dictionary::new();
+ if nvenc {
+ // The native export's NVENC set (crates/enc-ffmpeg h264.rs), minus
+ // B-frames: chunk assembly writes a table without composition offsets.
+ // Preset p1 instead of p5: 4K is NVENC-bound, and against a lossless
+ // render p1 measured 0.4 dB below p5 at the same bitrate for ~50% more
+ // throughput. RF_NVENC_* override the set.
+ let env =
+ |name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.into());
+ options.set("preset", &env("RF_NVENC_PRESET", "p1"));
+ options.set("tune", &env("RF_NVENC_TUNE", "hq"));
+ if env("RF_NVENC_TUNE", "hq") == "lossless" {
+ // Reference renders for quality comparisons.
+ options.set("rc", "constqp");
+ options.set("qp", "0");
+ } else {
+ options.set("rc", "vbr");
+ }
+ options.set("spatial-aq", &env("RF_NVENC_SAQ", "1"));
+ options.set("temporal-aq", &env("RF_NVENC_TAQ", "1"));
+ options.set("bf", "0");
+ options.set("g", &keyint);
+ options.set("forced-idr", "1");
+ } else {
+ // The native export's libx264 option set (crates/enc-ffmpeg h264.rs,
+ // `is_export` + default preset), so quality and GOP match desktop output.
+ options.set("preset", "veryfast");
+ options.set("threads", &threads.to_string());
+ options.set("bf", "0");
+ options.set("rc-lookahead", "10");
+ options.set("b-adapt", "0");
+ options.set("aq-mode", "1");
+ options.set("ref", "2");
+ options.set("subme", "2");
+ options.set("trellis", "0");
+ options.set("g", &keyint);
+ options.set("keyint_min", &keyint);
+ }
+ let mut encoder = encoder.open_as_with(codec, options)?;
+
+ let extradata = unsafe {
+ let pointer = encoder.as_ptr();
+ std::slice::from_raw_parts((*pointer).extradata, (*pointer).extradata_size as usize)
+ .to_vec()
+ };
+
+ crate::report_event("extradata", serde_json::json!(base64_encode(&extradata)));
+
+ let mut output = BufWriter::with_capacity(8 << 20, File::create(&out)?);
+ let mut sizes = Vec::with_capacity(expected as usize);
+ let mut keyframes = Vec::new();
+ let mut packet = ffmpeg::Packet::empty();
+ // Frames before this index have been announced as finished GOPs.
+ let mut announced = 0usize;
+ let mut drain = |encoder: &mut ffmpeg::encoder::Video,
+ sizes: &mut Vec<u32>,
+ keyframes: &mut Vec<u32>|
+ -> Result<()> {
+ while encoder.receive_packet(&mut packet).is_ok() {
+ let data = packet.data().ok_or_else(|| anyhow!("empty packet"))?;
+ if packet.is_key() && sizes.len() > announced {
+ // A new GOP starts: everything before it is final. Flush so
+ // the worker can read those bytes and publish a segment now.
+ output.flush()?;
+ crate::report_event(
+ "gop",
+ serde_json::json!({ "first": announced, "sizes": &sizes[announced..] }),
+ );
+ announced = sizes.len();
+ }
+ let written = write_length_prefixed(&mut output, data)?;
+ if packet.is_key() {
+ keyframes.push(sizes.len() as u32);
+ }
+ sizes.push(written);
+ }
+ Ok(())
+ };
+
+ let mut nv12 = frame::Video::new(Pixel::NV12, width, height);
+ let mut rgba_converter: Option<ffmpeg::software::scaling::Context> = None;
+ let mut stats = [0u64; 3];
+ let mut waiting = Instant::now();
+ for (index, rendered) in first.into_iter().chain(frames.iter()).enumerate() {
+ let pts = index as i64;
+ stats[0] += waiting.elapsed().as_micros() as u64;
+ #[cfg(target_os = "linux")]
+ if let (Some(cuda_frames), Some(gpu)) = (&cuda_frames, rendered.gpu.as_ref()) {
+ let copy = Instant::now();
+ let mut surface = cuda_frames.frame(gpu, width, height)?;
+ stats[1] += copy.elapsed().as_micros() as u64;
+ surface.set_pts(Some(pts));
+ drop(rendered);
+ let encode = Instant::now();
+ encoder.send_frame(&surface)?;
+ drain(&mut encoder, &mut sizes, &mut keyframes)?;
+ stats[2] += encode.elapsed().as_micros() as u64;
+ waiting = Instant::now();
+ continue;
+ }
+ if rendered.width != width || rendered.height != height {
+ bail!(
+ "renderer produced {}x{}, expected {width}x{height}",
+ rendered.width,
+ rendered.height
+ );
+ }
+ // The encoder may still hold a reference to the previous frame's buffer.
+ unsafe { ffmpeg::ffi::av_frame_make_writable(nv12.as_mut_ptr()) };
+ if rendered.format == GpuOutputFormat::Rgba {
+ let mut rgba = frame::Video::new(Pixel::RGBA, width, height);
+ let stride = rgba.stride(0);
+ let source_stride = rendered.y_stride as usize;
+ for row in 0..height as usize {
+ let length = (width as usize * 4).min(stride).min(source_stride);
+ rgba.data_mut(0)[row * stride..row * stride + length].copy_from_slice(
+ &rendered.data[row * source_stride..row * source_stride + length],
+ );
+ }
+ let converter = match &mut rgba_converter {
+ Some(converter) => converter,
+ None => rgba_converter.insert(ffmpeg::software::scaling::Context::get(
+ Pixel::RGBA,
+ width,
+ height,
+ Pixel::NV12,
+ width,
+ height,
+ ffmpeg::software::scaling::flag::Flags::BILINEAR,
+ )?),
+ };
+ converter.run(&rgba, &mut nv12)?;
+ } else {
+ fill_nv12(&mut nv12, &rendered.data, width, height, rendered.y_stride);
+ }
+ nv12.set_pts(Some(pts));
+ encoder.send_frame(&nv12)?;
+ drain(&mut encoder, &mut sizes, &mut keyframes)?;
+ waiting = Instant::now();
+ }
+ encoder.send_eof()?;
+ drain(&mut encoder, &mut sizes, &mut keyframes)?;
+ output.flush()?;
+ if keyframes.first() != Some(&0) {
+ bail!("chunk does not start with a keyframe");
+ }
+ Ok(Encoded {
+ sizes,
+ keyframes,
+ extradata,
+ stats,
+ cuda_input,
+ })
+}
+
+fn cap_enc_ffmpeg_keyframe_secs() -> u32 {
+ 2
+}
+
+fn fill_nv12(frame: &mut frame::Video, data: &[u8], width: u32, height: u32, y_stride: u32) {
+ let width = width as usize;
+ let height = height as usize;
+ let y_stride = y_stride as usize;
+ let destination_stride = frame.stride(0);
+ for row in 0..height {
+ frame.data_mut(0)[row * destination_stride..row * destination_stride + width]
+ .copy_from_slice(&data[row * y_stride..row * y_stride + width]);
+ }
+ let uv = &data[y_stride * height..];
+ let destination_stride = frame.stride(1);
+ for row in 0..height / 2 {
+ frame.data_mut(1)[row * destination_stride..row * destination_stride + width]
+ .copy_from_slice(&uv[row * width..row * width + width]);
+ }
+}
+
+/// libx264 emits Annex B; MP4 wants 4-byte NAL lengths. Returns bytes written.
+fn write_length_prefixed(output: &mut impl Write, data: &[u8]) -> Result<u32> {
+ let mut written = 0u32;
+ let starts = nal_starts(data);
+ for (index, &(start, prefix)) in starts.iter().enumerate() {
+ let payload_start = start + prefix;
+ let payload_end = starts
+ .get(index + 1)
+ .map(|&(next, _)| next)
+ .unwrap_or(data.len());
+ let mut end = payload_end;
+ while end > payload_start && data[end - 1] == 0 {
+ end -= 1;
+ }
+ let nal = &data[payload_start..end];
+ if nal.is_empty() {
+ continue;
+ }
+ output.write_all(&(nal.len() as u32).to_be_bytes())?;
+ output.write_all(nal)?;
+ written += 4 + nal.len() as u32;
+ }
+ Ok(written)
+}
+
+fn nal_starts(data: &[u8]) -> Vec<(usize, usize)> {
+ let mut starts = Vec::new();
+ let mut index = 0;
+ while index + 3 <= data.len() {
+ if data[index] == 0 && data[index + 1] == 0 {
+ if data[index + 2] == 1 {
+ starts.push((index, 3));
+ index += 3;
+ continue;
+ }
+ if index + 4 <= data.len() && data[index + 2] == 0 && data[index + 3] == 1 {
+ starts.push((index, 4));
+ index += 4;
+ continue;
+ }
+ }
+ index += 1;
+ }
+ starts
+}
+
+pub fn base64_encode(bytes: &[u8]) -> String {
+ use base64::Engine;
+ base64::engine::general_purpose::STANDARD.encode(bytes)
+}
+
+/// NVENC input surfaces in CUDA memory (hw_frames_ctx), filled device-to-
+/// device from the renderer's shared output buffers.
+struct CudaFrames {
+ device: *mut ffmpeg::ffi::AVBufferRef,
+ frames: *mut ffmpeg::ffi::AVBufferRef,
+}
+
+impl CudaFrames {
+ fn new(width: u32, height: u32) -> Result<Self> {
+ use ffmpeg::ffi::*;
+ unsafe {
+ let mut device = std::ptr::null_mut();
+ let mut options = std::ptr::null_mut();
+ av_dict_set(&mut options, c"primary_ctx".as_ptr(), c"1".as_ptr(), 0);
+ let created = av_hwdevice_ctx_create(
+ &mut device,
+ AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA,
+ std::ptr::null(),
+ options,
+ 0,
+ );
+ av_dict_free(&mut options);
+ if created < 0 {
+ bail!("CUDA device for NVENC: {created}");
+ }
+ let frames = av_hwframe_ctx_alloc(device);
+ if frames.is_null() {
+ bail!("av_hwframe_ctx_alloc failed");
+ }
+ let context = (*frames).data as *mut AVHWFramesContext;
+ (*context).format = AVPixelFormat::AV_PIX_FMT_CUDA;
+ (*context).sw_format = AVPixelFormat::AV_PIX_FMT_NV12;
+ (*context).width = width as i32;
+ (*context).height = height as i32;
+ (*context).initial_pool_size = 8;
+ let initialised = av_hwframe_ctx_init(frames);
+ if initialised < 0 {
+ bail!("CUDA frame pool: {initialised}");
+ }
+ Ok(Self { device, frames })
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ fn frame(
+ &self,
+ gpu: &cap_rendering::linux_gpu::GpuNv12Output,
+ width: u32,
+ height: u32,
+ ) -> Result<frame::Video> {
+ let mut surface = frame::Video::empty();
+ unsafe {
+ let result = ffmpeg::ffi::av_hwframe_get_buffer(self.frames, surface.as_mut_ptr(), 0);
+ if result < 0 {
+ bail!("av_hwframe_get_buffer: {result}");
+ }
+ let raw = surface.as_mut_ptr();
+ (*raw).color_range = ffmpeg::ffi::AVColorRange::AVCOL_RANGE_MPEG;
+ (*raw).colorspace = ffmpeg::ffi::AVColorSpace::AVCOL_SPC_BT709;
+ (*raw).color_primaries = ffmpeg::ffi::AVColorPrimaries::AVCOL_PRI_BT709;
+ (*raw).color_trc = ffmpeg::ffi::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
+ let source = gpu.cuda_ptr();
+ cap_rendering::linux_gpu::copy_plane(
+ source,
+ gpu.y_stride as usize,
+ (*raw).data[0] as u64,
+ (*raw).linesize[0] as usize,
+ width as usize,
+ height as usize,
+ )
+ .map_err(|error| anyhow!(error))?;
+ cap_rendering::linux_gpu::copy_plane(
+ source + gpu.uv_offset,
+ gpu.uv_stride as usize,
+ (*raw).data[1] as u64,
+ (*raw).linesize[1] as usize,
+ width as usize,
+ height as usize / 2,
+ )
+ .map_err(|error| anyhow!(error))?;
+ // The source slot is released (and reused by Vulkan) once `gpu`
+ // drops, so the copy must have landed before this returns.
+ cap_rendering::linux_gpu::synchronize().map_err(|error| anyhow!(error))?;
+ }
+ Ok(surface)
+ }
+}
+
+impl Drop for CudaFrames {
+ fn drop(&mut self) {
+ unsafe {
+ ffmpeg::ffi::av_buffer_unref(&mut self.frames);
+ ffmpeg::ffi::av_buffer_unref(&mut self.device);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn annex_b_packets_become_length_prefixed_samples() {
+ let packet = [
+ 0, 0, 0, 1, 0x09, 0xf0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00, 0x00, 0, 0, 0, 1, 0x06, 0x05,
+ ];
+ let mut out = Vec::new();
+ let written = write_length_prefixed(&mut out, &packet).unwrap();
+ assert_eq!(
+ out,
+ [
+ 0, 0, 0, 2, 0x09, 0xf0, 0, 0, 0, 3, 0x65, 0x88, 0x84, 0, 0, 0, 2, 0x06, 0x05
+ ]
+ );
+ assert_eq!(written as usize, out.len());
+ }
+
+ #[test]
+ fn packets_without_start_codes_write_nothing() {
+ let mut out = Vec::new();
+ assert_eq!(write_length_prefixed(&mut out, &[0x65, 0x88]).unwrap(), 0);
+ assert!(out.is_empty());
+ }
+
+ #[test]
+ fn finds_three_and_four_byte_start_codes() {
+ let data = [0, 0, 1, 0x67, 0, 0, 0, 1, 0x68, 0xaa];
+ assert_eq!(nal_starts(&data), vec![(0, 3), (4, 4)]);
+ }
+
+ #[test]
+ fn bitrate_matches_the_native_export_model() {
+ assert_eq!(bitrate(1920, 1080, 30.0, 0.3), 18_662_400);
+ assert!(bitrate(1920, 1080, 60.0, 0.3) > bitrate(1920, 1080, 30.0, 0.3));
+ }
+}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index cb030f00f..8166d4860 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -46,6 +46,11 @@ wgpu-hal = { workspace = true, features = ["metal"] }
wgpu-core.workspace = true
foreign-types = "0.5"
+[target.'cfg(target_os = "linux")'.dependencies]
+wgpu-hal = { workspace = true, features = ["vulkan"] }
+ash = "0.38"
+libloading = "0.8"
+
[target.'cfg(target_os = "windows")'.dependencies]
wgpu-hal = { workspace = true, features = ["dx12"] }
wgpu-core.workspace = true
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index 39afc4518..6e6a03623 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -32,10 +32,16 @@ struct ProcessedFrame {
format: PixelFormat,
y_stride: u32,
uv_stride: u32,
+ #[cfg(target_os = "linux")]
+ cuda: Option<Arc<crate::linux_gpu::CudaNv12Frame>>,
}
impl ProcessedFrame {
fn to_decoded_frame(&self) -> DecodedFrame {
+ #[cfg(target_os = "linux")]
+ if let Some(cuda) = &self.cuda {
+ return DecodedFrame::new_nv12_cuda(Arc::clone(cuda));
+ }
match self.format {
PixelFormat::Rgba => {
DecodedFrame::new_with_arc(Arc::clone(&self.data), self.width, self.height)
@@ -131,6 +137,37 @@ impl CachedFrame {
fn process_cpu(&mut self, converter: &mut FrameConverter) -> ProcessedFrame {
match self {
Self::Raw { frame, number } => {
+ #[cfg(target_os = "linux")]
+ if crate::linux_gpu::enabled() && frame.format() == format::Pixel::CUDA {
+ // Keep NVDEC's surface: a new reference holds it alive
+ // while the compositor copies it device-to-device.
+ let data = unsafe {
+ let mut reference = frame::Video::empty();
+ ffmpeg::ffi::av_frame_ref(reference.as_mut_ptr(), frame.as_ptr());
+ let raw = reference.as_ptr();
+ let cuda = crate::linux_gpu::CudaNv12Frame::new(
+ (*raw).data[0] as u64,
+ (*raw).data[1] as u64,
+ (*raw).linesize[0] as usize,
+ (*raw).linesize[1] as usize,
+ frame.width(),
+ frame.height(),
+ Box::new(reference),
+ );
+ ProcessedFrame {
+ data: Arc::new(Vec::new()),
+ number: *number,
+ width: frame.width(),
+ height: frame.height(),
+ format: PixelFormat::Nv12,
+ y_stride: cuda.y_pitch as u32,
+ uv_stride: cuda.uv_pitch as u32,
+ cuda: Some(Arc::new(cuda)),
+ }
+ };
+ *self = Self::Processed(data.clone());
+ return data;
+ }
let data = if let Some((yuv_data, pixel_format, y_stride, uv_stride)) =
extract_yuv_planes(frame)
{
@@ -142,6 +179,8 @@ impl CachedFrame {
format: pixel_format,
y_stride,
uv_stride,
+ #[cfg(target_os = "linux")]
+ cuda: None,
}
} else {
let frame_buffer = converter.convert(frame);
@@ -153,6 +192,8 @@ impl CachedFrame {
format: PixelFormat::Rgba,
y_stride: frame.width() * 4,
uv_stride: 0,
+ #[cfg(target_os = "linux")]
+ cuda: None,
}
};
@@ -205,6 +246,16 @@ enum CachedFrame {
impl CachedFrame {
fn estimated_bytes(&self) -> usize {
+ // Frames still on the GPU pin an NVDEC surface each; weighting them
+ // at 16 MB caps the 128 MB cache at 8 surfaces, inside the pool.
+ #[cfg(target_os = "linux")]
+ match self {
+ Self::Raw { frame, .. } if frame.format() == format::Pixel::CUDA => {
+ return 16 * 1024 * 1024;
+ }
+ Self::Processed(frame) if frame.cuda.is_some() => return 16 * 1024 * 1024,
+ _ => {}
+ }
match self {
Self::Raw { frame, .. } => {
let height = frame.height() as usize;
@@ -235,6 +286,19 @@ impl CachedFrame {
}
}
+/// Whether an idle decoder should decode one more frame past `anchor` (the
+/// frame the renderer last received): at most `readahead` frames ahead, so the
+/// held hardware surfaces stay within the decoder's pool.
+fn wants_readahead<T>(cache: &BTreeMap<u32, T>, anchor: Option<u32>, readahead: u32) -> bool {
+ anchor.is_some_and(|last| {
+ cache.range(last..).count() <= readahead as usize
+ && cache
+ .keys()
+ .next_back()
+ .is_none_or(|&newest| newest < last.saturating_add(readahead))
+ })
+}
+
fn insert_cached_frame(
cache: &mut BTreeMap<u32, CachedFrame>,
number: u32,
@@ -467,7 +531,11 @@ impl FfmpegDecoder {
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
- None
+ // Opt-in NVDEC for Linux GPU hosts (render farm workers).
+ match std::env::var("CAP_LINUX_HW_DECODE").as_deref() {
+ Ok("cuda") => Some(ffmpeg::sys::AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA),
+ _ => None,
+ }
}
} else {
None
@@ -1085,7 +1153,80 @@ impl FfmpegDecoder {
};
let _ = ready_tx.send(Ok(init_result));
- while let Ok(r) = rx.recv() {
+ // Export read-ahead: with no request pending, keep decoding forward
+ // into the cache so the renderer's next sequential request is served
+ // at once instead of waiting out NVDEC latency (~4.5 ms per 3K frame,
+ // which otherwise sits in every export frame). Bounded by `readahead`
+ // frames past the last request and by the cache's byte budget (hw
+ // surfaces). Off unless CAP_DECODER_READAHEAD is set: editor
+ // playback keeps its on-demand behaviour.
+ let readahead = std::env::var("CAP_DECODER_READAHEAD")
+ .ok()
+ .and_then(|value| value.parse::<u32>().ok())
+ .unwrap_or(0);
+ let mut readahead_exhausted = false;
+ loop {
+ let r = if readahead > 0 {
+ match rx.try_recv() {
+ Ok(message) => message,
+ Err(mpsc::TryRecvError::Disconnected) => break,
+ Err(mpsc::TryRecvError::Empty) => {
+ // Cache hits don't touch `last_active_frame`; the
+ // last frame actually sent is the renderer's position.
+ let anchor = last_sent_frame
+ .borrow()
+ .as_ref()
+ .map(|sent| sent.number)
+ .or(last_active_frame);
+ if !readahead_exhausted && wants_readahead(&cache, anchor, readahead) {
+ if managed_stopped(managed.as_ref()) {
+ return;
+ }
+ match frames.next() {
+ Some(Ok(frame)) => {
+ if let Some(pts) = frame.pts() {
+ let current_frame =
+ pts_to_frame(pts - start_time, time_base, fps);
+ if let Some(prev) = prev_vended
+ && current_frame > prev + 1
+ {
+ record_pts_hole(&mut pts_holes, prev, current_frame);
+ }
+ prev_vended = Some(current_frame);
+ let mut cache_frame = CachedFrame::Raw {
+ frame,
+ number: current_frame,
+ };
+ cache_frame.produce(&mut converter);
+ insert_cached_frame(
+ &mut cache,
+ current_frame,
+ cache_frame,
+ current_frame,
+ last_active_frame,
+ MAX_FRAME_CACHE_BYTES,
+ );
+ } else {
+ prev_vended = None;
+ }
+ }
+ Some(Err(_)) => prev_vended = None,
+ None => readahead_exhausted = true,
+ }
+ continue;
+ }
+ match rx.recv() {
+ Ok(message) => message,
+ Err(_) => break,
+ }
+ }
+ }
+ } else {
+ match rx.recv() {
+ Ok(message) => message,
+ Err(_) => break,
+ }
+ };
if managed_stopped(managed.as_ref()) {
return;
}
@@ -1190,6 +1331,7 @@ impl FfmpegDecoder {
return;
}
frames = this.frames();
+ readahead_exhausted = false;
*last_sent_frame.borrow_mut() = None;
cache.clear();
prev_vended = None;
@@ -1275,6 +1417,7 @@ impl FfmpegDecoder {
return;
}
frames = this.frames();
+ readahead_exhausted = false;
*last_sent_frame.borrow_mut() = None;
cache.clear();
prev_vended = None;
@@ -1524,6 +1667,21 @@ impl FfmpegDecoder {
mod cache_tests {
use super::*;
+ #[test]
+ fn readahead_stops_at_its_window() {
+ let mut cache = BTreeMap::new();
+ assert!(!wants_readahead(&cache, None, 4), "no request served yet");
+ assert!(wants_readahead(&cache, Some(10), 4));
+ for number in 10..14 {
+ cache.insert(number, frame(number, 1));
+ }
+ assert!(wants_readahead(&cache, Some(10), 4));
+ cache.insert(14, frame(14, 1));
+ assert!(!wants_readahead(&cache, Some(10), 4), "window full");
+ assert!(wants_readahead(&cache, Some(12), 4), "renderer moved on");
+ assert!(!wants_readahead(&cache, Some(10), 0), "disabled");
+ }
+
fn frame(number: u32, bytes: usize) -> CachedFrame {
CachedFrame::Processed(ProcessedFrame {
number,
@@ -1533,6 +1691,8 @@ mod cache_tests {
format: PixelFormat::Nv12,
y_stride: 2,
uv_stride: 2,
+ #[cfg(target_os = "linux")]
+ cuda: None,
})
}
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 296747b6c..e6164b221 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -159,6 +159,8 @@ pub struct DecodedFrame {
image_buf_backing: Option<Arc<SendableImageBuf>>,
#[cfg(target_os = "windows")]
d3d11_texture_backing: Option<Arc<SendableD3D11Texture>>,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: Option<Arc<crate::linux_gpu::CudaNv12Frame>>,
}
#[cfg(target_os = "macos")]
@@ -282,6 +284,8 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
@@ -297,9 +301,30 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
+ /// NV12 frame that never left GPU memory (NVDEC on Linux render hosts).
+ #[cfg(target_os = "linux")]
+ pub fn new_nv12_cuda(frame: Arc<crate::linux_gpu::CudaNv12Frame>) -> Self {
+ Self {
+ data: Arc::new(Vec::new()),
+ width: frame.width,
+ height: frame.height,
+ format: PixelFormat::Nv12,
+ y_stride: frame.y_pitch as u32,
+ uv_stride: frame.uv_pitch as u32,
+ cuda_nv12: Some(frame),
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ pub fn cuda_nv12(&self) -> Option<&Arc<crate::linux_gpu::CudaNv12Frame>> {
+ self.cuda_nv12.as_ref()
+ }
+
pub fn new_nv12(data: Vec<u8>, width: u32, height: u32, y_stride: u32, uv_stride: u32) -> Self {
Self {
data: Arc::new(data),
@@ -312,6 +337,8 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
@@ -333,6 +360,8 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
@@ -373,6 +402,8 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
@@ -394,6 +425,8 @@ impl DecodedFrame {
image_buf_backing: None,
#[cfg(target_os = "windows")]
d3d11_texture_backing: None,
+ #[cfg(target_os = "linux")]
+ cuda_nv12: None,
}
}
diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rs
index 1f78273ad..9785cf86c 100644
--- a/crates/rendering/src/frame_pipeline.rs
+++ b/crates/rendering/src/frame_pipeline.rs
@@ -154,6 +154,10 @@ pub struct RgbaToNv12Converter {
surface_ring: Option<Nv12SurfaceRing>,
#[cfg(all(test, target_os = "macos"))]
surface_setup_should_fail: bool,
+ #[cfg(target_os = "linux")]
+ external_ring: Option<crate::linux_gpu::SharedRing>,
+ #[cfg(target_os = "linux")]
+ external_output: bool,
}
/// An NV12 CVPixelBuffer produced by the GPU converter, ready for zero-copy
@@ -500,9 +504,20 @@ impl RgbaToNv12Converter {
surface_ring: None,
#[cfg(all(test, target_os = "macos"))]
surface_setup_should_fail: false,
+ #[cfg(target_os = "linux")]
+ external_ring: None,
+ #[cfg(target_os = "linux")]
+ external_output: false,
}
}
+ /// Keep NV12 output on the GPU: the compute result is copied into a ring
+ /// of CUDA-shared buffers for NVENC instead of being read back.
+ #[cfg(target_os = "linux")]
+ pub fn enable_external_output(&mut self) {
+ self.external_output = true;
+ }
+
/// Emit IOSurface-backed NV12 CVPixelBuffers instead of CPU readbacks:
/// the same compute output is GPU-copied into imported IOSurface planes
/// (byte-identical pixel values, 256-aligned stride for the buffer→texture
@@ -750,6 +765,42 @@ impl RgbaToNv12Converter {
return Ok(true);
}
+ #[cfg(target_os = "linux")]
+ if self.external_output {
+ let nv12_size = self.nv12_size(width, height);
+ if self
+ .external_ring
+ .as_ref()
+ .is_none_or(|ring| ring.size() < nv12_size)
+ {
+ // Frames in flight between renderer and encoder hold slots,
+ // so the ring covers both channels' depth.
+ match crate::linux_gpu::SharedRing::new(device, 16, nv12_size, "NV12 CUDA Output") {
+ Ok(ring) => self.external_ring = Some(ring),
+ Err(error) => {
+ tracing::warn!(%error, "CUDA output unavailable, reading frames back");
+ self.external_output = false;
+ }
+ }
+ }
+ if let Some(ring) = self.external_ring.as_mut().filter(|_| self.external_output) {
+ let slot = ring
+ .acquire(device)
+ .ok_or(RenderingError::BufferMapWaitingFailed)?;
+ encoder.copy_buffer_to_buffer(nv12_buffer, 0, &slot.shared.buffer, 0, nv12_size);
+ self.pending = Some(PendingNv12Output::External(PendingNv12External {
+ slot: Some(slot),
+ completed: None,
+ width,
+ height,
+ y_stride,
+ frame_number,
+ frame_rate,
+ }));
+ return Ok(true);
+ }
+ }
+
let readback_buffer = match self.readback_buffers[readback_idx].as_ref() {
Some(b) => b.clone(),
None => return Ok(false),
@@ -794,6 +845,15 @@ impl RgbaToNv12Converter {
});
pending.completed = Some(completed);
}
+ #[cfg(target_os = "linux")]
+ Some(PendingNv12Output::External(pending)) => {
+ let completed = Arc::new(AtomicBool::new(false));
+ let callback_completed = Arc::clone(&completed);
+ queue.on_submitted_work_done(move || {
+ callback_completed.store(true, Ordering::Release);
+ });
+ pending.completed = Some(completed);
+ }
None => {}
}
let _ = queue;
@@ -808,6 +868,75 @@ pub enum PendingNv12Output {
Readback(PendingNv12Readback),
#[cfg(target_os = "macos")]
Surface(PendingNv12Surface),
+ #[cfg(target_os = "linux")]
+ External(PendingNv12External),
+}
+
+#[cfg(target_os = "linux")]
+pub struct PendingNv12External {
+ slot: Option<Arc<crate::linux_gpu::RingSlot>>,
+ completed: Option<Arc<AtomicBool>>,
+ width: u32,
+ height: u32,
+ y_stride: u32,
+ frame_number: u32,
+ frame_rate: u32,
+}
+
+#[cfg(target_os = "linux")]
+impl Drop for PendingNv12External {
+ fn drop(&mut self) {
+ // Abandoned before hand-off (error or flush): free the slot.
+ if let Some(slot) = self.slot.take() {
+ slot.release();
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+impl PendingNv12External {
+ async fn wait(mut self, device: &wgpu::Device) -> Result<Nv12RenderedFrame, RenderingError> {
+ let Some(completed) = self.completed.clone() else {
+ return Err(RenderingError::BufferMapWaitingFailed);
+ };
+ let started = Instant::now();
+ let mut poll_count = 0u32;
+ while !completed.load(Ordering::Acquire) {
+ if started.elapsed() > gpu_buffer_wait_timeout() {
+ return Err(RenderingError::BufferMapWaitingFailed);
+ }
+ device.poll(wgpu::PollType::Poll)?;
+ poll_count += 1;
+ if poll_count < 10 {
+ tokio::task::yield_now().await;
+ } else if poll_count < 100 {
+ tokio::time::sleep(std::time::Duration::from_micros(100)).await;
+ } else {
+ tokio::time::sleep(std::time::Duration::from_millis(1)).await;
+ }
+ }
+ let slot = self
+ .slot
+ .take()
+ .ok_or(RenderingError::BufferMapWaitingFailed)?;
+ let target_time_ns =
+ (self.frame_number as u64 * 1_000_000_000) / self.frame_rate.max(1) as u64;
+ Ok(Nv12RenderedFrame {
+ data: SharedNv12Buffer::from_vec(Vec::new()),
+ width: self.width,
+ height: self.height,
+ y_stride: self.y_stride,
+ frame_number: self.frame_number,
+ target_time_ns,
+ format: GpuOutputFormat::Nv12,
+ gpu: Some(Arc::new(crate::linux_gpu::GpuNv12Output {
+ slot,
+ y_stride: self.y_stride,
+ uv_offset: u64::from(self.y_stride) * u64::from(self.height),
+ uv_stride: self.y_stride,
+ })),
+ })
+ }
}
impl PendingNv12Output {
@@ -820,6 +949,8 @@ impl PendingNv12Output {
Self::Readback(pending) => pending.wait_with_pool(device, buffer_pool).await,
#[cfg(target_os = "macos")]
Self::Surface(pending) => pending.wait(device).await,
+ #[cfg(target_os = "linux")]
+ Self::External(pending) => pending.wait(device).await,
}
}
}
@@ -873,6 +1004,8 @@ impl PendingNv12Surface {
target_time_ns,
format: GpuOutputFormat::Nv12,
surface: Some(Nv12Surface(self.pixel_buffer)),
+ #[cfg(target_os = "linux")]
+ gpu: None,
})
}
}
@@ -964,6 +1097,8 @@ impl PendingNv12Readback {
format: GpuOutputFormat::Nv12,
#[cfg(target_os = "macos")]
surface: None,
+ #[cfg(target_os = "linux")]
+ gpu: None,
})
}
}
@@ -986,6 +1121,10 @@ pub struct Nv12RenderedFrame {
/// `data` is empty (surface-output mode; macOS export path).
#[cfg(target_os = "macos")]
pub surface: Option<Nv12Surface>,
+ /// When set, the frame lives in a CUDA-shared GPU buffer and `data` is
+ /// empty (Linux GPU render hosts, NVENC input).
+ #[cfg(target_os = "linux")]
+ pub gpu: Option<Arc<crate::linux_gpu::GpuNv12Output>>,
}
impl Nv12RenderedFrame {
@@ -1000,6 +1139,8 @@ impl Nv12RenderedFrame {
format: self.format,
#[cfg(target_os = "macos")]
surface: self.surface.clone(),
+ #[cfg(target_os = "linux")]
+ gpu: self.gpu.clone(),
}
}
@@ -1711,7 +1852,8 @@ impl RenderSession {
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_SRC,
+ | wgpu::TextureUsages::COPY_SRC
+ | wgpu::TextureUsages::COPY_DST,
label: Some("Intermediate Texture"),
view_formats: &[],
})
@@ -1760,7 +1902,8 @@ impl RenderSession {
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_SRC,
+ | wgpu::TextureUsages::COPY_SRC
+ | wgpu::TextureUsages::COPY_DST,
label: Some("Intermediate Texture"),
view_formats: &[],
})
@@ -1973,6 +2116,8 @@ pub async fn finish_encoder_nv12_pooled(
format: GpuOutputFormat::Rgba,
#[cfg(target_os = "macos")]
surface: None,
+ #[cfg(target_os = "linux")]
+ gpu: None,
}))
}
}
diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rs
index 639b4dc27..85b92b35b 100644
--- a/crates/rendering/src/layers/background.rs
+++ b/crates/rendering/src/layers/background.rs
@@ -349,6 +349,9 @@ pub enum Inner {
pub struct BackgroundLayer {
inner: Option<Inner>,
+ /// Bumped whenever `inner` is replaced, so consumers can cache anything
+ /// derived from a static background (e.g. its blurred copy).
+ generation: u64,
image_pipeline: ImageBackgroundPipeline,
color_pipeline: GradientOrColorPipeline,
}
@@ -357,6 +360,7 @@ impl BackgroundLayer {
pub fn new(device: &wgpu::Device) -> Self {
Self {
inner: None,
+ generation: 0,
image_pipeline: ImageBackgroundPipeline::new(device),
color_pipeline: GradientOrColorPipeline::new(device),
}
@@ -377,6 +381,7 @@ impl BackgroundLayer {
layer.prepare(device, queue, config, uniforms);
}
_ => {
+ self.generation += 1;
self.inner = Some(Inner::AnimatedGradient(Box::new(
AnimatedGradientLayer::new(device, config, uniforms),
)));
@@ -398,6 +403,7 @@ impl BackgroundLayer {
let fallback_background = Background::Color([1.0, 1.0, 1.0, 1.0]);
let buffer = GradientOrColorUniforms::from(fallback_background)
.to_buffer(device);
+ self.generation += 1;
self.inner = Some(Inner::ColorOrGradient {
value: ColorOrGradient::Color([1.0, 1.0, 1.0, 1.0]),
bind_group: self.color_pipeline.bind_group(device, &buffer),
@@ -447,6 +453,7 @@ impl BackgroundLayer {
let texture_view =
texture.create_view(&wgpu::TextureViewDescriptor::default());
+ self.generation += 1;
self.inner = Some(Inner::Image {
path,
bind_group: self.image_pipeline.bind_group(
@@ -465,6 +472,7 @@ impl BackgroundLayer {
}) if &color == current_color => {}
_ => {
let buffer = GradientOrColorUniforms::from(background).to_buffer(device);
+ self.generation += 1;
self.inner = Some(Inner::ColorOrGradient {
value: ColorOrGradient::Color(color),
bind_group: self.color_pipeline.bind_group(device, &buffer),
@@ -479,6 +487,7 @@ impl BackgroundLayer {
}) if &gradient == current_gradient => {}
_ => {
let buffer = GradientOrColorUniforms::from(background).to_buffer(device);
+ self.generation += 1;
self.inner = Some(Inner::ColorOrGradient {
value: ColorOrGradient::Gradient(gradient),
bind_group: self.color_pipeline.bind_group(device, &buffer),
@@ -491,6 +500,15 @@ impl BackgroundLayer {
Ok(())
}
+ /// Identifies the current background while it renders the same pixels
+ /// every frame; `None` for animated backgrounds.
+ pub fn static_generation(&self) -> Option<u64> {
+ match &self.inner {
+ Some(Inner::Image { .. } | Inner::ColorOrGradient { .. }) => Some(self.generation),
+ _ => None,
+ }
+ }
+
pub fn render_surface(&mut self, encoder: &mut wgpu::CommandEncoder) {
if let Some(Inner::AnimatedGradient(layer)) = &mut self.inner {
layer.render_surface(encoder);
diff --git a/crates/rendering/src/layers/blur.rs b/crates/rendering/src/layers/blur.rs
index 4f9ea8afd..d3266a0c2 100644
--- a/crates/rendering/src/layers/blur.rs
+++ b/crates/rendering/src/layers/blur.rs
@@ -10,6 +10,19 @@ pub struct BlurLayer {
uniforms_buffer_v: wgpu::Buffer,
pipeline: BlurPipeline,
cached_uniforms: Option<BlurUniforms>,
+ result: Option<(BlurResultKey, wgpu::Texture)>,
+}
+
+/// Everything the blurred background depends on. While it matches, the
+/// previous frame's blurred background is still exact and two full-frame
+/// gaussian passes collapse into one texture copy. On a software rasterizer
+/// those passes are most of the frame's cost.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct BlurResultKey {
+ pub background_generation: u64,
+ pub blur_amount_bits: u64,
+ pub output_size: (u32, u32),
+ pub texture_size: (u32, u32),
}
impl BlurLayer {
@@ -39,9 +52,46 @@ impl BlurLayer {
uniforms_buffer_v: make_buffer(1.0),
pipeline: BlurPipeline::new(device),
cached_uniforms: None,
+ result: None,
}
}
+ pub fn cached_result(&self, key: BlurResultKey) -> Option<&wgpu::Texture> {
+ self.result
+ .as_ref()
+ .filter(|(cached, _)| *cached == key)
+ .map(|(_, texture)| texture)
+ }
+
+ pub fn store_result(
+ &mut self,
+ device: &wgpu::Device,
+ encoder: &mut wgpu::CommandEncoder,
+ key: BlurResultKey,
+ source: &wgpu::Texture,
+ ) {
+ let size = source.size();
+ let reusable = self
+ .result
+ .take()
+ .map(|(_, texture)| texture)
+ .filter(|texture| texture.size() == size && texture.format() == source.format());
+ let texture = reusable.unwrap_or_else(|| {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Blurred Background Cache"),
+ size,
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: source.format(),
+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ })
+ });
+ encoder.copy_texture_to_texture(source.as_image_copy(), texture.as_image_copy(), size);
+ self.result = Some((key, texture));
+ }
+
pub fn prepare(&mut self, queue: &wgpu::Queue, uniforms: &ProjectUniforms) {
self.blur_amount = uniforms.project.background.blur;
if self.blur_amount <= 0.0 {
diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs
index 06163a9f9..2fcf4df67 100644
--- a/crates/rendering/src/layers/camera.rs
+++ b/crates/rendering/src/layers/camera.rs
@@ -229,7 +229,16 @@ impl CameraLayer {
.is_ok()
})
.unwrap_or(false);
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "linux")]
+ let iosurface_converted = camera_frame.cuda_nv12().is_some_and(|cuda| {
+ self.yuv_converter
+ .convert_nv12_cuda(device, queue, cuda)
+ .inspect_err(|error| {
+ tracing::warn!(%error, "CUDA camera frame conversion failed")
+ })
+ .is_ok()
+ });
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
let iosurface_converted = false;
if iosurface_converted && self.yuv_converter.output_texture().is_some() {
@@ -460,7 +469,18 @@ impl CameraLayer {
.is_ok()
})
.unwrap_or(false);
- #[cfg(not(target_os = "macos"))]
+ // Submitted on its own ahead of `encoder`, so queue order
+ // still has the conversion land before the copy below.
+ #[cfg(target_os = "linux")]
+ let iosurface_converted = camera_frame.cuda_nv12().is_some_and(|cuda| {
+ self.yuv_converter
+ .convert_nv12_cuda(device, queue, cuda)
+ .inspect_err(|error| {
+ tracing::warn!(%error, "CUDA camera frame conversion failed")
+ })
+ .is_ok()
+ });
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
let iosurface_converted = false;
if iosurface_converted && self.yuv_converter.output_texture().is_some() {
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index 595585eeb..3a8c53a91 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -394,53 +394,81 @@ impl DisplayLayer {
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
- if let (Some(y_data), Some(uv_data)) =
- (screen_frame.y_plane(), screen_frame.uv_plane())
{
- let y_stride = screen_frame.y_stride();
- let uv_stride = screen_frame.uv_stride();
-
- let convert_result = if self.prefer_cpu_conversion {
- self.yuv_converter.convert_nv12_cpu(
- device,
- queue,
- y_data,
- uv_data,
- source_size.x,
- source_size.y,
- y_stride,
- uv_stride,
- )
- } else {
- self.yuv_converter.convert_nv12(
- device,
- queue,
- y_data,
- uv_data,
- source_size.x,
- source_size.y,
- y_stride,
- uv_stride,
- )
- };
-
- match convert_result {
- Ok(_) => {
- if self.yuv_converter.output_texture().is_some() {
+ #[cfg(target_os = "linux")]
+ let cuda_result = screen_frame.cuda_nv12().map(|cuda| {
+ let converted = self
+ .yuv_converter
+ .convert_nv12_cuda(device, queue, cuda)
+ .map(|_| ());
+ match converted {
+ Ok(()) if self.yuv_converter.output_texture().is_some() => {
self.pending_copy = Some(PendingTextureCopy {
width: source_size.x,
height: source_size.y,
dst_texture_index: next_texture,
});
true
- } else {
+ }
+ Ok(()) => false,
+ Err(error) => {
+ tracing::warn!(%error, "CUDA frame conversion failed");
false
}
}
- Err(_) => false,
+ });
+ #[cfg(not(target_os = "linux"))]
+ let cuda_result: Option<bool> = None;
+ if let Some(converted) = cuda_result {
+ converted
+ } else if let (Some(y_data), Some(uv_data)) =
+ (screen_frame.y_plane(), screen_frame.uv_plane())
+ {
+ let y_stride = screen_frame.y_stride();
+ let uv_stride = screen_frame.uv_stride();
+
+ let convert_result = if self.prefer_cpu_conversion {
+ self.yuv_converter.convert_nv12_cpu(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ source_size.x,
+ source_size.y,
+ y_stride,
+ uv_stride,
+ )
+ } else {
+ self.yuv_converter.convert_nv12(
+ device,
+ queue,
+ y_data,
+ uv_data,
+ source_size.x,
+ source_size.y,
+ y_stride,
+ uv_stride,
+ )
+ };
+
+ match convert_result {
+ Ok(_) => {
+ if self.yuv_converter.output_texture().is_some() {
+ self.pending_copy = Some(PendingTextureCopy {
+ width: source_size.x,
+ height: source_size.y,
+ dst_texture_index: next_texture,
+ });
+ true
+ } else {
+ false
+ }
+ }
+ Err(_) => false,
+ }
+ } else {
+ false
}
- } else {
- false
}
}
PixelFormat::Yuv420p => {
@@ -738,7 +766,18 @@ impl DisplayLayer {
.is_ok()
})
.unwrap_or(false);
- #[cfg(not(target_os = "macos"))]
+ // Submitted ahead of `encoder`, so the conversion
+ // lands before the pending copy recorded below.
+ #[cfg(target_os = "linux")]
+ let iosurface_converted = screen_frame.cuda_nv12().is_some_and(|cuda| {
+ self.yuv_converter
+ .convert_nv12_cuda(device, queue, cuda)
+ .inspect_err(
+ |error| tracing::warn!(%error, "CUDA frame conversion failed"),
+ )
+ .is_ok()
+ });
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
let iosurface_converted = false;
if iosurface_converted && self.yuv_converter.output_texture().is_some() {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index a3e2c0f9a..f16fd4fc8 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -46,6 +46,8 @@ mod frame_windows;
#[cfg(target_os = "macos")]
pub mod iosurface_texture;
mod layers;
+#[cfg(target_os = "linux")]
+pub mod linux_gpu;
mod managed_segment;
mod mask;
pub mod notch_shape;
@@ -1075,6 +1077,95 @@ pub fn zero_copy_export_disabled() -> bool {
})
}
+/// Cumulative wall time per stage of the NV12 export loop (µs), for finding
+/// which stage a render slot waits on. Off unless CAP_RENDER_LOOP_STATS=1;
+/// `take` reads and resets.
+pub mod loop_stats {
+ use std::sync::{
+ OnceLock,
+ atomic::{AtomicU64, Ordering},
+ };
+
+ pub static DECODE: AtomicU64 = AtomicU64::new(0);
+ pub static RENDER: AtomicU64 = AtomicU64::new(0);
+ pub static PREFETCH: AtomicU64 = AtomicU64::new(0);
+ pub static JOIN: AtomicU64 = AtomicU64::new(0);
+ pub static SEND: AtomicU64 = AtomicU64::new(0);
+ pub static FRAMES: AtomicU64 = AtomicU64::new(0);
+
+ pub fn enabled() -> bool {
+ static ENABLED: OnceLock<bool> = OnceLock::new();
+ *ENABLED.get_or_init(|| std::env::var("CAP_RENDER_LOOP_STATS").as_deref() == Ok("1"))
+ }
+
+ pub fn add(counter: &AtomicU64, elapsed: std::time::Duration) {
+ if enabled() {
+ counter.fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
+ }
+ }
+
+ /// [decode wait, render, next-frame decode, render+decode join, send wait, frames]
+ pub fn take() -> [u64; 6] {
+ [&DECODE, &RENDER, &PREFETCH, &JOIN, &SEND, &FRAMES]
+ .map(|counter| counter.swap(0, Ordering::Relaxed))
+ }
+}
+
+/// Layer pipelines take ~0.25-0.5 s to build per render. A process that
+/// renders many ranges of the same project (a render-farm engine) can set a
+/// key naming that project; successful renders then hand their layers to the
+/// next render with the same key on the same device. Layers cache per-project
+/// assets (cursor images, backgrounds) under ids that are only unique within
+/// a recording, so they are never shared across keys.
+static LAYERS_REUSE_KEY: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
+static LAYERS_POOL: std::sync::Mutex<Vec<(wgpu::Device, String, RendererLayers)>> =
+ std::sync::Mutex::new(Vec::new());
+
+pub fn set_layers_reuse_key(key: Option<String>) {
+ if let Ok(mut current) = LAYERS_REUSE_KEY.lock() {
+ *current = key;
+ }
+}
+
+/// Key of never-used layers: they hold no project state, so any project
+/// may take them.
+const SPARE_LAYERS: &str = "\0spare";
+
+fn take_pooled_layers(device: &wgpu::Device, key: &str) -> Option<RendererLayers> {
+ let mut pool = LAYERS_POOL.lock().ok()?;
+ // Layers for other projects will not be asked for again.
+ pool.retain(|(_, pooled_key, _)| pooled_key == key || pooled_key == SPARE_LAYERS);
+ let index = pool
+ .iter()
+ .position(|(owner, pooled_key, _)| owner == device && pooled_key == key)
+ .or_else(|| pool.iter().position(|(owner, _, _)| owner == device))?;
+ Some(pool.swap_remove(index).2)
+}
+
+/// Builds a fresh set of layers for the next project's first render, off
+/// its critical path (an idle engine calls this between tasks).
+pub fn prebuild_spare_layers(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ is_software_adapter: bool,
+) {
+ let has_spare = LAYERS_POOL.lock().is_ok_and(|pool| {
+ pool.iter()
+ .any(|(owner, key, _)| owner == device && key == SPARE_LAYERS)
+ });
+ if has_spare {
+ return;
+ }
+ let layers = RendererLayers::new_with_options(device, queue, is_software_adapter);
+ return_pooled_layers(device.clone(), SPARE_LAYERS.to_string(), layers);
+}
+
+fn return_pooled_layers(device: wgpu::Device, key: String, layers: RendererLayers) {
+ if let Ok(mut pool) = LAYERS_POOL.lock() {
+ pool.push((device, key, layers));
+ }
+}
+
#[allow(clippy::too_many_arguments)]
pub async fn render_video_to_channel_nv12(
constants: &RenderVideoConstants,
@@ -1169,11 +1260,17 @@ pub async fn render_video_to_channel_nv12(
frame_renderer.enable_nv12_surface_output();
}
- let mut layers = RendererLayers::new_with_options(
- &constants.device,
- &constants.queue,
- constants.is_software_adapter,
- );
+ let layers_reuse_key = LAYERS_REUSE_KEY.lock().ok().and_then(|key| key.clone());
+ let mut layers = layers_reuse_key
+ .as_deref()
+ .and_then(|key| take_pooled_layers(&constants.device, key))
+ .unwrap_or_else(|| {
+ RendererLayers::new_with_options(
+ &constants.device,
+ &constants.queue,
+ constants.is_software_adapter,
+ )
+ });
if let Some(first_segment) = render_segments.first() {
let (screen_w, screen_h) = first_segment.decoders.screen_video_dimensions();
@@ -1296,6 +1393,7 @@ pub async fn render_video_to_channel_nv12(
(incoming_decode.await, None)
};
let this_decode_ms = decode_wall_start.elapsed().as_millis() as u64;
+ loop_stats::add(&loop_stats::DECODE, decode_wall_start.elapsed());
if let Some(segment_frames) = segment_frames {
consecutive_failures = 0;
@@ -1429,7 +1527,7 @@ pub async fn render_video_to_channel_nv12(
)
}
} else if let Some(prefetch) = prefetch_future {
- if record_first_frame_nv12_phases {
+ if record_first_frame_nv12_phases || loop_stats::enabled() {
let join_wall_start = Instant::now();
let render_fut = async {
let t0 = Instant::now();
@@ -1451,6 +1549,9 @@ pub async fn render_video_to_channel_nv12(
};
let ((render_elapsed, render), (prefetch_elapsed, decoded)) =
tokio::join!(render_fut, prefetch_fut);
+ loop_stats::add(&loop_stats::RENDER, render_elapsed);
+ loop_stats::add(&loop_stats::PREFETCH, prefetch_elapsed);
+ loop_stats::add(&loop_stats::JOIN, join_wall_start.elapsed());
if let Some((next_frame_number, next_seg_time, next_clip_index)) =
next_prefetch_meta
{
@@ -1484,7 +1585,7 @@ pub async fn render_video_to_channel_nv12(
(render, None, None, None)
}
- } else if record_first_frame_nv12_phases {
+ } else if record_first_frame_nv12_phases || loop_stats::enabled() {
let render_start = Instant::now();
let render = frame_renderer
.render_nv12(
@@ -1495,6 +1596,8 @@ pub async fn render_video_to_channel_nv12(
&mut layers,
)
.await;
+ loop_stats::add(&loop_stats::RENDER, render_start.elapsed());
+ loop_stats::add(&loop_stats::JOIN, render_start.elapsed());
(
render,
Some(render_start.elapsed().as_millis() as u64),
@@ -1554,7 +1657,12 @@ pub async fn render_video_to_channel_nv12(
record_first_frame_nv12_phases = false;
}
last_successful_frame = Some(frame.clone_metadata_with_data());
+ let send_started = Instant::now();
sender.send((frame, current_frame_number)).await?;
+ loop_stats::add(&loop_stats::SEND, send_started.elapsed());
+ if loop_stats::enabled() {
+ loop_stats::FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
channel_frames_sent += 1;
if stop_after_frames_sent.is_some_and(|m| channel_frames_sent >= m) {
stopped_after_frame_limit = true;
@@ -1685,6 +1793,11 @@ pub async fn render_video_to_channel_nv12(
"NV12 render complete"
);
+ // Only after a clean run: a failed render may leave layer state behind.
+ if let Some(key) = layers_reuse_key {
+ return_pooled_layers(constants.device.clone(), key, layers);
+ }
+
Ok(())
}
@@ -2011,6 +2124,111 @@ pub struct RenderVideoConstants {
frozen_recorded_cursors: Option<FrozenRecordedCursorAssets>,
}
+/// Instance, adapter and device the way every renderer creates them. A
+/// long-lived process can make one up front and hand it to
+/// [`RenderVideoConstants::new_with_device`].
+#[cfg(not(target_arch = "wasm32"))]
+pub async fn create_shared_device() -> Result<SharedWgpuDevice, RenderingError> {
+ let instance_phase = readiness::Phase::start("wgpu.instance");
+ let instance = create_wgpu_instance().await;
+ instance_phase.finish("returned");
+
+ let force_software_adapter = force_software_wgpu_adapter();
+ if force_software_adapter {
+ tracing::warn!("Forcing software WGPU adapter");
+ }
+
+ let adapter_phase = readiness::Phase::start("wgpu.adapter");
+ let hardware_adapter = if force_software_adapter {
+ None
+ } else {
+ instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ })
+ .await
+ .ok()
+ };
+
+ let (adapter, is_software_adapter) = if let Some(adapter) = hardware_adapter {
+ let adapter_info = adapter.get_info();
+ let is_software = is_software_wgpu_adapter(&adapter_info);
+
+ if is_software {
+ tracing::warn!(
+ adapter_name = adapter_info.name,
+ adapter_backend = ?adapter_info.backend,
+ adapter_device_type = ?adapter_info.device_type,
+ "Hardware adapter behaves like a software renderer"
+ );
+ } else {
+ tracing::info!(
+ adapter_name = adapter_info.name,
+ adapter_backend = ?adapter_info.backend,
+ adapter_device_type = ?adapter_info.device_type,
+ "Using hardware GPU adapter"
+ );
+ }
+
+ (adapter, is_software)
+ } else {
+ tracing::warn!("No hardware GPU adapter found, attempting software fallback");
+ let software_adapter = instance
+ .request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::LowPower,
+ force_fallback_adapter: true,
+ compatible_surface: None,
+ })
+ .await
+ .map_err(|_| RenderingError::NoAdapter)?;
+
+ let adapter_info = software_adapter.get_info();
+ tracing::info!(
+ adapter_name = adapter_info.name,
+ adapter_backend = ?adapter_info.backend,
+ adapter_device_type = ?adapter_info.device_type,
+ "Using software adapter (CPU rendering - performance may be reduced)"
+ );
+ (software_adapter, true)
+ };
+
+ adapter_phase.finish(if is_software_adapter {
+ "software"
+ } else {
+ "hardware"
+ });
+
+ let mut required_features = wgpu::Features::empty();
+ if adapter.features().contains(wgpu::Features::PIPELINE_CACHE) {
+ required_features |= wgpu::Features::PIPELINE_CACHE;
+ }
+ if adapter
+ .features()
+ .contains(wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)
+ {
+ required_features |= wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES;
+ }
+
+ let device_descriptor = wgpu::DeviceDescriptor {
+ label: Some("cap-rendering-device"),
+ required_features,
+ ..Default::default()
+ };
+
+ let device_phase = readiness::Phase::start("wgpu.device");
+ let (device, queue) = adapter.request_device(&device_descriptor).await?;
+ device_phase.finish("returned");
+ Ok(SharedWgpuDevice {
+ instance,
+ adapter,
+ device,
+ queue,
+ is_software_adapter,
+ })
+}
+
pub struct SharedWgpuDevice {
pub instance: wgpu::Instance,
pub adapter: wgpu::Adapter,
@@ -2130,97 +2348,15 @@ impl RenderVideoConstants {
meta: StudioRecordingMeta,
) -> Result<Self, RenderingError> {
let constants_phase = readiness::Phase::start("constants.new");
- let instance_phase = readiness::Phase::start("wgpu.instance");
- let instance = create_wgpu_instance().await;
- instance_phase.finish("returned");
-
- let force_software_adapter = force_software_wgpu_adapter();
- if force_software_adapter {
- tracing::warn!("Forcing software WGPU adapter");
- }
-
- let adapter_phase = readiness::Phase::start("wgpu.adapter");
- let hardware_adapter = if force_software_adapter {
- None
- } else {
- instance
- .request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::HighPerformance,
- force_fallback_adapter: false,
- compatible_surface: None,
- })
- .await
- .ok()
- };
-
- let (adapter, is_software_adapter, adapter_name) = if let Some(adapter) = hardware_adapter {
- let adapter_info = adapter.get_info();
- let is_software = is_software_wgpu_adapter(&adapter_info);
-
- if is_software {
- tracing::warn!(
- adapter_name = adapter_info.name,
- adapter_backend = ?adapter_info.backend,
- adapter_device_type = ?adapter_info.device_type,
- "Hardware adapter behaves like a software renderer"
- );
- } else {
- tracing::info!(
- adapter_name = adapter_info.name,
- adapter_backend = ?adapter_info.backend,
- adapter_device_type = ?adapter_info.device_type,
- "Using hardware GPU adapter"
- );
- }
-
- (adapter, is_software, adapter_info.name)
- } else {
- tracing::warn!("No hardware GPU adapter found, attempting software fallback");
- let software_adapter = instance
- .request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::LowPower,
- force_fallback_adapter: true,
- compatible_surface: None,
- })
- .await
- .map_err(|_| RenderingError::NoAdapter)?;
-
- let adapter_info = software_adapter.get_info();
- tracing::info!(
- adapter_name = adapter_info.name,
- adapter_backend = ?adapter_info.backend,
- adapter_device_type = ?adapter_info.device_type,
- "Using software adapter (CPU rendering - performance may be reduced)"
- );
- (software_adapter, true, adapter_info.name)
- };
-
- adapter_phase.finish(if is_software_adapter {
- "software"
- } else {
- "hardware"
- });
-
- let mut required_features = wgpu::Features::empty();
- if adapter.features().contains(wgpu::Features::PIPELINE_CACHE) {
- required_features |= wgpu::Features::PIPELINE_CACHE;
- }
- if adapter
- .features()
- .contains(wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES)
- {
- required_features |= wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES;
- }
-
- let device_descriptor = wgpu::DeviceDescriptor {
- label: Some("cap-rendering-device"),
- required_features,
- ..Default::default()
- };
-
- let device_phase = readiness::Phase::start("wgpu.device");
- let (device, queue) = adapter.request_device(&device_descriptor).await?;
- device_phase.finish("returned");
+ let shared = create_shared_device().await?;
+ let adapter_name = shared.adapter.get_info().name;
+ let SharedWgpuDevice {
+ instance,
+ adapter,
+ device,
+ queue,
+ is_software_adapter,
+ } = shared;
let background_textures = Arc::new(BackgroundTextureCache::default());
@@ -5979,7 +6115,15 @@ impl<'a> FrameRenderer<'a> {
}
converter
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "linux")]
+ {
+ let mut converter = frame_pipeline::RgbaToNv12Converter::new(&self.constants.device);
+ if crate::linux_gpu::enabled() && !self.constants.is_software_adapter {
+ converter.enable_external_output();
+ }
+ converter
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
frame_pipeline::RgbaToNv12Converter::new(&self.constants.device)
}
@@ -6665,6 +6809,8 @@ impl<'a> FrameRenderer<'a> {
format: frame_pipeline::GpuOutputFormat::Nv12,
#[cfg(target_os = "macos")]
surface: None,
+ #[cfg(target_os = "linux")]
+ gpu: None,
}
}
@@ -7390,26 +7536,54 @@ impl RendererLayers {
self.camera_only.copy_to_texture(encoder);
self.background.render_surface(encoder);
- {
- let mut pass = render_pass!(
- session.current_texture_view(),
- wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ let blur_key = (self.background_blur.blur_amount > 0.0)
+ .then(|| self.background.static_generation())
+ .flatten()
+ .map(|background_generation| {
+ let size = session.current_texture().size();
+ layers::BlurResultKey {
+ background_generation,
+ blur_amount_bits: self.background_blur.blur_amount.to_bits(),
+ output_size: uniforms.output_size,
+ texture_size: (size.width, size.height),
+ }
+ });
+ if let Some(cached) = blur_key.and_then(|key| self.background_blur.cached_result(key)) {
+ encoder.copy_texture_to_texture(
+ cached.as_image_copy(),
+ session.current_texture().as_image_copy(),
+ cached.size(),
);
- self.background.render(&mut pass);
- }
-
- // Separable gaussian: horizontal into the spare texture, vertical back
- // into the current one, so the result ends up where it started and no
- // swap is needed.
- if self.background_blur.blur_amount > 0.0 {
+ } else {
{
- let mut pass = render_pass!(session.other_texture_view(), wgpu::LoadOp::Load);
+ let mut pass = render_pass!(
+ session.current_texture_view(),
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
+ );
+ self.background.render(&mut pass);
+ }
+
+ // Separable gaussian: horizontal into the spare texture, vertical
+ // back into the current one, so the result ends up where it
+ // started and no swap is needed.
+ if self.background_blur.blur_amount > 0.0 {
+ {
+ let mut pass = render_pass!(session.other_texture_view(), wgpu::LoadOp::Load);
+ self.background_blur.render_h(
+ &mut pass,
+ device,
+ session.current_texture_view(),
+ );
+ }
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
self.background_blur
- .render_h(&mut pass, device, session.current_texture_view());
+ .render_v(&mut pass, device, session.other_texture_view());
+ }
+
+ if let Some(key) = blur_key {
+ self.background_blur
+ .store_result(device, encoder, key, session.current_texture());
}
- let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
- self.background_blur
- .render_v(&mut pass, device, session.other_texture_view());
}
// Runs before content layers so the screen grade covers the whole
diff --git a/crates/rendering/src/linux_gpu.rs b/crates/rendering/src/linux_gpu.rs
new file mode 100644
index 000000000..f0bf2fecd
--- /dev/null
+++ b/crates/rendering/src/linux_gpu.rs
@@ -0,0 +1,548 @@
+//! GPU-resident frames on Linux + NVIDIA (render farm workers).
+//!
+//! With `CAP_LINUX_GPU_FRAMES=1` decoded frames stay in CUDA memory (NVDEC),
+//! reach the compositor through Vulkan buffers that CUDA imports, and the
+//! NV12 output goes back to CUDA for NVENC the same way. Every hop is a
+//! device-to-device copy: no frame crosses PCIe to the CPU. CUDA is loaded at
+//! runtime, so builds without an NVIDIA driver are unaffected.
+
+use ash::vk;
+use std::{
+ ffi::c_void,
+ sync::{
+ Arc, Mutex, OnceLock,
+ atomic::{AtomicBool, Ordering},
+ },
+};
+
+pub fn enabled() -> bool {
+ static ENABLED: OnceLock<bool> = OnceLock::new();
+ *ENABLED.get_or_init(|| std::env::var("CAP_LINUX_GPU_FRAMES").as_deref() == Ok("1"))
+}
+
+type CuResult = i32;
+pub type CuDevicePtr = u64;
+type CuContext = *mut c_void;
+type CuStream = *mut c_void;
+type CuExternalMemory = *mut c_void;
+
+#[repr(C)]
+struct CudaMemcpy2d {
+ src_x_in_bytes: usize,
+ src_y: usize,
+ src_memory_type: u32,
+ src_host: *const c_void,
+ src_device: CuDevicePtr,
+ src_array: *mut c_void,
+ src_pitch: usize,
+ dst_x_in_bytes: usize,
+ dst_y: usize,
+ dst_memory_type: u32,
+ dst_host: *mut c_void,
+ dst_device: CuDevicePtr,
+ dst_array: *mut c_void,
+ dst_pitch: usize,
+ width_in_bytes: usize,
+ height: usize,
+}
+
+#[repr(C)]
+struct ExternalMemoryHandleDesc {
+ kind: u32,
+ _pad: u32,
+ fd: i32,
+ _union_rest: [u8; 12],
+ size: u64,
+ flags: u32,
+ reserved: [u32; 16],
+}
+
+#[repr(C)]
+struct ExternalMemoryBufferDesc {
+ offset: u64,
+ size: u64,
+ flags: u32,
+ reserved: [u32; 16],
+}
+
+const CU_MEMORYTYPE_DEVICE: u32 = 2;
+const CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD: u32 = 1;
+const CUDA_EXTERNAL_MEMORY_DEDICATED: u32 = 1;
+
+struct Cuda {
+ _library: libloading::Library,
+ context: CuContext,
+ ctx_push: unsafe extern "C" fn(CuContext) -> CuResult,
+ ctx_pop: unsafe extern "C" fn(*mut CuContext) -> CuResult,
+ memcpy_2d_async: unsafe extern "C" fn(*const CudaMemcpy2d, CuStream) -> CuResult,
+ stream_create: unsafe extern "C" fn(*mut CuStream, u32) -> CuResult,
+ stream_synchronize: unsafe extern "C" fn(CuStream) -> CuResult,
+ mem_get_info: unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult,
+ import_external_memory:
+ unsafe extern "C" fn(*mut CuExternalMemory, *const ExternalMemoryHandleDesc) -> CuResult,
+ external_memory_mapped_buffer: unsafe extern "C" fn(
+ *mut CuDevicePtr,
+ CuExternalMemory,
+ *const ExternalMemoryBufferDesc,
+ ) -> CuResult,
+}
+
+unsafe impl Send for Cuda {}
+unsafe impl Sync for Cuda {}
+
+fn check(result: CuResult, what: &str) -> Result<(), String> {
+ if result == 0 {
+ Ok(())
+ } else {
+ Err(format!("{what} failed with CUDA error {result}"))
+ }
+}
+
+impl Cuda {
+ fn load() -> Result<Self, String> {
+ unsafe {
+ let library = libloading::Library::new("libcuda.so.1")
+ .map_err(|error| format!("libcuda: {error}"))?;
+ macro_rules! symbol {
+ ($name:literal) => {
+ *library
+ .get($name)
+ .map_err(|error| format!("{}: {error}", String::from_utf8_lossy($name)))?
+ };
+ }
+ let init: unsafe extern "C" fn(u32) -> CuResult = symbol!(b"cuInit\0");
+ let device_get: unsafe extern "C" fn(*mut i32, i32) -> CuResult =
+ symbol!(b"cuDeviceGet\0");
+ let primary_retain: unsafe extern "C" fn(*mut CuContext, i32) -> CuResult =
+ symbol!(b"cuDevicePrimaryCtxRetain\0");
+ check(init(0), "cuInit")?;
+ let mut device = 0;
+ check(device_get(&mut device, 0), "cuDeviceGet")?;
+ // ffmpeg's CUDA hwcontext (primary_ctx=1) insists on blocking-sync
+ // scheduling and refuses to attach to an active primary context
+ // with other flags, so activate it the way ffmpeg would.
+ let set_flags: unsafe extern "C" fn(i32, u32) -> CuResult =
+ symbol!(b"cuDevicePrimaryCtxSetFlags_v2\0");
+ const CU_CTX_SCHED_BLOCKING_SYNC: u32 = 0x04;
+ let _ = set_flags(device, CU_CTX_SCHED_BLOCKING_SYNC);
+ let mut context = std::ptr::null_mut();
+ // The primary context is shared with ffmpeg's CUDA hwaccel and
+ // NVENC (primary_ctx=1), so device pointers are valid everywhere.
+ check(
+ primary_retain(&mut context, device),
+ "cuDevicePrimaryCtxRetain",
+ )?;
+ Ok(Self {
+ ctx_push: symbol!(b"cuCtxPushCurrent_v2\0"),
+ ctx_pop: symbol!(b"cuCtxPopCurrent_v2\0"),
+ memcpy_2d_async: symbol!(b"cuMemcpy2DAsync_v2\0"),
+ stream_create: symbol!(b"cuStreamCreate\0"),
+ stream_synchronize: symbol!(b"cuStreamSynchronize\0"),
+ mem_get_info: symbol!(b"cuMemGetInfo_v2\0"),
+ import_external_memory: symbol!(b"cuImportExternalMemory\0"),
+ external_memory_mapped_buffer: symbol!(b"cuExternalMemoryGetMappedBuffer\0"),
+ context,
+ _library: library,
+ })
+ }
+ }
+
+ fn with_context<T>(&self, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
+ unsafe {
+ check((self.ctx_push)(self.context), "cuCtxPushCurrent")?;
+ let result = f();
+ let mut popped = std::ptr::null_mut();
+ (self.ctx_pop)(&mut popped);
+ result
+ }
+ }
+}
+
+fn cuda() -> Result<&'static Cuda, String> {
+ static CUDA: OnceLock<Result<Cuda, String>> = OnceLock::new();
+ CUDA.get_or_init(Cuda::load).as_ref().map_err(Clone::clone)
+}
+
+/// Device-to-device copy of a pitched plane (synchronous).
+pub fn copy_plane(
+ src: CuDevicePtr,
+ src_pitch: usize,
+ dst: CuDevicePtr,
+ dst_pitch: usize,
+ width_bytes: usize,
+ rows: usize,
+) -> Result<(), String> {
+ let cuda = cuda()?;
+ let copy = CudaMemcpy2d {
+ src_x_in_bytes: 0,
+ src_y: 0,
+ src_memory_type: CU_MEMORYTYPE_DEVICE,
+ src_host: std::ptr::null(),
+ src_device: src,
+ src_array: std::ptr::null_mut(),
+ src_pitch,
+ dst_x_in_bytes: 0,
+ dst_y: 0,
+ dst_memory_type: CU_MEMORYTYPE_DEVICE,
+ dst_host: std::ptr::null_mut(),
+ dst_device: dst,
+ dst_array: std::ptr::null_mut(),
+ dst_pitch,
+ width_in_bytes: width_bytes,
+ height: rows,
+ };
+ cuda.with_context(|| unsafe {
+ check(
+ (cuda.memcpy_2d_async)(&copy, thread_stream(cuda)?),
+ "cuMemcpy2DAsync",
+ )
+ })
+}
+
+/// One blocking stream per thread: it orders after NVDEC's writes on the
+/// legacy stream, and waiting on it waits only for this thread's copies.
+fn thread_stream(cuda: &Cuda) -> Result<CuStream, String> {
+ thread_local! {
+ static STREAM: std::cell::Cell<CuStream> = const { std::cell::Cell::new(std::ptr::null_mut()) };
+ }
+ STREAM.with(|slot| {
+ if slot.get().is_null() {
+ let mut stream = std::ptr::null_mut();
+ check(
+ unsafe { (cuda.stream_create)(&mut stream, 0) },
+ "cuStreamCreate",
+ )?;
+ slot.set(stream);
+ }
+ Ok(slot.get())
+ })
+}
+
+/// Retains the primary context with the scheduling flags ffmpeg wants, before
+/// any decoder or encoder exists. Otherwise two ffmpeg device inits can race
+/// on cuDevicePrimaryCtxSetFlags (CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE) and one
+/// decoder silently falls back to software decode.
+pub fn init() -> Result<(), String> {
+ cuda().map(|_| ())
+}
+
+/// Waits for this thread's queued copies. Device-to-device copies never
+/// block the host, so without this Vulkan (or NVENC) can read a shared
+/// buffer before the copy lands, and a ring slot can be recycled mid-copy:
+/// green (zeroed) or stale frames.
+pub fn synchronize() -> Result<(), String> {
+ let cuda = cuda()?;
+ cuda.with_context(|| unsafe {
+ check(
+ (cuda.stream_synchronize)(thread_stream(cuda)?),
+ "cuStreamSynchronize",
+ )
+ })
+}
+
+/// A device-local Vulkan buffer that wgpu can copy to/from and CUDA can
+/// address directly.
+pub struct SharedBuffer {
+ pub buffer: wgpu::Buffer,
+ pub size: u64,
+ pub cuda_ptr: CuDevicePtr,
+ _memory: vk::DeviceMemory,
+}
+
+impl SharedBuffer {
+ pub fn new(device: &wgpu::Device, size: u64, label: &str) -> Result<Self, String> {
+ let cuda = cuda()?;
+ let size = size.next_multiple_of(4096);
+ let (raw_buffer, memory, allocation_size, fd) = unsafe {
+ device.as_hal::<wgpu_hal::api::Vulkan, _, _>(|hal| {
+ let hal = hal.ok_or("wgpu device is not Vulkan")?;
+ let raw = hal.raw_device();
+ let instance = hal.shared_instance().raw_instance();
+ let mut external_info = vk::ExternalMemoryBufferCreateInfo::default()
+ .handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
+ let buffer_info = vk::BufferCreateInfo::default()
+ .size(size)
+ .usage(
+ vk::BufferUsageFlags::TRANSFER_SRC
+ | vk::BufferUsageFlags::TRANSFER_DST
+ | vk::BufferUsageFlags::STORAGE_BUFFER,
+ )
+ .sharing_mode(vk::SharingMode::EXCLUSIVE)
+ .push_next(&mut external_info);
+ let buffer = raw
+ .create_buffer(&buffer_info, None)
+ .map_err(|error| format!("vkCreateBuffer: {error}"))?;
+ let requirements = raw.get_buffer_memory_requirements(buffer);
+ let properties =
+ instance.get_physical_device_memory_properties(hal.raw_physical_device());
+ let memory_type = (0..properties.memory_type_count)
+ .find(|&index| {
+ requirements.memory_type_bits & (1 << index) != 0
+ && properties.memory_types[index as usize]
+ .property_flags
+ .contains(vk::MemoryPropertyFlags::DEVICE_LOCAL)
+ })
+ .ok_or("no device-local memory type")?;
+ let mut export_info = vk::ExportMemoryAllocateInfo::default()
+ .handle_types(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD);
+ let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().buffer(buffer);
+ let allocate = vk::MemoryAllocateInfo::default()
+ .allocation_size(requirements.size)
+ .memory_type_index(memory_type)
+ .push_next(&mut export_info)
+ .push_next(&mut dedicated);
+ let memory = raw
+ .allocate_memory(&allocate, None)
+ .map_err(|error| format!("vkAllocateMemory: {error}"))?;
+ raw.bind_buffer_memory(buffer, memory, 0)
+ .map_err(|error| format!("vkBindBufferMemory: {error}"))?;
+ let fd_loader = ash::khr::external_memory_fd::Device::new(instance, raw);
+ let fd = fd_loader
+ .get_memory_fd(
+ &vk::MemoryGetFdInfoKHR::default()
+ .memory(memory)
+ .handle_type(vk::ExternalMemoryHandleTypeFlags::OPAQUE_FD),
+ )
+ .map_err(|error| format!("vkGetMemoryFdKHR: {error}"))?;
+ Ok::<_, String>((buffer, memory, requirements.size, fd))
+ })?
+ };
+
+ let cuda_ptr = cuda.with_context(|| unsafe {
+ let handle = ExternalMemoryHandleDesc {
+ kind: CU_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD,
+ _pad: 0,
+ fd,
+ _union_rest: [0; 12],
+ size: allocation_size,
+ flags: CUDA_EXTERNAL_MEMORY_DEDICATED,
+ reserved: [0; 16],
+ };
+ let mut external = std::ptr::null_mut();
+ check(
+ (cuda.import_external_memory)(&mut external, &handle),
+ "cuImportExternalMemory",
+ )?;
+ let mapping = ExternalMemoryBufferDesc {
+ offset: 0,
+ size,
+ flags: 0,
+ reserved: [0; 16],
+ };
+ let mut pointer = 0;
+ check(
+ (cuda.external_memory_mapped_buffer)(&mut pointer, external, &mapping),
+ "cuExternalMemoryGetMappedBuffer",
+ )?;
+ Ok(pointer)
+ })?;
+
+ let buffer = unsafe {
+ let hal_buffer = wgpu_hal::vulkan::Device::buffer_from_raw(raw_buffer);
+ device.create_buffer_from_hal::<wgpu_hal::api::Vulkan>(
+ hal_buffer,
+ &wgpu::BufferDescriptor {
+ label: Some(label),
+ size,
+ usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ },
+ )
+ };
+
+ Ok(Self {
+ buffer,
+ size,
+ cuda_ptr,
+ _memory: memory,
+ })
+ }
+}
+
+/// A fixed ring of shared buffers. A slot is free again once the GPU work
+/// that reads it has completed (input) or its consumer dropped it (output).
+pub struct SharedRing {
+ slots: Vec<Arc<RingSlot>>,
+ next: usize,
+}
+
+pub struct RingSlot {
+ pub shared: std::mem::ManuallyDrop<SharedBuffer>,
+ busy: AtomicBool,
+ device: wgpu::Device,
+}
+
+impl RingSlot {
+ pub fn release(&self) {
+ self.busy.store(false, Ordering::Release);
+ }
+
+ pub fn is_busy(&self) -> bool {
+ self.busy.load(Ordering::Acquire)
+ }
+}
+
+/// Shared buffers are never freed individually (their Vulkan memory and CUDA
+/// import outlive wgpu's deferred buffer destruction), so rings hand them back
+/// here and later rings on the same device reuse them. With a device that
+/// lives for the whole process this bounds memory to one set per size;
+/// allocating fresh per render leaked ~250 MB per 4K chunk until NVDEC hit
+/// CUDA_ERROR_OUT_OF_MEMORY.
+static POOL: std::sync::Mutex<Vec<(wgpu::Device, SharedBuffer)>> =
+ std::sync::Mutex::new(Vec::new());
+
+static ALLOCATED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+
+/// (shared buffers ever allocated, buffers idle in the pool, CUDA free MiB).
+pub fn memory_stats() -> (usize, usize, u64) {
+ let pooled = POOL.lock().map_or(0, |pool| pool.len());
+ let free = cuda()
+ .and_then(|cuda| {
+ cuda.with_context(|| {
+ let (mut free, mut total) = (0usize, 0usize);
+ check(
+ unsafe { (cuda.mem_get_info)(&mut free, &mut total) },
+ "cuMemGetInfo",
+ )?;
+ Ok(free as u64 >> 20)
+ })
+ })
+ .unwrap_or(0);
+ (ALLOCATED.load(Ordering::Relaxed), pooled, free)
+}
+
+fn pooled_buffer(device: &wgpu::Device, size: u64, label: &str) -> Result<SharedBuffer, String> {
+ if let Ok(mut pool) = POOL.lock()
+ && let Some(index) = pool
+ .iter()
+ // `SharedBuffer::new` rounds up to whole pages and stores that.
+ .position(|(owner, buffer)| {
+ owner == device && buffer.size == size.next_multiple_of(4096)
+ })
+ {
+ return Ok(pool.swap_remove(index).1);
+ }
+ ALLOCATED.fetch_add(1, Ordering::Relaxed);
+ SharedBuffer::new(device, size, label)
+}
+
+/// The buffer goes back to the pool when the slot's last reference drops:
+/// output frames can outlive their ring (the encoder drains its queue after
+/// the renderer returns), so the ring itself cannot hand them back.
+impl Drop for RingSlot {
+ fn drop(&mut self) {
+ // SAFETY: `shared` is not touched again after this.
+ let shared = unsafe { std::mem::ManuallyDrop::take(&mut self.shared) };
+ if let Ok(mut pool) = POOL.lock() {
+ pool.push((self.device.clone(), shared));
+ }
+ }
+}
+
+impl SharedRing {
+ pub fn new(
+ device: &wgpu::Device,
+ count: usize,
+ size: u64,
+ label: &str,
+ ) -> Result<Self, String> {
+ let slots = (0..count)
+ .map(|_| {
+ pooled_buffer(device, size, label).map(|shared| {
+ Arc::new(RingSlot {
+ shared: std::mem::ManuallyDrop::new(shared),
+ busy: AtomicBool::new(false),
+ device: device.clone(),
+ })
+ })
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(Self { slots, next: 0 })
+ }
+
+ pub fn size(&self) -> u64 {
+ self.slots.first().map_or(0, |slot| slot.shared.size)
+ }
+
+ /// Next free slot, polling the device until one frees up. `None` after
+ /// 10 s: every slot is held by a frame nobody is consuming.
+ pub fn acquire(&mut self, device: &wgpu::Device) -> Option<Arc<RingSlot>> {
+ let started = std::time::Instant::now();
+ loop {
+ for offset in 0..self.slots.len() {
+ let index = (self.next + offset) % self.slots.len();
+ let slot = &self.slots[index];
+ if !slot.is_busy() {
+ slot.busy.store(true, Ordering::Release);
+ self.next = (index + 1) % self.slots.len();
+ return Some(Arc::clone(slot));
+ }
+ }
+ if started.elapsed() > std::time::Duration::from_secs(10) {
+ return None;
+ }
+ let _ = device.poll(wgpu::PollType::Poll);
+ if started.elapsed() > std::time::Duration::from_millis(2) {
+ std::thread::sleep(std::time::Duration::from_micros(200));
+ }
+ }
+ }
+}
+
+/// A decoded NV12 frame resident in CUDA memory (an ffmpeg CUDA AVFrame,
+/// kept alive by holding a reference to it).
+pub struct CudaNv12Frame {
+ pub y: CuDevicePtr,
+ pub uv: CuDevicePtr,
+ pub y_pitch: usize,
+ pub uv_pitch: usize,
+ pub width: u32,
+ pub height: u32,
+ _owner: Mutex<Box<dyn Send>>,
+}
+
+impl CudaNv12Frame {
+ /// # Safety
+ /// `y`/`uv` must be device pointers kept valid by `owner`.
+ #[allow(clippy::too_many_arguments)]
+ pub unsafe fn new(
+ y: CuDevicePtr,
+ uv: CuDevicePtr,
+ y_pitch: usize,
+ uv_pitch: usize,
+ width: u32,
+ height: u32,
+ owner: Box<dyn Send>,
+ ) -> Self {
+ Self {
+ y,
+ uv,
+ y_pitch,
+ uv_pitch,
+ width,
+ height,
+ _owner: Mutex::new(owner),
+ }
+ }
+}
+
+/// Rendered NV12 output resident in a shared buffer. Dropping it hands the
+/// slot back to the renderer.
+pub struct GpuNv12Output {
+ pub slot: Arc<RingSlot>,
+ pub y_stride: u32,
+ pub uv_offset: u64,
+ pub uv_stride: u32,
+}
+
+impl GpuNv12Output {
+ pub fn cuda_ptr(&self) -> CuDevicePtr {
+ self.slot.shared.cuda_ptr
+ }
+}
+
+impl Drop for GpuNv12Output {
+ fn drop(&mut self) {
+ self.slot.release();
+ }
+}
diff --git a/crates/rendering/src/yuv_converter.rs b/crates/rendering/src/yuv_converter.rs
index 969e21208..fd187ccbf 100644
--- a/crates/rendering/src/yuv_converter.rs
+++ b/crates/rendering/src/yuv_converter.rs
@@ -19,6 +19,9 @@ use windows::Win32::Graphics::Direct3D11::{
#[derive(Debug, thiserror::Error)]
pub enum YuvConversionError {
+ #[cfg(target_os = "linux")]
+ #[error("GPU interop: {0}")]
+ GpuInterop(String),
#[error("{plane} plane size mismatch: expected {expected}, got {actual}")]
PlaneSizeMismatch {
plane: &'static str,
@@ -436,6 +439,8 @@ pub struct YuvToRgbaConverter {
zero_copy_failed: bool,
#[cfg(target_os = "windows")]
d3d11_interop: D3D11WgpuInterop,
+ #[cfg(target_os = "linux")]
+ cuda_staging: Option<crate::linux_gpu::SharedRing>,
}
impl YuvToRgbaConverter {
@@ -494,9 +499,133 @@ impl YuvToRgbaConverter {
zero_copy_failed: false,
#[cfg(target_os = "windows")]
d3d11_interop: D3D11WgpuInterop::new(),
+ #[cfg(target_os = "linux")]
+ cuda_staging: None,
}
}
+ /// NV12 straight from NVDEC: device-to-device into a Vulkan-shared
+ /// staging buffer, then GPU copies into the plane textures. Nothing
+ /// touches system memory.
+ #[cfg(target_os = "linux")]
+ pub fn convert_nv12_cuda(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ frame: &crate::linux_gpu::CudaNv12Frame,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ let width = frame.width;
+ let height = frame.height;
+ let (effective_width, effective_height, _downscaled) =
+ validate_dimensions(width, height, self.gpu_max_texture_size)?;
+ self.ensure_texture_size(device, effective_width, effective_height);
+ self.swap_output_buffer();
+
+ let pitch = u64::from(width.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT));
+ let needed = pitch * u64::from(height) * 3 / 2;
+ if self
+ .cuda_staging
+ .as_ref()
+ .is_none_or(|ring| ring.size() < needed)
+ {
+ self.cuda_staging = Some(
+ crate::linux_gpu::SharedRing::new(device, 3, needed, "NV12 CUDA Staging")
+ .map_err(YuvConversionError::GpuInterop)?,
+ );
+ }
+ let ring = self.cuda_staging.as_mut().expect("staging ring");
+ let slot = ring.acquire(device).ok_or_else(|| {
+ YuvConversionError::GpuInterop("no free CUDA staging slot".to_string())
+ })?;
+ let base = slot.shared.cuda_ptr;
+ let y_rows = height as usize;
+ let copied = crate::linux_gpu::copy_plane(
+ frame.y,
+ frame.y_pitch,
+ base,
+ pitch as usize,
+ width as usize,
+ y_rows,
+ )
+ .and_then(|_| {
+ crate::linux_gpu::copy_plane(
+ frame.uv,
+ frame.uv_pitch,
+ base + pitch * u64::from(height),
+ pitch as usize,
+ width as usize,
+ y_rows / 2,
+ )
+ })
+ .and_then(|_| crate::linux_gpu::synchronize());
+ if let Err(error) = copied {
+ slot.release();
+ return Err(YuvConversionError::GpuInterop(error));
+ }
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("NV12 CUDA Conversion Encoder"),
+ });
+ encoder.copy_buffer_to_texture(
+ wgpu::TexelCopyBufferInfo {
+ buffer: &slot.shared.buffer,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(pitch as u32),
+ rows_per_image: Some(height),
+ },
+ },
+ self.y_texture.as_image_copy(),
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ encoder.copy_buffer_to_texture(
+ wgpu::TexelCopyBufferInfo {
+ buffer: &slot.shared.buffer,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: pitch * u64::from(height),
+ bytes_per_row: Some(pitch as u32),
+ rows_per_image: Some(height / 2),
+ },
+ },
+ self.uv_texture.as_image_copy(),
+ wgpu::Extent3d {
+ width: width / 2,
+ height: height / 2,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ let output_index = self.current_output;
+ let bind_group = self.bind_group_cache.get_or_create_nv12(
+ device,
+ &self.pipelines.nv12_bind_group_layout,
+ &self.y_view,
+ &self.uv_view,
+ &self.output_views[output_index],
+ output_index,
+ self.allocated_width,
+ self.allocated_height,
+ );
+ {
+ let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some("NV12 CUDA Conversion Pass"),
+ ..Default::default()
+ });
+ compute_pass.set_pipeline(&self.pipelines.nv12_pipeline);
+ compute_pass.set_bind_group(0, bind_group, &[]);
+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);
+ }
+ queue.submit(std::iter::once(encoder.finish()));
+ let released = std::sync::Arc::clone(&slot);
+ queue.on_submitted_work_done(move || released.release());
+
+ Ok(self.current_output_view())
+ }
+
fn create_y_texture(
device: &wgpu::Device,
width: u32,