From e3c1b28f44ce851299684879ccc8932214c53079 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 30 Oct 2026 09:30:24 -0400 Subject: [PATCH 1/4] feat(cli): render --start and --end render only that span of the film as its own MP4 The span reuses the chunked render path, so frames are captured at their absolute times and sub-composition timing matches a full render. --- docs/packages/cli.mdx | 1 + packages/cli/src/commands/render.ts | 82 ++++++++++++- packages/cli/src/commands/render/execute.ts | 2 + packages/cli/src/commands/render/plan.test.ts | 24 ++++ packages/cli/src/commands/render/plan.ts | 54 +++++++++ packages/cli/src/utils/dockerRunArgs.ts | 8 ++ packages/producer/src/index.ts | 6 + .../services/distributed/renderSpan.test.ts | 108 ++++++++++++++++++ .../src/services/distributed/renderSpan.ts | 92 +++++++++++++++ 9 files changed, 376 insertions(+), 1 deletion(-) create mode 100644 packages/producer/src/services/distributed/renderSpan.test.ts create mode 100644 packages/producer/src/services/distributed/renderSpan.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 4a19decda5b..9826314b740 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1674,6 +1674,7 @@ Quality and file size: | `--crf` | from `--quality`| Override MP4/WebM encoder CRF, 0–51. Lower is better quality. Not with `--video-bitrate`; rejected for MOV. | | `--video-bitrate` | from `--quality`| Target MP4/WebM bitrate, e.g. `10M` or `5000k`. Not with `--crf`; rejected for MOV. | | `--keyframe-interval` | encoder default | MP4 only. A keyframe at least every N seconds, e.g. `2`, so a player can seek or switch rendition at that spacing. | +| `--start`, `--end` | whole film | Render only the seconds between them, as an MP4 that starts at 0 with that span's audio. MP4 at 24, 25, 30 or 60 fps, SDR only. | | `--max-bitrate` | uncapped | MP4 only. Peak video bitrate cap, e.g. `8M`, held alongside the `--crf` or `--quality` target rather than replacing it. | | `--buffer-size` | 2 × `--max-bitrate` | MP4 only. Buffer the cap is measured over, e.g. `16M`. Needs `--max-bitrate`. | | `--vp9-cpu-used` | encoder default | libvpx-vp9 speed/quality trade-off for WebM, -8 to 8. Env: `PRODUCER_VP9_CPU_USED`. | diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index b36e6afc3e7..b687b785e34 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -4,7 +4,12 @@ import { failCommand, requestCliExit, scheduleCliExit } from "../utils/commandRe import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import { mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync, rmSync } from "node:fs"; -import { createRenderPlan, resolveBrowserGpuForCli, type RenderFormat } from "./render/plan.js"; +import { + createRenderPlan, + resolveBrowserGpuForCli, + type RenderFormat, + type RenderRange, +} from "./render/plan.js"; import { seedProjectAuthoringSkill } from "../utils/projectConfig.js"; import { deliveryFlagArgs } from "../utils/deliveryFlags.js"; import type { CatalogUsage } from "../utils/catalogUsage.js"; @@ -263,6 +268,16 @@ export default defineCommand({ description: "Override MP4/WebM encoder CRF. Mutually exclusive with --video-bitrate; unsupported for MOV.", }, + start: { + type: "string", + description: + "Render from this second of the film (MP4). The clip starts at 0 and carries the audio of the span.", + }, + end: { + type: "string", + description: + "Render up to this second of the film (default: the end). Needs MP4, a whole frame rate of 24, 25, 30 or 60, and SDR.", + }, "video-bitrate": { type: "string", description: @@ -526,6 +541,7 @@ export interface RenderOptions { vp9CpuUsed?: number; videoBitrate?: string; keyframeIntervalSeconds?: number; + range?: RenderRange; proresProfile?: ProresProfile; maxBitrate?: string; bufferSize?: string; @@ -861,6 +877,7 @@ async function renderDocker( vp9CpuUsed: options.vp9CpuUsed, videoBitrate: options.videoBitrate, keyframeIntervalSeconds: options.keyframeIntervalSeconds, + range: options.range, proresProfile: options.proresProfile, maxBitrate: options.maxBitrate, bufferSize: options.bufferSize, @@ -1160,8 +1177,23 @@ async function executeLocalRender( resumeSegments: options.resumeSegments, keepSegments: options.keepSegments, strictness: options.bestEffort === false ? "strict" : "best-effort", + distributed: options.range ? { width: 1920, height: 1080 } : undefined, }, }); + if (options.range) { + return renderRange({ + producer, + request, + range: options.range, + projectDir, + outputPath, + options, + logger, + startTime, + cpu, + signal: cancellation.signal, + }); + } const job = producer.createRenderJob(producer.renderConfigFromRequest(request, { logger })); const onProgress = options.quiet @@ -1261,6 +1293,54 @@ async function executeLocalRender( }; } +async function renderRange(input: { + producer: Awaited>; + request: ReturnType>["createRenderRequest"]>; + range: RenderRange; + projectDir: string; + outputPath: string; + options: RenderOptions; + logger: ProducerLogger; + startTime: number; + cpu: RenderCpuSampler; + signal: AbortSignal; +}): Promise { + const { producer, options } = input; + let framesEncoded = 0; + try { + const config = producer.distributedConfigFromRequest(input.request, { + logger: input.logger, + abortSignal: input.signal, + }); + ({ framesEncoded } = await producer.renderSpan( + input.projectDir, + config, + input.range, + input.outputPath, + )); + } catch (error: unknown) { + handleRenderError(error, options, input.startTime, input.cpu, false, ""); + } + markRenderSucceeded(); + const elapsed = Date.now() - input.startTime; + input.cpu.stop(); + printRenderComplete({ + outputPath: input.outputPath, + projectDir: input.projectDir, + desktopHint: wantsDesktopHint(options), + elapsedMs: elapsed, + quiet: options.quiet, + format: options.format, + }); + if (options.exitAfterComplete) scheduleCliExit(); + return { + renderTimeMs: elapsed, + durationMs: Math.round((framesEncoded / fpsToNumber(options.fps)) * 1000), + outcome: "completed", + warnings: [], + }; +} + function getMemorySnapshot() { return { peakMemoryMb: bytesToMb(process.memoryUsage.rss()), diff --git a/packages/cli/src/commands/render/execute.ts b/packages/cli/src/commands/render/execute.ts index 2e51075b553..d5b16af90ea 100644 --- a/packages/cli/src/commands/render/execute.ts +++ b/packages/cli/src/commands/render/execute.ts @@ -162,6 +162,7 @@ export function renderOptionsFromPlan( vp9CpuUsed: plan.vp9CpuUsed, videoBitrate: plan.videoBitrate, keyframeIntervalSeconds: plan.keyframeIntervalSeconds, + range: plan.range, proresProfile: plan.proresProfile, maxBitrate: plan.maxBitrate, bufferSize: plan.bufferSize, @@ -376,6 +377,7 @@ export function batchRowRenderOptions( vp9CpuUsed: plan.vp9CpuUsed, videoBitrate: plan.videoBitrate, keyframeIntervalSeconds: plan.keyframeIntervalSeconds, + range: plan.range, proresProfile: plan.proresProfile, maxBitrate: plan.maxBitrate, bufferSize: plan.bufferSize, diff --git a/packages/cli/src/commands/render/plan.test.ts b/packages/cli/src/commands/render/plan.test.ts index 89cbd2b8cb2..2a517bca208 100644 --- a/packages/cli/src/commands/render/plan.test.ts +++ b/packages/cli/src/commands/render/plan.test.ts @@ -254,6 +254,30 @@ describe("createRenderPlan", () => { } }); + it("carries --start and --end into the plan, and refuses what a range cannot render", () => { + expect(createRenderPlan({ dir: projectDir, start: "2.5", end: "6" }).range).toEqual({ + startSeconds: 2.5, + endSeconds: 6, + }); + expect(createRenderPlan({ dir: projectDir, end: "4" }).range).toEqual({ + startSeconds: 0, + endSeconds: 4, + }); + expect(createRenderPlan({ dir: projectDir }).range).toBeUndefined(); + const refused: Array> = [ + { start: "-1" }, + { start: "abc" }, + { start: "5", end: "5" }, + { start: "1", format: "webm" }, + { start: "1", fps: "29.97" }, + { start: "1", fps: "50" }, + { start: "1", hdr: true }, + ]; + for (const flags of refused) { + expect(() => createRenderPlan({ dir: projectDir, ...flags })).toThrow(CliUsageError); + } + }); + it("rejects batch and single-render variables before execution", () => { expect(() => createRenderPlan({ dir: projectDir, batch: "rows.json", variables: '{"name":"Ada"}' }), diff --git a/packages/cli/src/commands/render/plan.ts b/packages/cli/src/commands/render/plan.ts index 2df7d830d17..5247008e339 100644 --- a/packages/cli/src/commands/render/plan.ts +++ b/packages/cli/src/commands/render/plan.ts @@ -1,9 +1,11 @@ import { statSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { + DISTRIBUTED_FPS, formatRenderOutputTimestamp, fpsToNumber, isAspectAgnosticResolutionAlias, + isDistributedFps, normalizeResolutionFlag, parseFps, type CanvasResolution, @@ -84,6 +86,8 @@ export interface RenderCommandArgs { hdr?: boolean; sdr?: boolean; crf?: string; + start?: string; + end?: string; "video-bitrate"?: string; "keyframe-interval"?: string; "max-bitrate"?: string; @@ -168,6 +172,7 @@ export interface RenderPlan { vp9CpuUsed?: number; videoBitrate?: string; keyframeIntervalSeconds?: number; + range?: RenderRange; proresProfile?: ProresProfile; maxBitrate?: string; bufferSize?: string; @@ -207,6 +212,53 @@ function parseRenderFormat(input: string): RenderFormat | undefined { return RENDER_FORMATS.find((format) => format === input); } +export interface RenderRange { + startSeconds: number; + endSeconds?: number; +} + +function parseRenderRange( + args: Pick, + format: RenderFormat, + fps: Fps, + hdr: boolean | undefined, +): RenderRange | undefined { + if (args.start === undefined && args.end === undefined) return undefined; + const seconds = (flag: string, raw: string): number => { + const parsed = raw.trim() === "" ? Number.NaN : Number(raw); + if (!Number.isFinite(parsed) || parsed < 0) { + errorBox(`Invalid ${flag}`, `Got "${raw}". Must be a number of seconds, 0 or more.`); + failUsage(); + } + return parsed; + }; + const startSeconds = args.start === undefined ? 0 : seconds("--start", args.start); + const endSeconds = args.end === undefined ? undefined : seconds("--end", args.end); + if (endSeconds !== undefined && endSeconds <= startSeconds) { + errorBox("Invalid range", `--end (${endSeconds}) must be after --start (${startSeconds}).`); + failUsage(); + } + const limit = rangeLimit(format, fps, hdr); + if (limit) { + errorBox( + "A range renders what chunked renders can", + limit, + "Remove --start/--end to render the whole film.", + ); + failUsage(); + } + return { startSeconds, endSeconds }; +} + +function rangeLimit(format: RenderFormat, fps: Fps, hdr: boolean | undefined): string | undefined { + if (format !== "mp4") return `--start/--end render MP4 only, not ${format}.`; + if (fps.den !== 1 || !isDistributedFps(fps.num)) { + return `--start/--end need a whole frame rate in ${DISTRIBUTED_FPS.join(", ")}, not ${fps.num}/${fps.den}.`; + } + if (hdr) return "--start/--end render SDR only, not --hdr."; + return undefined; +} + function positiveInteger(raw: string, title: string, message: string, min = 1): number { const parsed = Number(raw); if (!Number.isInteger(parsed) || parsed < min) { @@ -545,6 +597,7 @@ export function createRenderPlan(args: RenderCommandArgs, now = new Date()): Ren failUsage(); } + const range = parseRenderRange(args, format, fps, args.hdr); const quiet = args.quiet ?? false; const batchJson = args.json ?? false; return Object.freeze({ @@ -592,6 +645,7 @@ export function createRenderPlan(args: RenderCommandArgs, now = new Date()): Ren vp9CpuUsed, videoBitrate, ...delivery, + range, hdrMode: args.sdr ? "force-sdr" : args.hdr ? "force-hdr" : "auto", pageSideCompositing: args["page-side-compositing"] !== false, experimentalFastCapture: args["experimental-fast-capture"] === true, diff --git a/packages/cli/src/utils/dockerRunArgs.ts b/packages/cli/src/utils/dockerRunArgs.ts index 16d8b671614..bcd1faeaf25 100644 --- a/packages/cli/src/utils/dockerRunArgs.ts +++ b/packages/cli/src/utils/dockerRunArgs.ts @@ -51,6 +51,7 @@ export interface DockerRenderOptions { vp9CpuUsed?: number; videoBitrate?: string; keyframeIntervalSeconds?: number; + range?: { startSeconds: number; endSeconds?: number }; proresProfile?: string; maxBitrate?: string; bufferSize?: string; @@ -148,6 +149,13 @@ export function buildDockerRunArgs(input: DockerRunArgsInput): string[] { ...(options.vp9CpuUsed != null ? ["--vp9-cpu-used", String(options.vp9CpuUsed)] : []), ...(options.videoBitrate ? ["--video-bitrate", options.videoBitrate] : []), ...(options.proresProfile ? ["--prores-profile", options.proresProfile] : []), + ...(options.range + ? [ + "--start", + String(options.range.startSeconds), + ...(options.range.endSeconds != null ? ["--end", String(options.range.endSeconds)] : []), + ] + : []), ...(options.keyframeIntervalSeconds != null ? ["--keyframe-interval", String(options.keyframeIntervalSeconds)] : []), diff --git a/packages/producer/src/index.ts b/packages/producer/src/index.ts index 3ea7e361fbe..1af687c2939 100644 --- a/packages/producer/src/index.ts +++ b/packages/producer/src/index.ts @@ -24,6 +24,12 @@ export { type RenderPerfSummary, type ProgressCallback, } from "./services/renderOrchestrator.js"; +export { + renderSpan, + RenderSpanUnsupportedError, + spanFrameRange, + type RenderSpanResult, +} from "./services/distributed/renderSpan.js"; export { extractSafeRenderErrorCode } from "./services/safeRenderErrorCode.js"; export { RENDER_JOB_DIR, diff --git a/packages/producer/src/services/distributed/renderSpan.test.ts b/packages/producer/src/services/distributed/renderSpan.test.ts new file mode 100644 index 00000000000..60f494e62f0 --- /dev/null +++ b/packages/producer/src/services/distributed/renderSpan.test.ts @@ -0,0 +1,108 @@ +import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createRenderJob, executeRenderJob } from "../renderOrchestrator.js"; +import { renderSpan, RenderSpanUnsupportedError, spanFrameRange } from "./renderSpan.js"; + +describe("spanFrameRange", () => { + it("is the frames the seconds cover, to the end when --end is absent", () => { + expect(spanFrameRange(0.5, 1.5, 30, 90)).toEqual({ startFrame: 15, endFrame: 45 }); + expect(spanFrameRange(1, undefined, 30, 90)).toEqual({ startFrame: 30, endFrame: 90 }); + }); + + it("stops at the last frame of the film", () => { + expect(spanFrameRange(2, 9, 30, 90)).toEqual({ startFrame: 60, endFrame: 90 }); + }); + + it("refuses a range with no frame, naming how long the film is", () => { + expect(() => spanFrameRange(3, 4, 30, 90)).toThrow(RenderSpanUnsupportedError); + expect(() => spanFrameRange(3, 4, 30, 90)).toThrow("90 frames at 30 fps (3s)"); + }); +}); + +const ROOT_HTML = ` + + + +
+
+
+
+
+ +`; + +const SUB_HTML = ``; + +function frames(path: string): Buffer[] { + const out = spawnSync( + "ffmpeg", + ["-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], + { maxBuffer: 1 << 28 }, + ); + const size = 160 * 90 * 3; + const all = out.stdout; + return Array.from({ length: Math.floor(all.length / size) }, (_, i) => + all.subarray(i * size, (i + 1) * size), + ); +} + +function meanDiff(a: Buffer, b: Buffer): number { + let sum = 0; + for (let i = 0; i < a.length; i++) sum += Math.abs(a[i]! - b[i]!); + return sum / a.length; +} + +describe("renderSpan", () => { + let root: string; + let projectDir: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "hf-render-span-")); + projectDir = join(root, "project"); + mkdirSync(join(projectDir, "compositions"), { recursive: true }); + writeFileSync(join(projectDir, "index.html"), ROOT_HTML); + writeFileSync(join(projectDir, "compositions", "sub.html"), SUB_HTML); + }); + + afterAll(() => rmSync(root, { recursive: true, force: true })); + + it("renders the frames of the span the way a full render renders them, sub-composition included", async () => { + const fullPath = join(root, "full.mp4"); + const job = createRenderJob({ fps: { num: 30, den: 1 }, quality: "draft", format: "mp4" }); + await executeRenderJob(job, projectDir, fullPath); + + const spanPath = join(root, "span.mp4"); + const { framesEncoded } = await renderSpan( + projectDir, + { fps: 30, width: 160, height: 90, format: "mp4", quality: "draft", hdrMode: "force-sdr" }, + { startSeconds: 0.5, endSeconds: 2 }, + spanPath, + ); + expect(framesEncoded).toBe(45); + + const full = frames(fullPath); + const span = frames(spanPath); + expect(span.length).toBe(45); + const worstMatch = Math.max(...span.map((frame, i) => meanDiff(frame, full[15 + i]!))); + // The backdrop brightens about 2.8 levels a frame, so a span one frame off its place misses by more than this. + expect(worstMatch).toBeLessThan(1.5); + const oneFrameLate = span.map((frame, i) => meanDiff(frame, full[16 + i]!)); + expect(Math.min(...oneFrameLate)).toBeGreaterThan(worstMatch); + }, 240_000); +}); diff --git a/packages/producer/src/services/distributed/renderSpan.ts b/packages/producer/src/services/distributed/renderSpan.ts new file mode 100644 index 00000000000..45540f057d1 --- /dev/null +++ b/packages/producer/src/services/distributed/renderSpan.ts @@ -0,0 +1,92 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { ChunkSliceJson } from "../render/stages/freezePlan.js"; +import { writeStitchedMp4 } from "./mp4Stitch.js"; +import { plan, type DistributedRenderConfig } from "./plan.js"; +import { renderChunk } from "./renderChunk.js"; + +export interface RenderSpanResult { + startFrame: number; + endFrame: number; + framesEncoded: number; +} + +export class RenderSpanUnsupportedError extends Error { + constructor(message: string) { + super(message); + this.name = "RenderSpanUnsupportedError"; + } +} + +/** The frames `[startFrame, endFrame)` of a `totalFrames` timeline that `[startSeconds, endSeconds)` covers. */ +export function spanFrameRange( + startSeconds: number, + endSeconds: number | undefined, + fps: number, + totalFrames: number, +): { startFrame: number; endFrame: number } { + const startFrame = Math.round(startSeconds * fps); + const endFrame = Math.min( + endSeconds === undefined ? totalFrames : Math.round(endSeconds * fps), + totalFrames, + ); + if (!(endFrame > startFrame)) { + throw new RenderSpanUnsupportedError( + `The range ${startSeconds}s to ${endSeconds ?? "the end"}s holds no frame: the composition has ${totalFrames} frames at ${fps} fps (${totalFrames / fps}s).`, + ); + } + return { startFrame, endFrame }; +} + +/** + * Renders only `[startSeconds, endSeconds)` of a composition as a standalone mp4 that starts at 0, + * with the audio of that span. It plans the whole composition, renders just the frames of the span + * (a chunk's sub-range renders as a chunk of its own, at the frames' absolute times), and joins them. + */ +export async function renderSpan( + projectDir: string, + config: DistributedRenderConfig, + span: { startSeconds: number; endSeconds?: number }, + outputPath: string, +): Promise { + if (config.format !== "mp4") { + throw new RenderSpanUnsupportedError( + `--start/--end render mp4 only; ${config.format} is not supported for a range.`, + ); + } + if (config.cfr === true) { + throw new RenderSpanUnsupportedError("--start/--end cannot be combined with a cfr re-encode."); + } + const workDir = mkdtempSync(join(tmpdir(), "hf-render-span-")); + try { + const planDir = join(workDir, "plan"); + const partsDir = join(workDir, "parts"); + mkdirSync(partsDir, { recursive: true }); + const planned = await plan(projectDir, config, planDir, { chunksCarryAudio: true }); + const { startFrame, endFrame } = spanFrameRange( + span.startSeconds, + span.endSeconds, + config.fps, + planned.totalFrames, + ); + const slices = JSON.parse( + readFileSync(join(planDir, "meta", "chunks.json"), "utf-8"), + ) as ChunkSliceJson[]; + const parts: string[] = []; + for (const slice of slices) { + const range = { + startFrame: Math.max(slice.startFrame, startFrame), + endFrame: Math.min(slice.endFrame, endFrame), + }; + if (range.endFrame <= range.startFrame) continue; + const part = join(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`); + await renderChunk(planDir, slice.index, part, { frameRange: range }); + parts.push(part); + } + await writeStitchedMp4(parts, outputPath); + return { startFrame, endFrame, framesEncoded: endFrame - startFrame }; + } finally { + rmSync(workDir, { recursive: true, force: true }); + } +} From 2d0449df2c99b53d1ae7631a93bf654fa8195b60 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 30 Oct 2026 09:31:03 -0400 Subject: [PATCH 2/4] chore(producer): shorten the renderSpan comment --- packages/producer/src/services/distributed/renderSpan.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/producer/src/services/distributed/renderSpan.ts b/packages/producer/src/services/distributed/renderSpan.ts index 45540f057d1..aa0f76dcb91 100644 --- a/packages/producer/src/services/distributed/renderSpan.ts +++ b/packages/producer/src/services/distributed/renderSpan.ts @@ -39,11 +39,7 @@ export function spanFrameRange( return { startFrame, endFrame }; } -/** - * Renders only `[startSeconds, endSeconds)` of a composition as a standalone mp4 that starts at 0, - * with the audio of that span. It plans the whole composition, renders just the frames of the span - * (a chunk's sub-range renders as a chunk of its own, at the frames' absolute times), and joins them. - */ +/** Renders `[startSeconds, endSeconds)` as a standalone mp4 from 0, with that span's audio, by chunk sub-ranges. */ export async function renderSpan( projectDir: string, config: DistributedRenderConfig, From 3470a3477b2675cbe7fa836360bdbbc1bf4c1590 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 30 Oct 2026 10:13:08 -0400 Subject: [PATCH 3/4] fix(producer): a cancelled span render stops, and its real-render test runs in the integration lane renderSpan checks the abort signal before each chunk part and before the stitch. The real-render tests move to their own file listed in the integration lane. --- packages/cli/src/commands/render.ts | 1 + .../producer/scripts/integration-tests.json | 1 + .../renderSpan.integration.test.ts | 129 ++++++++++++++++++ .../services/distributed/renderSpan.test.ts | 94 +------------ .../src/services/distributed/renderSpan.ts | 15 +- 5 files changed, 147 insertions(+), 93 deletions(-) create mode 100644 packages/producer/src/services/distributed/renderSpan.integration.test.ts diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index b687b785e34..7dbf5fd5f49 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -1177,6 +1177,7 @@ async function executeLocalRender( resumeSegments: options.resumeSegments, keepSegments: options.keepSegments, strictness: options.bestEffort === false ? "strict" : "best-effort", + // plan() takes the film's own size; these only satisfy the request shape. distributed: options.range ? { width: 1920, height: 1080 } : undefined, }, }); diff --git a/packages/producer/scripts/integration-tests.json b/packages/producer/scripts/integration-tests.json index 1c5a9be9446..3c0ce782cc3 100644 --- a/packages/producer/scripts/integration-tests.json +++ b/packages/producer/scripts/integration-tests.json @@ -16,6 +16,7 @@ "src/services/distributed/planSizeCap.test.ts", "src/services/distributed/planV2RemoteFiles.test.ts", "src/services/distributed/renderChunk.test.ts", + "src/services/distributed/renderSpan.integration.test.ts", "src/services/fileServer.test.ts", "src/services/fileServer.file-race.test.ts", "src/services/fileServer.listenError.test.ts", diff --git a/packages/producer/src/services/distributed/renderSpan.integration.test.ts b/packages/producer/src/services/distributed/renderSpan.integration.test.ts new file mode 100644 index 00000000000..db28a2abcc1 --- /dev/null +++ b/packages/producer/src/services/distributed/renderSpan.integration.test.ts @@ -0,0 +1,129 @@ +import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createRenderJob, executeRenderJob, RenderCancelledError } from "../renderOrchestrator.js"; +import { renderSpan } from "./renderSpan.js"; + +const ROOT_HTML = ` + + + +
+
+
+
+
+ +`; + +const SUB_HTML = ``; + +function frames(path: string): Buffer[] { + const out = spawnSync( + "ffmpeg", + ["-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], + { maxBuffer: 1 << 28 }, + ); + const size = 160 * 90 * 3; + const all = out.stdout; + return Array.from({ length: Math.floor(all.length / size) }, (_, i) => + all.subarray(i * size, (i + 1) * size), + ); +} + +function meanDiff(a: Buffer, b: Buffer): number { + let sum = 0; + for (let i = 0; i < a.length; i++) sum += Math.abs(a[i]! - b[i]!); + return sum / a.length; +} + +describe("renderSpan", () => { + let root: string; + let projectDir: string; + + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "hf-render-span-")); + projectDir = join(root, "project"); + mkdirSync(join(projectDir, "compositions"), { recursive: true }); + writeFileSync(join(projectDir, "index.html"), ROOT_HTML); + writeFileSync(join(projectDir, "compositions", "sub.html"), SUB_HTML); + }); + + afterAll(() => rmSync(root, { recursive: true, force: true })); + + it("renders the frames of the span the way a full render renders them, sub-composition included", async () => { + const fullPath = join(root, "full.mp4"); + const job = createRenderJob({ fps: { num: 30, den: 1 }, quality: "draft", format: "mp4" }); + await executeRenderJob(job, projectDir, fullPath); + + const spanPath = join(root, "span.mp4"); + const { framesEncoded } = await renderSpan( + projectDir, + { fps: 30, width: 160, height: 90, format: "mp4", quality: "draft", hdrMode: "force-sdr" }, + { startSeconds: 0.5, endSeconds: 2 }, + spanPath, + ); + expect(framesEncoded).toBe(45); + + const full = frames(fullPath); + const span = frames(spanPath); + expect(span.length).toBe(45); + const worstMatch = Math.max(...span.map((frame, i) => meanDiff(frame, full[15 + i]!))); + // The backdrop brightens about 2.8 levels a frame, so a span one frame off its place misses by more than this. + expect(worstMatch).toBeLessThan(1.5); + const oneFrameLate = span.map((frame, i) => meanDiff(frame, full[16 + i]!)); + expect(Math.min(...oneFrameLate)).toBeGreaterThan(worstMatch); + }, 240_000); + + it("stops when it is cancelled after planning, with no output written", async () => { + const scratch = join(root, "scratch"); + mkdirSync(scratch, { recursive: true }); + const previousTmp = process.env.TMPDIR; + process.env.TMPDIR = scratch; + const controller = new AbortController(); + const outputPath = join(root, "cancelled.mp4"); + try { + const running = renderSpan( + projectDir, + { + fps: 30, + width: 160, + height: 90, + format: "mp4", + quality: "draft", + hdrMode: "force-sdr", + chunkSize: 15, + abortSignal: controller.signal, + }, + { startSeconds: 0 }, + outputPath, + ); + const firstPart = () => + readdirSync(scratch).some((dir) => + existsSync(join(scratch, dir, "parts", "part-0000.mp4")), + ); + while (!firstPart()) await new Promise((done) => setTimeout(done, 20)); + controller.abort(); + await expect(running).rejects.toBeInstanceOf(RenderCancelledError); + expect(existsSync(outputPath)).toBe(false); + } finally { + if (previousTmp === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = previousTmp; + } + }, 240_000); +}); diff --git a/packages/producer/src/services/distributed/renderSpan.test.ts b/packages/producer/src/services/distributed/renderSpan.test.ts index 60f494e62f0..c09b5922773 100644 --- a/packages/producer/src/services/distributed/renderSpan.test.ts +++ b/packages/producer/src/services/distributed/renderSpan.test.ts @@ -1,10 +1,5 @@ -import { afterAll, beforeAll, describe, expect, it } from "bun:test"; -import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { createRenderJob, executeRenderJob } from "../renderOrchestrator.js"; -import { renderSpan, RenderSpanUnsupportedError, spanFrameRange } from "./renderSpan.js"; +import { describe, expect, it } from "bun:test"; +import { RenderSpanUnsupportedError, spanFrameRange } from "./renderSpan.js"; describe("spanFrameRange", () => { it("is the frames the seconds cover, to the end when --end is absent", () => { @@ -21,88 +16,3 @@ describe("spanFrameRange", () => { expect(() => spanFrameRange(3, 4, 30, 90)).toThrow("90 frames at 30 fps (3s)"); }); }); - -const ROOT_HTML = ` - - - -
-
-
-
-
- -`; - -const SUB_HTML = ``; - -function frames(path: string): Buffer[] { - const out = spawnSync( - "ffmpeg", - ["-v", "error", "-i", path, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], - { maxBuffer: 1 << 28 }, - ); - const size = 160 * 90 * 3; - const all = out.stdout; - return Array.from({ length: Math.floor(all.length / size) }, (_, i) => - all.subarray(i * size, (i + 1) * size), - ); -} - -function meanDiff(a: Buffer, b: Buffer): number { - let sum = 0; - for (let i = 0; i < a.length; i++) sum += Math.abs(a[i]! - b[i]!); - return sum / a.length; -} - -describe("renderSpan", () => { - let root: string; - let projectDir: string; - - beforeAll(() => { - root = mkdtempSync(join(tmpdir(), "hf-render-span-")); - projectDir = join(root, "project"); - mkdirSync(join(projectDir, "compositions"), { recursive: true }); - writeFileSync(join(projectDir, "index.html"), ROOT_HTML); - writeFileSync(join(projectDir, "compositions", "sub.html"), SUB_HTML); - }); - - afterAll(() => rmSync(root, { recursive: true, force: true })); - - it("renders the frames of the span the way a full render renders them, sub-composition included", async () => { - const fullPath = join(root, "full.mp4"); - const job = createRenderJob({ fps: { num: 30, den: 1 }, quality: "draft", format: "mp4" }); - await executeRenderJob(job, projectDir, fullPath); - - const spanPath = join(root, "span.mp4"); - const { framesEncoded } = await renderSpan( - projectDir, - { fps: 30, width: 160, height: 90, format: "mp4", quality: "draft", hdrMode: "force-sdr" }, - { startSeconds: 0.5, endSeconds: 2 }, - spanPath, - ); - expect(framesEncoded).toBe(45); - - const full = frames(fullPath); - const span = frames(spanPath); - expect(span.length).toBe(45); - const worstMatch = Math.max(...span.map((frame, i) => meanDiff(frame, full[15 + i]!))); - // The backdrop brightens about 2.8 levels a frame, so a span one frame off its place misses by more than this. - expect(worstMatch).toBeLessThan(1.5); - const oneFrameLate = span.map((frame, i) => meanDiff(frame, full[16 + i]!)); - expect(Math.min(...oneFrameLate)).toBeGreaterThan(worstMatch); - }, 240_000); -}); diff --git a/packages/producer/src/services/distributed/renderSpan.ts b/packages/producer/src/services/distributed/renderSpan.ts index aa0f76dcb91..d384e4c37b5 100644 --- a/packages/producer/src/services/distributed/renderSpan.ts +++ b/packages/producer/src/services/distributed/renderSpan.ts @@ -5,6 +5,7 @@ import type { ChunkSliceJson } from "../render/stages/freezePlan.js"; import { writeStitchedMp4 } from "./mp4Stitch.js"; import { plan, type DistributedRenderConfig } from "./plan.js"; import { renderChunk } from "./renderChunk.js"; +import { RenderCancelledError } from "../renderOrchestrator.js"; export interface RenderSpanResult { startFrame: number; @@ -40,6 +41,10 @@ export function spanFrameRange( } /** Renders `[startSeconds, endSeconds)` as a standalone mp4 from 0, with that span's audio, by chunk sub-ranges. */ +function throwIfAborted(signal: AbortSignal | undefined): void { + if (signal?.aborted) throw new RenderCancelledError("render_cancelled", "user_cancelled"); +} + export async function renderSpan( projectDir: string, config: DistributedRenderConfig, @@ -59,7 +64,13 @@ export async function renderSpan( const planDir = join(workDir, "plan"); const partsDir = join(workDir, "parts"); mkdirSync(partsDir, { recursive: true }); - const planned = await plan(projectDir, config, planDir, { chunksCarryAudio: true }); + // The span captures here in the browser a full render uses, so the container-only font guards do not apply. + const planned = await plan( + projectDir, + { ...config, rejectOnSystemFonts: false, failClosedFontFetch: false }, + planDir, + { chunksCarryAudio: true }, + ); const { startFrame, endFrame } = spanFrameRange( span.startSeconds, span.endSeconds, @@ -76,10 +87,12 @@ export async function renderSpan( endFrame: Math.min(slice.endFrame, endFrame), }; if (range.endFrame <= range.startFrame) continue; + throwIfAborted(config.abortSignal); const part = join(partsDir, `part-${String(parts.length).padStart(4, "0")}.mp4`); await renderChunk(planDir, slice.index, part, { frameRange: range }); parts.push(part); } + throwIfAborted(config.abortSignal); await writeStitchedMp4(parts, outputPath); return { startFrame, endFrame, framesEncoded: endFrame - startFrame }; } finally { From 4e555d57f68537e20d644c0fb922d1564faf7784 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Fri, 30 Oct 2026 10:30:10 -0400 Subject: [PATCH 4/4] chore(producer): put the renderSpan doc comment back above renderSpan --- packages/producer/src/services/distributed/renderSpan.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/producer/src/services/distributed/renderSpan.ts b/packages/producer/src/services/distributed/renderSpan.ts index d384e4c37b5..a75b26226e9 100644 --- a/packages/producer/src/services/distributed/renderSpan.ts +++ b/packages/producer/src/services/distributed/renderSpan.ts @@ -40,11 +40,11 @@ export function spanFrameRange( return { startFrame, endFrame }; } -/** Renders `[startSeconds, endSeconds)` as a standalone mp4 from 0, with that span's audio, by chunk sub-ranges. */ function throwIfAborted(signal: AbortSignal | undefined): void { if (signal?.aborted) throw new RenderCancelledError("render_cancelled", "user_cancelled"); } +/** Renders `[startSeconds, endSeconds)` as a standalone mp4 from 0, with that span's audio, by chunk sub-ranges. */ export async function renderSpan( projectDir: string, config: DistributedRenderConfig,