Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(render-farm): make task ownership, resume and GPU interop failures safe

Richie McIlroy6011f3183e92
diff --git a/apps/render-farm/src/coordinator.ts b/apps/render-farm/src/coordinator.ts
index 40da7446f..c84c93b6c 100644
--- a/apps/render-farm/src/coordinator.ts
+++ b/apps/render-farm/src/coordinator.ts
@@ -55,10 +55,11 @@ 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";
+// Every dispatch of a chunk (original, hedge, retry) uploads into its own part
+// range, cycling through this many. NVENC output differs between GPUs, so two
+// live copies must never write the same part numbers; completion lists exactly
+// the accepted copy's parts and S3 discards the rest.
+const PART_RANGES = 4;
// 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
@@ -168,9 +169,9 @@ async function runAudioLocally(job: Job, state: TaskState) {
if (state.attempts >= 3) failJob(job, error);
else
setTimeout(() => {
- state.state = "queued";
- state.worker = undefined;
- queue.unshift(state);
+ if (job.status !== "rendering" || job.audioSections.has(task.section))
+ return;
+ requeue(state, "local audio lane failed");
pumpLocalAudio();
dispatch();
}, 1000 * state.attempts);
@@ -204,6 +205,8 @@ type Chunk = {
files: FileSpec[];
firstPart: number;
partLimit: number;
+ /** Copies dispatched so far; picks each dispatch's part range. */
+ dispatches: number;
};
type TaskState = {
@@ -222,6 +225,8 @@ type TaskState = {
* chunk being rendered twice.
*/
heldUntil?: number;
+ /** Last heartbeat in which the owning worker listed this task. */
+ lastReportedAt?: number;
progress?: { frames: number; total: number; elapsedMs: number; at: number };
};
@@ -390,6 +395,33 @@ type SourceIndex = {
// once uploaded, so their moov indexes never need re-reading per export.
const sourceIndexes = new Map<string, SourceIndex>();
+// Shared prefixes a manifest may point sources at besides its own recording
+// prefix (e.g. assets reused across recordings), comma-separated.
+const SOURCE_KEY_PREFIXES = (process.env.RF_SOURCE_KEY_PREFIXES ?? "")
+ .split(",")
+ .filter(Boolean);
+
+/** Manifests name local paths and bucket keys; neither may escape its scope. */
+function checkManifest(manifest: Manifest, prefix: string) {
+ for (const file of manifest.files) {
+ const parts = file.path.split("/");
+ if (
+ file.path.startsWith("/") ||
+ parts.includes("..") ||
+ parts.includes("")
+ ) {
+ throw new Error(`manifest path ${file.path} is not a relative path`);
+ }
+ if (
+ file.key !== undefined &&
+ !file.key.startsWith(`${prefix}/`) &&
+ !SOURCE_KEY_PREFIXES.some((allowed) => file.key?.startsWith(allowed))
+ ) {
+ throw new Error(`manifest key for ${file.path} is outside the recording`);
+ }
+ }
+}
+
async function sourceIndex(prefix: string): Promise<SourceIndex> {
const cached =
process.env.RF_INDEX_CACHE !== "0" ? sourceIndexes.get(prefix) : undefined;
@@ -397,6 +429,7 @@ async function sourceIndex(prefix: string): Promise<SourceIndex> {
const manifest = JSON.parse(
new TextDecoder().decode(await s3.get(`${prefix}/manifest.json`)),
) as Manifest;
+ checkManifest(manifest, prefix);
const keyOf = (file: { path: string; key?: string }) =>
file.key ?? `${prefix}/${file.path}`;
const metaFile = manifest.files.find(
@@ -575,12 +608,10 @@ async function planJob(job: Job) {
});
const chunkCount = boundaries.length - 1;
const partsPerChunk = Math.floor(9998 / chunkCount);
- if (partsPerChunk < (SPLIT_HEDGE_PARTS ? 8 : 4)) {
+ const partLimit = Math.floor(partsPerChunk / PART_RANGES);
+ if (partLimit < 3) {
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) => {
@@ -630,6 +661,7 @@ async function planJob(job: Job) {
],
firstPart: 2 + index * partsPerChunk,
partLimit,
+ dispatches: 0,
});
}
@@ -874,10 +906,10 @@ function audioFrame(meta: AudioResultMeta, data: Uint8Array) {
return body;
}
-function newHlsState(prefix: string): HlsState {
+async function newHlsState(prefix: string): Promise<HlsState> {
return {
prefix,
- url: s3.presign("GET", `${prefix}/index.m3u8`, 6 * 3600),
+ url: await s3.presignFresh("GET", `${prefix}/index.m3u8`, 6 * 3600),
segments: new Map(),
listed: [],
cursor: { chunk: 0, index: 0 },
@@ -947,9 +979,10 @@ async function resumeJobs() {
workersUsed: new Set(),
waiters: [],
taskStats: [],
- hls: record.hls ? newHlsState(record.hls.prefix) : undefined,
+ hls: record.hls ? await newHlsState(record.hls.prefix) : undefined,
};
job.t.resumed = now();
+ job.t.lastProgress = now();
for (const name of names) {
const video = name.match(/^v\/(\d+)\.json$/);
if (video) {
@@ -1055,6 +1088,34 @@ function pickQueued(accepts: (kind: string) => boolean) {
});
}
+/** The task as sent for this attempt: its attempt number and part range. */
+function dispatchedTask(job: Job | undefined, state: TaskState): Task {
+ const task = state.task;
+ if (task.kind !== "video" || !job)
+ return { ...task, attempt: state.attempts };
+ const chunk = job.chunks[task.chunk];
+ if (!chunk) return { ...task, attempt: state.attempts };
+ const range = chunk.dispatches++ % PART_RANGES;
+ return {
+ ...task,
+ attempt: state.attempts,
+ upload: {
+ ...task.upload,
+ firstPart: chunk.firstPart + range * chunk.partLimit,
+ partLimit: chunk.partLimit,
+ },
+ };
+}
+
+/** Put a task back in the queue, at most once. */
+function requeue(state: TaskState, reason: string) {
+ console.warn(`requeue ${state.task.taskId}: ${reason}`);
+ state.state = "queued";
+ state.worker = undefined;
+ state.progress = undefined;
+ if (!queue.includes(state)) queue.unshift(state);
+}
+
function dispatch() {
pumpLocalAudio();
for (let p = 0; p < pollers.length; ) {
@@ -1079,13 +1140,14 @@ function dispatch() {
state.worker = poller.worker;
state.startedAt = now();
state.attempts++;
+ state.lastReportedAt = undefined;
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);
+ poller.resolve(dispatchedTask(job, state));
}
}
@@ -1147,21 +1209,8 @@ function straggler(): TaskState | 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 task: VideoTask = { ...original, taskId: `${original.taskId}:dup` };
const state: TaskState = {
task,
state: "queued",
@@ -1198,17 +1247,19 @@ function cancellations(worker: string) {
*/
function supersede(id: string) {
const host = id.slice(0, id.lastIndexOf("-"));
- for (const old of [...workers.keys()]) {
+ // Only predecessors that have gone quiet: two live workers sharing a
+ // hostname (several GPUs on one host) must not evict each other.
+ const quietSince = Date.now() - 4_500;
+ for (const [old, worker] of [...workers.entries()]) {
if (old === id || old.slice(0, old.lastIndexOf("-")) !== host) continue;
+ if (worker.lastSeen > quietSince) 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);
+ if (state.state === "running" && state.worker === old) {
+ requeue(state, `worker ${old} restarted`);
+ }
}
}
}
@@ -1238,13 +1289,15 @@ setInterval(() => {
)
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);
+ if (!worker || worker.lastSeen < cutoff) {
+ requeue(state, `worker ${state.worker} went away`);
+ continue;
+ }
+ // A live worker that stops listing a task (lost /work response,
+ // crashed slot) no longer holds it.
+ if ((state.lastReportedAt ?? state.startedAt ?? 0) < cutoff) {
+ requeue(state, `not reported by ${state.worker}`);
+ }
}
}
dispatch();
@@ -1286,7 +1339,7 @@ async function writeInit(job: Job, hls: HlsState) {
}),
"video/mp4",
);
- hls.initUrl = s3.presign("GET", key, 6 * 3600);
+ hls.initUrl = await s3.presignFresh("GET", key, 6 * 3600);
return true;
}
@@ -1310,7 +1363,7 @@ async function publishPlaylist(job: Job) {
?.get(hls.cursor.index);
if (!segment) break;
hls.listed.push({
- url: s3.presign("GET", segment.key, 6 * 3600),
+ url: await s3.presignFresh("GET", segment.key, 6 * 3600),
duration: (segment.frames[1] - segment.frames[0]) / job.fps,
});
grew = true;
@@ -1378,6 +1431,8 @@ function recordStat(
function onVideoDone(job: Job, state: TaskState, result: VideoResult) {
if (state.task.kind !== "video") return;
state.state = "done";
+ const queued = queue.indexOf(state);
+ if (queued >= 0) queue.splice(queued, 1);
const chunk = state.task.chunk;
recordStat(job, "video", chunk, result.worker, {
...result.timings,
@@ -1406,6 +1461,19 @@ function onVideoDone(job: Job, state: TaskState, result: VideoResult) {
}
job.videoResults.set(chunk, result);
job.t.lastProgress = now();
+ // Segments reported to a previous coordinator process (before a restart)
+ // are not reported again; derive any missing ones from the result.
+ const chunkPlan = job.chunks[chunk];
+ if (job.hls && chunkPlan) {
+ job.hls.extradata ??= result.extradata;
+ const known =
+ job.hls.segments.get(chunk) ?? new Map<number, SegmentReport>();
+ for (const segment of segmentsFromResult(job, chunkPlan, result)) {
+ if (!known.has(segment.index)) known.set(segment.index, segment);
+ }
+ job.hls.segments.set(chunk, known);
+ publishPlaylist(job);
+ }
journalPut(journalKey(job.id, `v/${chunk}.json`), JSON.stringify(result));
if (job.videoResults.size === job.chunks.length) {
job.t.videoDone = now();
@@ -1421,6 +1489,11 @@ function onAudioDone(
) {
if (state.task.kind !== "audio") return;
state.state = "done";
+ const queued = queue.indexOf(state);
+ if (queued >= 0) queue.splice(queued, 1);
+ // Chunks may already have muxed the first copy's packets; a second render
+ // replacing them would desync the header from those bytes.
+ if (job.audioSections.has(state.task.section)) return;
if (!job.audioSections.has(state.task.section)) {
journalPut(
journalKey(job.id, `a/${state.task.section}.bin`),
@@ -1530,68 +1603,19 @@ async function assemble(job: Job) {
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);
- }
- }
+ // Exactly the accepted copies' parts: other copies' parts sit in their own
+ // ranges and are discarded, and S3 checks every listed ETag, so a part
+ // overwritten with other bytes fails the completion instead of corrupting it.
+ await s3.completeMultipart(
+ job.key,
+ job.uploadId,
+ parts.sort((a, b) => a.partNumber - b.partNumber),
+ );
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);
+ job.url = await s3.presignFresh("GET", job.key, 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.
@@ -1756,6 +1780,7 @@ Bun.serve({
kinds?: string[];
audioSlots?: number;
prefetch?: boolean;
+ draining?: boolean;
};
const worker = workers.get(body.worker) ?? {
id: body.worker,
@@ -1767,8 +1792,10 @@ Bun.serve({
worker.lastSeen = Date.now();
worker.slots = body.slots;
worker.audioSlots = body.audioSlots ?? 0;
- if (!workers.has(body.worker)) supersede(body.worker);
+ supersede(body.worker);
workers.set(body.worker, worker);
+ if (body.draining)
+ return Response.json({ task: null, finished: finishedJobs });
const task = await new Promise<Task | null>((resolve) => {
const poller: Poller = {
worker: body.worker,
@@ -1804,6 +1831,8 @@ Bun.serve({
usage?: Usage | null;
running?: {
taskId: string;
+ attempt?: number;
+ phase?: "reserved" | "running";
frames: number;
total: number;
elapsedMs: number;
@@ -1819,11 +1848,15 @@ Bun.serve({
state.worker = body.worker;
state.startedAt = now() - entry.elapsedMs;
state.heldUntil = undefined;
- state.attempts = 1;
+ state.attempts = entry.attempt ?? 1;
+ state.prefetched = entry.phase === "reserved";
const index = queue.indexOf(state);
if (index >= 0) queue.splice(index, 1);
console.log(`re-attached ${entry.taskId} to ${body.worker}`);
}
+ if (state.state !== "running" || state.worker !== body.worker) continue;
+ state.lastReportedAt = Date.now();
+ if (entry.phase === "reserved") continue;
if (state.task.kind === "video") {
if (entry.frames > (state.progress?.frames ?? 0) && job)
job.t.lastProgress = now();
@@ -1831,11 +1864,11 @@ Bun.serve({
}
}
const worker = workers.get(body.worker);
+ supersede(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,
@@ -1882,9 +1915,19 @@ Bun.serve({
const body = (await request.json()) as {
error: string;
worker: string;
+ attempt?: number;
};
console.warn(`task ${taskId} failed on ${body.worker}: ${body.error}`);
if (job.status !== "rendering") return Response.json({ ok: true });
+ // A stale copy (already requeued, re-dispatched or resumed) failing
+ // says nothing about the attempt now in charge of the task.
+ if (
+ state.state !== "running" ||
+ state.worker !== body.worker ||
+ (body.attempt !== undefined && body.attempt !== state.attempts)
+ ) {
+ return Response.json({ ok: true });
+ }
if (
state.task.kind === "video" &&
job.videoResults.has(state.task.chunk)
@@ -1903,11 +1946,9 @@ Bun.serve({
// 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);
+ state.heldUntil = Date.now() + 1000 * state.attempts;
+ if (!queue.includes(state)) queue.unshift(state);
+ setTimeout(dispatch, 1000 * state.attempts + 50);
}
return Response.json({ ok: true });
}
@@ -1990,7 +2031,10 @@ Bun.serve({
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 parsed = validateJobRequest(await request.json().catch(() => null));
+ if (typeof parsed === "string")
+ return new Response(parsed, { status: 400 });
+ const body = parsed;
const started = performance.now();
await sourceIndex(body.recording.replace(/\/$/, ""));
return Response.json({ ms: Math.round(performance.now() - started) });
@@ -2037,7 +2081,7 @@ Bun.serve({
waiters: [],
taskStats: [],
};
- if (HLS) job.hls = newHlsState(`hls/${id}`);
+ if (HLS) job.hls = await newHlsState(`hls/${id}`);
jobs.set(id, job);
planJob(job).catch((error) => failJob(job, error));
return Response.json({ id, hlsUrl: job.hls?.url });
diff --git a/apps/render-farm/src/engine.ts b/apps/render-farm/src/engine.ts
index 59a8c6381..1b62dc329 100644
--- a/apps/render-farm/src/engine.ts
+++ b/apps/render-farm/src/engine.ts
@@ -186,9 +186,10 @@ 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(() => {
+ const stop = () => {
done = true;
- });
+ };
+ until.then(stop, stop);
while (!done) {
try {
for (const tid of readdirSync(`/proc/${pid}/task`)) {
diff --git a/apps/render-farm/src/materialize.ts b/apps/render-farm/src/materialize.ts
index c55c5385e..8df1d5214 100644
--- a/apps/render-farm/src/materialize.ts
+++ b/apps/render-farm/src/materialize.ts
@@ -7,7 +7,7 @@ import {
writeFileSync,
writeSync,
} from "node:fs";
-import { dirname, join } from "node:path";
+import { dirname, join, resolve, sep } from "node:path";
import type { S3 } from "./s3";
// Recreates a recording on local disk with only the bytes a task needs.
@@ -67,7 +67,10 @@ export class ProjectCache {
}
private open(spec: FileSpec) {
- const fullPath = join(this.root, spec.path);
+ const fullPath = resolve(this.root, spec.path);
+ if (!fullPath.startsWith(resolve(this.root) + sep)) {
+ throw new Error(`${spec.path} is outside the project`);
+ }
let file = this.files.get(fullPath);
if (!file) {
mkdirSync(dirname(fullPath), { recursive: true });
diff --git a/apps/render-farm/src/planning.ts b/apps/render-farm/src/planning.ts
index 49f7b0eda..b9b0848cd 100644
--- a/apps/render-farm/src/planning.ts
+++ b/apps/render-farm/src/planning.ts
@@ -21,6 +21,9 @@ export type ChunkPlanInput = {
* Boundaries sit on GOP edges when chunks are long enough, else on whole
* seconds; every chunk opens with its own IDR either way.
*/
+/** Keeps four part ranges of at least three parts per chunk in one upload. */
+export const MAX_CHUNKS = 800;
+
export function planChunkBoundaries(input: ChunkPlanInput) {
const { totalFrames, fps } = input;
const gop = fps * 2;
@@ -37,7 +40,7 @@ export function planChunkBoundaries(input: ChunkPlanInput) {
input.chunksPerSlot ?? 6,
Math.ceil(totalFrames / input.targetFrames / slots),
);
- chunkCount = Math.min(slots * waves, 2000);
+ chunkCount = Math.min(slots * waves, MAX_CHUNKS);
}
const unit = totalFrames / Math.max(1, chunkCount) >= gop ? gop : fps;
const units = Math.ceil(totalFrames / unit);
diff --git a/apps/render-farm/src/protocol.ts b/apps/render-farm/src/protocol.ts
index 663b5905b..c9cb44e54 100644
--- a/apps/render-farm/src/protocol.ts
+++ b/apps/render-farm/src/protocol.ts
@@ -15,6 +15,8 @@ export const MIN_PART = 5 * 1024 * 1024;
export type VideoTask = {
kind: "video";
taskId: string;
+ /** Dispatch attempt; echoed in failures so stale ones are ignored. */
+ attempt?: number;
jobId: string;
chunk: number;
fps: number;
@@ -53,6 +55,7 @@ export type SegmentReport = {
export type AudioTask = {
kind: "audio";
taskId: string;
+ attempt?: number;
jobId: string;
section: number;
fps: number;
diff --git a/apps/render-farm/src/s3.ts b/apps/render-farm/src/s3.ts
index ab9be72d3..2f6c88e88 100644
--- a/apps/render-farm/src/s3.ts
+++ b/apps/render-farm/src/s3.ts
@@ -50,13 +50,40 @@ function hmac(key: Buffer | string, value: string) {
export class S3 {
private expiresAt = 0;
+ private fetchedAt = 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;
+ /**
+ * Presigns with credentials refreshed first. A URL signed with instance-role
+ * credentials stops working when they expire, so its lifetime is capped at
+ * theirs (up to ~6 h after issue); longer-lived playback needs a CDN.
+ */
+ async presignFresh(method: string, key: string, expiresSeconds: number) {
+ await this.ready(Math.min(expiresSeconds * 1000, 60 * 60_000));
+ const remaining = this.config.imds
+ ? Math.floor((this.expiresAt - Date.now()) / 1000) - 60
+ : expiresSeconds;
+ return this.presign(
+ method,
+ key,
+ Math.max(60, Math.min(expiresSeconds, remaining)),
+ );
+ }
+
+ async ready(minRemainingMs = 5 * 60_000) {
+ if (!this.config.imds || Date.now() < this.expiresAt - minRemainingMs)
+ return;
+ // Instance credentials rotate on AWS's schedule; asking again sooner
+ // returns the same ones, so only the hard 5 min floor forces a fetch.
+ if (
+ Date.now() - this.fetchedAt < 60_000 &&
+ Date.now() < this.expiresAt - 5 * 60_000
+ ) {
+ return;
+ }
this.refreshing ??= (async () => {
const token = await (
await fetch("http://169.254.169.254/latest/api/token", {
@@ -82,6 +109,7 @@ export class S3 {
this.config.secretAccessKey = credentials.SecretAccessKey;
this.config.sessionToken = credentials.Token;
this.expiresAt = Date.parse(credentials.Expiration);
+ this.fetchedAt = Date.now();
})().finally(() => {
this.refreshing = null;
});
diff --git a/apps/render-farm/src/scheduler.test.ts b/apps/render-farm/src/scheduler.test.ts
index c447fa60e..bb2d70bb2 100644
--- a/apps/render-farm/src/scheduler.test.ts
+++ b/apps/render-farm/src/scheduler.test.ts
@@ -115,6 +115,16 @@ describe("pickQueued", () => {
).toBe(1);
});
+ test("leftover entries of jobs that are no longer rendering are skipped", () => {
+ const done = job("done", 0, 4, { status: "ready" });
+ const live = job("live", 50, 4, { runningTasks: 30 });
+ const queue = [video("done", 0), video("gone", 0), video("live", 3)];
+ expect(pickQueued(queue, [done, live], any, options)).toBe(2);
+ expect(
+ pickQueued(queue, [done, live], any, { ...options, fifo: true }),
+ ).toBe(2);
+ });
+
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
index e1b6b84ab..563c8f427 100644
--- a/apps/render-farm/src/scheduler.ts
+++ b/apps/render-farm/src/scheduler.ts
@@ -42,13 +42,12 @@ export function pickQueued(
accepts: (kind: SchedulableTask["kind"]) => boolean,
options: SchedulerOptions,
) {
+ const byId = new Map<string, { job: SchedulableJob; head: Set<number> }>();
const eligible = (state: SchedulableState) =>
state.state === "queued" &&
+ byId.has(state.task.jobId) &&
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>();
@@ -59,6 +58,7 @@ export function pickQueued(
}
byId.set(job.id, { job, head });
}
+ if (options.fifo) return queue.findIndex(eligible);
let best = -1;
let bestKey: number[] | null = null;
@@ -66,15 +66,14 @@ export function pickQueued(
if (!eligible(state)) continue;
const task = state.task;
const entry = byId.get(task.jobId);
+ if (!entry) continue;
const position = task.kind === "video" ? task.chunk : task.section;
const gating =
- task.kind === "video"
- ? entry?.head.has(task.chunk) === true
- : position === 0;
+ task.kind === "video" ? entry.head.has(task.chunk) : position === 0;
const key = [
gating ? 0 : 1,
- entry?.job.runningTasks ?? 0,
- entry?.job.requestedAt ?? 0,
+ entry.job.runningTasks,
+ entry.job.requestedAt,
position,
];
if (!bestKey || compareKeys(key, bestKey) < 0) {
diff --git a/apps/render-farm/src/validate.test.ts b/apps/render-farm/src/validate.test.ts
index 9b68a892a..4b2328b33 100644
--- a/apps/render-farm/src/validate.test.ts
+++ b/apps/render-farm/src/validate.test.ts
@@ -25,7 +25,12 @@ describe("validateJobRequest", () => {
{ recording: "rec", compression: "Lossless" },
"compression must be one of",
],
+ [
+ { recording: "rec", compression: "toString" },
+ "compression must be one of",
+ ],
[{ recording: "rec", maxChunks: -1 }, "maxChunks"],
+ [{ recording: "rec", chunks: 5000 }, "chunks"],
[{ recording: "rec", chunkWorkSeconds: Number.NaN }, "chunkWorkSeconds"],
[{ recording: "rec", label: "x".repeat(201) }, "label"],
])("rejects %j", (body, message) => {
diff --git a/apps/render-farm/src/validate.ts b/apps/render-farm/src/validate.ts
index 1dae6b2c6..6ff68a294 100644
--- a/apps/render-farm/src/validate.ts
+++ b/apps/render-farm/src/validate.ts
@@ -42,14 +42,14 @@ export function validateJobRequest(body: unknown): JobRequest | string {
request.compression !== undefined &&
!(
typeof request.compression === "string" &&
- request.compression in COMPRESSION_BPP
+ Object.hasOwn(COMPRESSION_BPP, request.compression)
)
) {
return `compression must be one of ${Object.keys(COMPRESSION_BPP).join(", ")}`;
}
for (const [field, max] of [
- ["maxChunks", 5000],
- ["chunks", 5000],
+ ["maxChunks", 800],
+ ["chunks", 800],
["chunksPerSlot", 64],
["frameLimit", 10_000_000],
] as const) {
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index 7fa4f2483..d591afb10 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -114,23 +114,28 @@ const progress = new Map<
}
>();
-async function post(path: string, body: unknown) {
+async function post(path: string, body: unknown, signal?: AbortSignal) {
for (let attempt = 0; ; attempt++) {
try {
const response = await fetch(`${COORDINATOR}${path}`, {
method: "POST",
headers,
body: JSON.stringify(body),
+ signal,
});
if (!response.ok) throw new Error(`${path} -> ${response.status}`);
return response;
} catch (error) {
- if (attempt >= 5) throw error;
+ if (attempt >= 5 || signal?.aborted) throw error;
await Bun.sleep(250 * 2 ** attempt);
}
}
}
+// Open /work long-polls, aborted when the worker starts draining so the
+// coordinator stops handing it tasks it would never run.
+const openPolls = new Set<AbortController>();
+
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);
@@ -433,6 +438,9 @@ async function runVideo(
const cache = cacheFor(task.jobId);
const fetchStats = await cache.materialize(task.files);
const audioPromise = fetchAudio(task);
+ // Awaited only after the render; without a handler until then, a failure
+ // (job cancelled, coordinator unreachable) would kill the whole worker.
+ audioPromise.catch(() => {});
const out = join(
cache.root,
`v${task.chunk}-${randomUUID().slice(0, 6)}.h264`,
@@ -490,6 +498,7 @@ async function runVideo(
});
nearEnd();
const segmentsDone = stream?.finish(result.sizes, result.extradata);
+ segmentsDone?.catch(() => {});
const engineMs = performance.now() - engineStarted;
const threads = await threadsPromise;
const waitStarted = performance.now();
@@ -633,15 +642,22 @@ async function runAudio(task: AudioTask, engine: Engine, queuedMs: number) {
}
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 controller = new AbortController();
+ openPolls.add(controller);
+ const response = await post(
+ "/work",
+ {
+ worker: WORKER_ID,
+ slots: SLOTS,
+ cpus: CPUS,
+ service: SERVICE,
+ kinds,
+ audioSlots: AUDIO_SLOTS,
+ prefetch,
+ draining,
+ },
+ controller.signal,
+ ).finally(() => openPolls.delete(controller));
const body = (await response.json()) as {
task: Task | null;
finished: string[];
@@ -650,9 +666,15 @@ async function poll(kinds: string[] | undefined, prefetch = false) {
return body.task;
}
+// A stray rejection must not take down every slot's task with the process.
+process.on("unhandledRejection", (error) => {
+ console.error(`unhandled rejection: ${error}`);
+});
+
let draining = false;
-// Slots holding a prefetched (already reserved) next task.
-const reserved = new Set<number>();
+// Slots holding a prefetched (already reserved) next task, once it is known.
+const reserved = new Map<number, Task | null>();
+const busySince = new Map<number, number>();
function exitWhenIdle() {
if (draining && busy.size === 0 && reserved.size === 0) {
@@ -665,6 +687,7 @@ for (const signal of ["SIGTERM", "SIGINT"] as const) {
process.on(signal, () => {
if (draining) return;
draining = true;
+ for (const controller of openPolls) controller.abort();
console.log(
`${signal}: finishing ${busy.size} running task(s), taking no new work`,
);
@@ -698,19 +721,22 @@ async function slotLoop(slot: number) {
// source download (queued work only; never a hedge).
const prefetchNext = () => {
if (next || draining || PREFETCH_LEAD_MS <= 0) return;
- reserved.add(slot);
+ reserved.set(slot, null);
next = poll(kinds, true)
.then((upcoming) => {
- if (upcoming)
+ if (upcoming) {
+ reserved.set(slot, upcoming);
cacheFor(upcoming.jobId)
.materialize(upcoming.files)
.catch(() => {});
+ }
return upcoming;
})
.catch(() => null);
};
const received = performance.now();
busy.set(slot, task);
+ busySince.set(slot, Date.now());
try {
if (!engine.alive) {
engine = warm(
@@ -763,10 +789,12 @@ async function slotLoop(slot: number) {
}
await post(`/tasks/${encodeURIComponent(task.taskId)}/fail`, {
worker: WORKER_ID,
+ attempt: task.attempt,
error: String(error instanceof Error ? error.message : error),
}).catch(() => {});
} finally {
busy.delete(slot);
+ busySince.delete(slot);
exitWhenIdle();
}
}
@@ -844,12 +872,32 @@ setInterval(() => {
}, 5_000);
setInterval(async () => {
- const running = [...progress.values()].map((entry) => ({
- taskId: entry.taskId,
- frames: entry.frames,
- total: entry.total,
- elapsedMs: Date.now() - entry.startedAt,
- }));
+ // Every task this worker holds, in every phase (fetch, render, upload) and
+ // reserved ahead: the coordinator requeues anything a live worker stops
+ // listing, and a restarted coordinator re-attaches what is listed.
+ const running = [];
+ for (const [slot, task] of busy) {
+ const entry = progress.get(slot);
+ running.push({
+ taskId: task.taskId,
+ attempt: task.attempt,
+ phase: "running",
+ frames: entry?.taskId === task.taskId ? entry.frames : 0,
+ total: entry?.taskId === task.taskId ? entry.total : 0,
+ elapsedMs: Date.now() - (busySince.get(slot) ?? Date.now()),
+ });
+ }
+ for (const task of reserved.values()) {
+ if (!task) continue;
+ running.push({
+ taskId: task.taskId,
+ attempt: task.attempt,
+ phase: "reserved",
+ frames: 0,
+ total: 0,
+ elapsedMs: 0,
+ });
+ }
post("/heartbeat", {
worker: WORKER_ID,
slots: SLOTS,
diff --git a/crates/render-farm/src/video.rs b/crates/render-farm/src/video.rs
index 9b717f81f..90af08f74 100644
--- a/crates/render-farm/src/video.rs
+++ b/crates/render-farm/src/video.rs
@@ -331,14 +331,24 @@ pub async fn render(request: VideoRequest) -> Result<VideoResult> {
(received, forward_blocked_us)
};
cap_rendering::loop_stats::take();
+ #[cfg(target_os = "linux")]
+ cap_rendering::linux_gpu::take_interop_failures();
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;
-
+ // `forward` has dropped the encoder's sender, so this returns once the
+ // encoder drains. Joining before looking at the render result keeps a
+ // failed chunk's encoder from outliving the request (it reports events
+ // under the current request id and holds an NVENC session), and surfaces
+ // the encoder's error, which is usually why the render's send failed.
let encoded = encoder
.join()
- .map_err(|_| anyhow!("encoder thread panicked"))??;
+ .map_err(|_| anyhow!("encoder thread panicked"))?;
+ let encoded = match (render_result, encoded) {
+ (_, Err(error)) => return Err(error.context("encode")),
+ (Err(error), Ok(_)) => bail!("render: {error}"),
+ (Ok(()), Ok(encoded)) => encoded,
+ };
if received != expected || encoded.sizes.len() as u32 != expected {
bail!(
"chunk {:?} produced {received} rendered / {} encoded frames, expected {expected}",
@@ -357,6 +367,13 @@ pub async fn render(request: VideoRequest) -> Result<VideoResult> {
{
bail!("gpu path degraded: frames reached the encoder through system memory");
}
+ #[cfg(target_os = "linux")]
+ {
+ let failures = cap_rendering::linux_gpu::take_interop_failures();
+ if failures > 0 && std::env::var("RF_REQUIRE_GPU").as_deref() == Ok("1") {
+ bail!("gpu path degraded: {failures} decoded frames failed to reach the compositor");
+ }
+ }
let ms = |us: u64| us / 1000;
timings.pipeline = Some(serde_json::json!({
"decode_wait": ms(decode),
@@ -540,6 +557,13 @@ fn encode(
for (index, rendered) in first.into_iter().chain(frames.iter()).enumerate() {
let pts = index as i64;
stats[0] += waiting.elapsed().as_micros() as u64;
+ if rendered.width != width || rendered.height != height {
+ bail!(
+ "renderer produced {}x{}, expected {width}x{height}",
+ rendered.width,
+ rendered.height
+ );
+ }
#[cfg(target_os = "linux")]
if let (Some(cuda_frames), Some(gpu)) = (&cuda_frames, rendered.gpu.as_ref()) {
let copy = Instant::now();
@@ -554,13 +578,6 @@ fn encode(
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 {
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index 6e6a03623..b06811534 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -40,7 +40,7 @@ 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));
+ return DecodedFrame::new_nv12_cuda(Arc::clone(cuda), Arc::clone(&self.data));
}
match self.format {
PixelFormat::Rgba => {
@@ -78,6 +78,9 @@ struct PendingRequest {
const MAX_FRAME_LOOKBACK_TOLERANCE: u32 = 2;
const MAX_FRAME_CACHE_BYTES: usize = 128 * 1024 * 1024;
+/// Cache weight of a frame still on the GPU (it pins an NVDEC surface).
+#[cfg(target_os = "linux")]
+const CUDA_FRAME_CACHE_WEIGHT: usize = 16 * 1024 * 1024;
fn extract_yuv_planes(frame: &frame::Video) -> Option<(Vec<u8>, PixelFormat, u32, u32)> {
let height = frame.height();
@@ -251,9 +254,9 @@ impl CachedFrame {
#[cfg(target_os = "linux")]
match self {
Self::Raw { frame, .. } if frame.format() == format::Pixel::CUDA => {
- return 16 * 1024 * 1024;
+ return CUDA_FRAME_CACHE_WEIGHT;
}
- Self::Processed(frame) if frame.cuda.is_some() => return 16 * 1024 * 1024,
+ Self::Processed(frame) if frame.cuda.is_some() => return CUDA_FRAME_CACHE_WEIGHT,
_ => {}
}
match self {
@@ -1160,10 +1163,16 @@ impl FfmpegDecoder {
// 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.
+ // More than the cache holds would evict the frames just decoded ahead.
+ #[cfg(target_os = "linux")]
+ let readahead_limit = (MAX_FRAME_CACHE_BYTES / CUDA_FRAME_CACHE_WEIGHT) as u32;
+ #[cfg(not(target_os = "linux"))]
+ let readahead_limit = FRAME_CACHE_SIZE as u32;
let readahead = std::env::var("CAP_DECODER_READAHEAD")
.ok()
.and_then(|value| value.parse::<u32>().ok())
- .unwrap_or(0);
+ .unwrap_or(0)
+ .min(readahead_limit);
let mut readahead_exhausted = false;
loop {
let r = if readahead > 0 {
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index e6164b221..7146d7b6f 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -307,10 +307,15 @@ impl DecodedFrame {
}
/// NV12 frame that never left GPU memory (NVDEC on Linux render hosts).
+ /// `storage` is the decoder's per-frame allocation: layers compare it to
+ /// skip re-uploading a frame they already hold (VFR holds, fps upsampling).
#[cfg(target_os = "linux")]
- pub fn new_nv12_cuda(frame: Arc<crate::linux_gpu::CudaNv12Frame>) -> Self {
+ pub fn new_nv12_cuda(
+ frame: Arc<crate::linux_gpu::CudaNv12Frame>,
+ storage: Arc<Vec<u8>>,
+ ) -> Self {
Self {
- data: Arc::new(Vec::new()),
+ data: storage,
width: frame.width,
height: frame.height,
format: PixelFormat::Nv12,
diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rs
index 2fcf4df67..9f36daa88 100644
--- a/crates/rendering/src/layers/camera.rs
+++ b/crates/rendering/src/layers/camera.rs
@@ -34,6 +34,14 @@ struct BlurCacheEntry {
}
impl CameraLayer {
+ /// Forget the last frame shown, as a new layer would: the next render of
+ /// a reused layer set starts somewhere else in the recording.
+ pub(crate) fn reset_frame_state(&mut self) {
+ self.last_recording_time = None;
+ self.last_frame_storage = None;
+ self.blur_cache = None;
+ }
+
#[allow(dead_code)]
pub fn new(device: &wgpu::Device) -> Self {
Self::new_with_all_shared_pipelines(
diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rs
index 3a8c53a91..ad7575b64 100644
--- a/crates/rendering/src/layers/display.rs
+++ b/crates/rendering/src/layers/display.rs
@@ -31,6 +31,13 @@ pub struct DisplayLayer {
}
impl DisplayLayer {
+ /// Forget the last frame shown, as a new layer would.
+ pub(crate) fn reset_frame_state(&mut self) {
+ self.last_recording_time = None;
+ self.last_frame_storage = None;
+ self.has_valid_frame = false;
+ }
+
#[allow(dead_code)]
pub fn new(device: &wgpu::Device) -> Self {
Self::new_with_options(device, false)
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index f16fd4fc8..0a47bb46a 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1264,6 +1264,10 @@ pub async fn render_video_to_channel_nv12(
let mut layers = layers_reuse_key
.as_deref()
.and_then(|key| take_pooled_layers(&constants.device, key))
+ .map(|mut layers| {
+ layers.reset_frame_state();
+ layers
+ })
.unwrap_or_else(|| {
RendererLayers::new_with_options(
&constants.device,
@@ -6935,6 +6939,12 @@ pub struct RendererLayers {
}
impl RendererLayers {
+ fn reset_frame_state(&mut self) {
+ self.display.reset_frame_state();
+ self.camera.reset_frame_state();
+ self.camera_only.reset_frame_state();
+ }
+
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
Self::new_with_options(device, queue, false)
}
diff --git a/crates/rendering/src/linux_gpu.rs b/crates/rendering/src/linux_gpu.rs
index f0bf2fecd..5a0d5b691 100644
--- a/crates/rendering/src/linux_gpu.rs
+++ b/crates/rendering/src/linux_gpu.rs
@@ -15,6 +15,17 @@ use std::{
},
};
+static INTEROP_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+pub fn note_interop_failure() {
+ INTEROP_FAILURES.fetch_add(1, Ordering::Relaxed);
+}
+
+/// CUDA frames that failed to reach the compositor since the last call.
+pub fn take_interop_failures() -> u64 {
+ INTEROP_FAILURES.swap(0, Ordering::Relaxed)
+}
+
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"))
@@ -77,6 +88,7 @@ struct Cuda {
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,
+ stream_destroy: 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,
@@ -138,6 +150,7 @@ impl Cuda {
memcpy_2d_async: symbol!(b"cuMemcpy2DAsync_v2\0"),
stream_create: symbol!(b"cuStreamCreate\0"),
stream_synchronize: symbol!(b"cuStreamSynchronize\0"),
+ stream_destroy: symbol!(b"cuStreamDestroy_v2\0"),
mem_get_info: symbol!(b"cuMemGetInfo_v2\0"),
import_external_memory: symbol!(b"cuImportExternalMemory\0"),
external_memory_mapped_buffer: symbol!(b"cuExternalMemoryGetMappedBuffer\0"),
@@ -201,20 +214,38 @@ pub fn copy_plane(
/// 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.
+/// Encoder threads are created per chunk; destroying the stream with the
+/// thread keeps a long-lived engine from leaking one per chunk.
+struct ThreadStream(std::cell::Cell<CuStream>);
+
+impl Drop for ThreadStream {
+ fn drop(&mut self) {
+ let stream = self.0.get();
+ if stream.is_null() {
+ return;
+ }
+ if let Ok(driver) = cuda() {
+ let _ = driver.with_context(|| unsafe {
+ check((driver.stream_destroy)(stream), "cuStreamDestroy")
+ });
+ }
+ }
+}
+
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()) };
+ static STREAM: ThreadStream = const { ThreadStream(std::cell::Cell::new(std::ptr::null_mut())) };
}
STREAM.with(|slot| {
- if slot.get().is_null() {
+ if slot.0.get().is_null() {
let mut stream = std::ptr::null_mut();
check(
unsafe { (cuda.stream_create)(&mut stream, 0) },
"cuStreamCreate",
)?;
- slot.set(stream);
+ slot.0.set(stream);
}
- Ok(slot.get())
+ Ok(slot.0.get())
})
}
@@ -411,19 +442,24 @@ pub fn memory_stats() -> (usize, usize, u64) {
(ALLOCATED.load(Ordering::Relaxed), pooled, free)
}
+/// Pool buffers come in power-of-two sizes: every source resolution and
+/// output size would otherwise add its own set of buffers that the pool keeps
+/// forever, while callers only need a buffer at least as large as asked.
+fn pool_size_class(size: u64) -> u64 {
+ size.max(4096).next_power_of_two()
+}
+
fn pooled_buffer(device: &wgpu::Device, size: u64, label: &str) -> Result<SharedBuffer, String> {
+ let class = pool_size_class(size);
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)
- })
+ .position(|(owner, buffer)| owner == device && buffer.size == class)
{
return Ok(pool.swap_remove(index).1);
}
ALLOCATED.fetch_add(1, Ordering::Relaxed);
- SharedBuffer::new(device, size, label)
+ SharedBuffer::new(device, class, label)
}
/// The buffer goes back to the pool when the slot's last reference drops:
@@ -546,3 +582,17 @@ impl Drop for GpuNv12Output {
self.slot.release();
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::pool_size_class;
+
+ #[test]
+ fn pool_sizes_collapse_into_power_of_two_classes() {
+ assert_eq!(pool_size_class(1), 4096);
+ assert_eq!(pool_size_class(3_110_400), 4 << 20);
+ assert_eq!(pool_size_class(12_441_600), 16 << 20);
+ assert_eq!(pool_size_class(16 << 20), 16 << 20);
+ assert!((3_000_000..4_000_000).all(|size| pool_size_class(size) == 4 << 20));
+ }
+}
diff --git a/crates/rendering/src/yuv_converter.rs b/crates/rendering/src/yuv_converter.rs
index fd187ccbf..4bd420ddb 100644
--- a/crates/rendering/src/yuv_converter.rs
+++ b/crates/rendering/src/yuv_converter.rs
@@ -513,6 +513,20 @@ impl YuvToRgbaConverter {
device: &wgpu::Device,
queue: &wgpu::Queue,
frame: &crate::linux_gpu::CudaNv12Frame,
+ ) -> Result<&wgpu::TextureView, YuvConversionError> {
+ // There is no CPU copy of a CUDA frame to fall back to, so a failed
+ // conversion leaves the previous texture on screen; count it so the
+ // caller can reject the render instead of encoding stale frames.
+ self.convert_nv12_cuda_into_textures(device, queue, frame)
+ .inspect_err(|_| crate::linux_gpu::note_interop_failure())
+ }
+
+ #[cfg(target_os = "linux")]
+ fn convert_nv12_cuda_into_textures(
+ &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;