diff --git a/packages/engine/src/services/audioMixer.ts b/packages/engine/src/services/audioMixer.ts index a363b82a8f..ca018928b5 100644 --- a/packages/engine/src/services/audioMixer.ts +++ b/packages/engine/src/services/audioMixer.ts @@ -1371,6 +1371,7 @@ async function mixThroughFloatSum( signal?: AbortSignal, config?: Partial> & { keepEncoderInputAt?: string; + window?: { startSeconds: number; durationSeconds: number }; }, ): Promise { const sumPath = join(workDir, "master-sum.wav"); @@ -1388,10 +1389,47 @@ async function mixThroughFloatSum( ).path : sumPath; const encodeStart = Date.now(); - const encoded = await encodeAac(encoderInput, outputPath, totalDuration, { - signal, - timeout: config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout, - }); + const timeout = config?.ffmpegProcessTimeout ?? DEFAULT_CONFIG.ffmpegProcessTimeout; + const window = config?.window; + const deliveryInput = window ? join(workDir, "window.wav") : encoderInput; + if (window) { + const length = formatFilterNumber(window.durationSeconds); + const trimmed = await runFfmpeg( + [ + "-i", + encoderInput, + "-af", + `atrim=start=${formatFilterNumber(window.startSeconds)}:duration=${length},asetpts=PTS-STARTPTS,apad,atrim=0:${length}`, + "-acodec", + "pcm_f32le", + "-ar", + "48000", + "-y", + deliveryInput, + ], + { signal, timeout }, + ); + if (!trimmed.success) { + const failure = ffmpegFailure("mix", trimmed, timeout); + return { + success: false, + outputPath, + durationMs: sum.durationMs + trimmed.durationMs, + tracksProcessed: 0, + error: failure.detail, + failures: [failure], + }; + } + } + const encoded = await encodeAac( + deliveryInput, + outputPath, + window?.durationSeconds ?? totalDuration, + { + signal, + timeout, + }, + ); if (!encoded.success) { const failure = ffmpegFailure( "mix", @@ -1408,7 +1446,7 @@ async function mixThroughFloatSum( }; } if (config?.keepEncoderInputAt) - renameWithRetry(encoderInput, config.keepEncoderInputAt, { copyFallback: true }); + renameWithRetry(deliveryInput, config.keepEncoderInputAt, { copyFallback: true }); return { ...sum, outputPath, @@ -1436,6 +1474,8 @@ export async function processCompositionAudio( keepEncoderInputAt?: string; /** Folders a local source must be in; one outside them, or private there, is never opened. Unset allows any folder. */ assetRoots?: readonly string[]; + /** Deliver only this part of the mix; the whole film is mixed first so effect tails cross into it. */ + window?: { startSeconds: number; durationSeconds: number }; }, compiledDir?: string, ): Promise { diff --git a/packages/engine/src/services/audioMixer.window.test.ts b/packages/engine/src/services/audioMixer.window.test.ts new file mode 100644 index 0000000000..b323a65b58 --- /dev/null +++ b/packages/engine/src/services/audioMixer.window.test.ts @@ -0,0 +1,100 @@ +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { getFfmpegBinary, getFfprobeBinary } from "../utils/ffmpegBinaries.js"; +import { MIXED_AUDIO_FILENAME, processCompositionAudio } from "./audioMixer.js"; + +const HAS_FFMPEG = spawnSync(getFfmpegBinary(), ["-version"], { encoding: "utf-8" }).status === 0; +const tempDirs: string[] = []; + +function durationSeconds(path: string): number { + const result = spawnSync( + getFfprobeBinary(), + ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", "--", path], + { encoding: "utf-8" }, + ); + return Number(result.stdout.trim()); +} + +function firstAudibleSeconds(path: string): number { + const sampleRate = 48_000; + const result = spawnSync( + getFfmpegBinary(), + ["-nostdin", "-v", "error", "-i", path, "-ac", "1", "-ar", "48000", "-f", "s16le", "-"], + { maxBuffer: 1 << 28 }, + ); + const pcm = result.stdout; + for (let i = 0; i < pcm.length / 2; i += 1) { + if (Math.abs(pcm.readInt16LE(i * 2)) > 512) return i / sampleRate; + } + return Number.NaN; +} + +function tone(dir: string): void { + const setup = spawnSync( + getFfmpegBinary(), + [ + "-nostdin", + "-v", + "error", + "-f", + "lavfi", + "-i", + "sine=frequency=1000:duration=1:sample_rate=48000", + "-c:a", + "pcm_s16le", + join(dir, "tone.wav"), + ], + { encoding: "utf-8" }, + ); + expect(setup.status, setup.stderr).toBe(0); +} + +describe.skipIf(!HAS_FFMPEG)( + "processCompositionAudio window", + () => { + afterEach(() => { + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); + }); + + it("delivers only the window of the whole mix, shifted to start at 0", async () => { + const projectDir = mkdtempSync(join(tmpdir(), "hf-window-")); + const workDir = mkdtempSync(join(tmpdir(), "hf-window-work-")); + tempDirs.push(projectDir, workDir); + tone(projectDir); + const outputPath = join(projectDir, MIXED_AUDIO_FILENAME); + const pcmPath = join(projectDir, "delivery.wav"); + + const result = await processCompositionAudio( + [ + { + id: "tone", + src: "tone.wav", + start: 2, + end: 3, + mediaStart: 0, + layer: 0, + volume: 1, + type: "audio", + }, + ], + projectDir, + workDir, + outputPath, + 5, + undefined, + { keepEncoderInputAt: pcmPath, window: { startSeconds: 1.5, durationSeconds: 2 } }, + ); + + expect(result.success).toBe(true); + expect(durationSeconds(pcmPath)).toBeCloseTo(2, 3); + expect(durationSeconds(outputPath)).toBeCloseTo(2, 1); + // The tone starts 2 s into the film, so 0.5 s into a window that starts at 1.5 s. + expect(firstAudibleSeconds(pcmPath)).toBeCloseTo(0.5, 2); + expect(firstAudibleSeconds(outputPath)).toBeCloseTo(0.5, 1); + }); + }, + 30_000, +); diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts index 2ebe6700bd..01996df0e5 100644 --- a/packages/engine/src/services/frameCapture.ts +++ b/packages/engine/src/services/frameCapture.ts @@ -5618,13 +5618,14 @@ export async function captureFrame( session: CaptureSession, frameIndex: number, time: number, + fileIndex: number = frameIndex, ): Promise { const { buffer, quantizedTime, captureTimeMs } = await captureFrameCore( session, frameIndex, time, ); - const framePath = writeCapturedFrame(session, frameIndex, buffer); + const framePath = writeCapturedFrame(session, fileIndex, buffer); return { frameIndex, time: quantizedTime, path: framePath, captureTimeMs }; } diff --git a/packages/producer/src/services/render/captureCost.ts b/packages/producer/src/services/render/captureCost.ts index 7660e8f16d..e0182fd3d1 100644 --- a/packages/producer/src/services/render/captureCost.ts +++ b/packages/producer/src/services/render/captureCost.ts @@ -303,8 +303,10 @@ export async function measureCaptureCostFromSession( totalFrames: number, fps: number, log?: ProducerLogger, + /** The film frame a range render starts at; samples are taken inside its window. */ + firstFrame = 0, ): Promise<{ estimate: CaptureCostEstimate; samples: CaptureCalibrationSample[] }> { - const sampledFrames = selectCaptureCalibrationFrames(totalFrames); + const sampledFrames = selectCaptureCalibrationFrames(totalFrames).map((i) => firstFrame + i); const samples: CaptureCalibrationSample[] = []; const totalSamples = sampledFrames.length; @@ -463,7 +465,13 @@ export async function runCaptureCalibration(input: { } assertNotAborted(); log.info("Calibration session ready, capturing test frames..."); - const result = await measureCaptureCostFromSession(session, totalFrames, fps, log); + const result = await measureCaptureCostFromSession( + session, + totalFrames, + fps, + log, + job.frameWindow?.startFrame, + ); logCaptureCalibrationResult(result, log); return result; }; diff --git a/packages/producer/src/services/render/frameWindow.test.ts b/packages/producer/src/services/render/frameWindow.test.ts new file mode 100644 index 0000000000..8633b929fc --- /dev/null +++ b/packages/producer/src/services/render/frameWindow.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { resolveFrameWindow } from "./frameWindow.js"; + +const fps30 = { num: 30, den: 1 }; +const ntsc = { num: 30000, den: 1001 }; + +describe("resolveFrameWindow", () => { + it("covers the frames from the start to the end second", () => { + expect(resolveFrameWindow({ startSeconds: 2.5, endSeconds: 4 }, fps30, 300)).toEqual({ + startFrame: 75, + endFrame: 120, + }); + }); + + it("runs to the film's end without an end, and stops there when the end is past it", () => { + expect(resolveFrameWindow({ startSeconds: 9 }, fps30, 300)).toEqual({ + startFrame: 270, + endFrame: 300, + }); + expect(resolveFrameWindow({ startSeconds: 9, endSeconds: 60 }, fps30, 300)).toEqual({ + startFrame: 270, + endFrame: 300, + }); + }); + + it("lands on exact frames at a rational frame rate", () => { + // 1001 s at 30000/1001 fps is exactly 30000 frames; a float fps of 29.97 would give 30000.03. + expect(resolveFrameWindow({ startSeconds: 1001, endSeconds: 2002 }, ntsc, 90_000)).toEqual({ + startFrame: 30_000, + endFrame: 60_000, + }); + expect(resolveFrameWindow({ startSeconds: 1.001 }, ntsc, 300)).toEqual({ + startFrame: 30, + endFrame: 300, + }); + }); + + it("refuses a range that holds no frame", () => { + expect(() => resolveFrameWindow({ startSeconds: 10 }, fps30, 300)).toThrow(/holds no frame/); + expect(() => resolveFrameWindow({ startSeconds: 2, endSeconds: 2.01 }, fps30, 300)).toThrow( + /holds no frame/, + ); + }); +}); diff --git a/packages/producer/src/services/render/frameWindow.ts b/packages/producer/src/services/render/frameWindow.ts new file mode 100644 index 0000000000..82d9aa0d05 --- /dev/null +++ b/packages/producer/src/services/render/frameWindow.ts @@ -0,0 +1,43 @@ +import type { Fps } from "@hyperframes/core"; +import type { CapturePlan } from "./capturePlan.js"; + +/** A part of the film in seconds of the film; the output starts at 0. No end = to the film's end. */ +export interface RenderRange { + startSeconds: number; + endSeconds?: number; +} + +/** The film frames `[startFrame, endFrame)` a render captures. */ +export interface FrameWindow { + startFrame: number; + endFrame: number; +} + +/** The frames a range covers at an exact frame rate; an end past the film stops at the film's end. */ +export function resolveFrameWindow(range: RenderRange, fps: Fps, filmFrames: number): FrameWindow { + const frameAt = (seconds: number) => Math.round((seconds * fps.num) / fps.den); + const startFrame = frameAt(range.startSeconds); + const endFrame = Math.min( + range.endSeconds === undefined ? filmFrames : frameAt(range.endSeconds), + filmFrames, + ); + if (!(endFrame > startFrame)) { + throw new Error( + `The range ${range.startSeconds}s to ${range.endSeconds ?? "the end"}s holds no frame: the film has ` + + `${filmFrames} frames at ${fps.num}/${fps.den} fps.`, + ); + } + return { startFrame, endFrame }; +} + +/** Only the disk route captures a frame window; HDR content and shader transitions render whole films for now. */ +export function assertRangeSupported( + frameWindow: FrameWindow | undefined, + route: CapturePlan["kind"], +): void { + if (!frameWindow || route === "sdr_disk") return; + throw new Error( + `This composition renders on the "${route}" capture route, which renders the whole film only; ` + + "render it without a start or end.", + ); +} diff --git a/packages/producer/src/services/render/stages/audioStage.ts b/packages/producer/src/services/render/stages/audioStage.ts index 64f973effb..ecccf3d7df 100644 --- a/packages/producer/src/services/render/stages/audioStage.ts +++ b/packages/producer/src/services/render/stages/audioStage.ts @@ -42,9 +42,11 @@ export interface AudioStageInput { workDir: string; /** `join(workDir, "compiled")`; passed through to the audio mixer for asset resolution. */ compiledDir: string; - /** Probed video frame count and exact frame rate define the delivered audio length. */ + /** The film's frame count and exact frame rate define the mixed audio length. */ totalFrames: number; fps: Fps; + /** Deliver only these film frames' audio, cut from the whole mix. */ + frameWindow?: { startFrame: number; endFrame: number }; /** Timeout forwarded to ffmpeg subprocesses used by the audio mixer. */ ffmpegProcessTimeout: number; /** Master gain forwarded to the audio mixer. */ @@ -113,10 +115,15 @@ export function runAudioStage(input: AudioStageInput): Promise async function runAudioStageScoped(input: AudioStageInput): Promise { const stageStart = Date.now(); const pcmSourcePath = join(input.workDir, "audio-source.wav"); - const duration = (input.totalFrames * input.fps.den) / input.fps.num; + const seconds = (frames: number) => (frames * input.fps.den) / input.fps.num; + const duration = seconds(input.totalFrames); + const window = input.frameWindow && { + startSeconds: seconds(input.frameWindow.startFrame), + durationSeconds: seconds(input.frameWindow.endFrame - input.frameWindow.startFrame), + }; let deliverySourcePath: string | undefined; try { - const result = await mixAudioForDelivery(input, duration, pcmSourcePath); + const result = await mixAudioForDelivery(input, duration, pcmSourcePath, window); let audioLoweredDb: number | undefined; if (result.hasAudio) { const guardStart = Date.now(); @@ -124,7 +131,7 @@ async function runAudioStageScoped(input: AudioStageInput): Promise> { const { projectDir, @@ -218,6 +226,7 @@ async function mixAudioForDelivery( urlByAbsentLocalPath, audioSidecarUrlByLocalPath, keepEncoderInputAt: pcmSourcePath, + window, assetRoots: input.allowOutsideProjectAssets ? undefined : mediaAssetRoots(projectDir, compiledDir), diff --git a/packages/producer/src/services/render/stages/captureStage.test.ts b/packages/producer/src/services/render/stages/captureStage.test.ts index d9e7caa3bb..adb9d17412 100644 --- a/packages/producer/src/services/render/stages/captureStage.test.ts +++ b/packages/producer/src/services/render/stages/captureStage.test.ts @@ -18,6 +18,8 @@ const verifyDiskDrawElementSamples = vi.fn(async () => {}); const completeDeferredDrawElementInit = vi.fn(async () => {}); const getCapturePerfSummary = vi.fn(() => ({})); const executeParallelCapture = vi.fn(); +const captureFrameToBufferPipelined = vi.fn(); +const writeCapturedFrame = vi.fn(); vi.mock("@hyperframes/engine", async (importOriginal) => { const actual = await importOriginal(); @@ -32,6 +34,8 @@ vi.mock("@hyperframes/engine", async (importOriginal) => { completeDeferredDrawElementInit(...args), getCapturePerfSummary: (...args: unknown[]) => getCapturePerfSummary(...args), executeParallelCapture: (...args: unknown[]) => executeParallelCapture(...args), + captureFrameToBufferPipelined: (...args: unknown[]) => captureFrameToBufferPipelined(...args), + writeCapturedFrame: (...args: unknown[]) => writeCapturedFrame(...args), mergeWorkerFrames: async () => {}, }; }); @@ -518,6 +522,65 @@ describe("runCaptureStage — sequential path transient Target-closed single ret } }); + it("pipelined: hands the engine film frames inside a frameRange and names files from 0", async () => { + const framesDir = mkdtempSync(join(tmpdir(), "hf-seq-pipelined-range-")); + createCaptureSession.mockResolvedValue({ + isInitialized: false, + browserConsoleBuffer: [], + options: { captureBeyondViewport: false, format: "jpeg" }, + workerEncodeEnabled: true, + outputDir: framesDir, + }); + const captured: [number, number][] = []; + captureFrameToBufferPipelined.mockImplementation( + async (_s: unknown, frameIndex: number, time: number) => { + captured.push([frameIndex, time]); + return { encodeResult: Promise.resolve(Buffer.from("frame")), captureTimeMs: 1 }; + }, + ); + const written: number[] = []; + writeCapturedFrame.mockImplementation((_s: unknown, fileIndex: number) => { + written.push(fileIndex); + writeFileSync(join(framesDir, formatCaptureFrameName(fileIndex, "jpg")), "captured-frame"); + }); + try { + await runCaptureStage({ + fileServer: { url: "http://localhost:0" } as never, + workDir: framesDir, + framesDir, + job: createRenderJob({ fps: { num: 10, den: 1 }, quality: "draft" }), + totalFrames: 4, + cfg: DEFAULT_CONFIG, + plan: { workerCount: 1, forceScreenshot: false }, + log: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as never, + probeSession: null, + captureAttempts: [], + dedupPerfs: [], + buildCaptureOptions: () => ({ + width: 64, + height: 64, + fps: { num: 10, den: 1 }, + format: "jpeg", + }), + createRenderVideoFrameInjector: () => null, + abortSignal: undefined, + assertNotAborted: () => {}, + frameRange: { startFrame: 10, endFrame: 14 }, + }); + expect(captured).toEqual([ + [10, 1.0], + [11, 1.1], + [12, 1.2], + [13, 1.3], + ]); + expect(written).toEqual([0, 1, 2, 3]); + } finally { + captureFrameToBufferPipelined.mockReset(); + writeCapturedFrame.mockReset(); + rmSync(framesDir, { recursive: true, force: true }); + } + }); + it("resumes from the first missing frame inside a frameRange and fails on a second death", async () => { const framesDir = mkdtempSync(join(tmpdir(), "hf-seq-transient-range-")); let sessionCount = 0; @@ -532,16 +595,20 @@ describe("runCaptureStage — sequential path transient Target-closed single ret }; }); const times: number[] = []; - captureFrame.mockImplementation(async (_s: unknown, frameIndex: number, time: number) => { - times.push(time); - if (sessionCount === 1 && frameIndex === 2) { - throw new Error("Protocol error (Runtime.callFunctionOn): Target closed"); - } - if (sessionCount === 2 && frameIndex === 3) { - throw new Error("Protocol error (Runtime.callFunctionOn): Target closed"); - } - writeFileSync(join(framesDir, formatCaptureFrameName(frameIndex, "jpg")), "captured-frame"); - }); + const indexes: [number, number][] = []; + captureFrame.mockImplementation( + async (_s: unknown, frameIndex: number, time: number, fileIndex: number) => { + times.push(time); + indexes.push([frameIndex, fileIndex]); + if (sessionCount === 1 && frameIndex === 12) { + throw new Error("Protocol error (Runtime.callFunctionOn): Target closed"); + } + if (sessionCount === 2 && frameIndex === 13) { + throw new Error("Protocol error (Runtime.callFunctionOn): Target closed"); + } + writeFileSync(join(framesDir, formatCaptureFrameName(fileIndex, "jpg")), "captured-frame"); + }, + ); const log = { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() }; const job = createRenderJob({ fps: { num: 10, den: 1 }, quality: "draft" }); @@ -576,6 +643,15 @@ describe("runCaptureStage — sequential path transient Target-closed single ret // frame 2 ok, 3 dies; no third session. expect(createCaptureSession).toHaveBeenCalledTimes(2); expect(times).toEqual([1.0, 1.1, 1.2, 1.2, 1.3]); + // The engine gets the film frame (its dedup, risk and boundary sets are keyed by it); the + // file is named from 0 so the encoder reads the window as a whole video. + expect(indexes).toEqual([ + [10, 0], + [11, 1], + [12, 2], + [12, 2], + [13, 3], + ]); expect(log.warn).toHaveBeenCalledTimes(1); expect(closeCaptureSession).toHaveBeenCalledTimes(2); } finally { diff --git a/packages/producer/src/services/render/stages/captureStage.ts b/packages/producer/src/services/render/stages/captureStage.ts index 4efd849199..e694cd0bc7 100644 --- a/packages/producer/src/services/render/stages/captureStage.ts +++ b/packages/producer/src/services/render/stages/captureStage.ts @@ -641,7 +641,7 @@ async function captureSessionFrames( assertNotAborted(); const absoluteIdx = rangeStart + i; const time = (absoluteIdx * job.config.fps.den) / job.config.fps.num; - const { encodeResult } = await captureFrameToBufferPipelined(session, i, time); + const { encodeResult } = await captureFrameToBufferPipelined(session, absoluteIdx, time); await drainPrev(); prev = { fileIndex: i, encodeResult }; } @@ -651,7 +651,7 @@ async function captureSessionFrames( assertNotAborted(); const absoluteIdx = rangeStart + i; const time = (absoluteIdx * job.config.fps.den) / job.config.fps.num; - await captureFrame(session, i, time); + await captureFrame(session, absoluteIdx, time, i); reportFrame(i); } } diff --git a/packages/producer/src/services/renderOrchestrator.range.test.ts b/packages/producer/src/services/renderOrchestrator.range.test.ts new file mode 100644 index 0000000000..89bdc23b89 --- /dev/null +++ b/packages/producer/src/services/renderOrchestrator.range.test.ts @@ -0,0 +1,175 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resolveConfig } from "@hyperframes/engine"; +import { createRenderJob, executeRenderJob, type RenderJob } from "./renderOrchestrator.js"; + +// Entry: executeRenderJob with a range on a 10 s, 300-frame film. Each capture stage records what +// it was given and ends the render there. +const { state, CAPTURE_REACHED } = vi.hoisted(() => ({ + state: { + shaderTransitions: false, + disk: [] as { totalFrames: number; frameRange?: { startFrame: number; endFrame: number } }[], + streaming: 0, + audio: [] as { totalFrames: number; frameWindow?: { startFrame: number; endFrame: number } }[], + }, + CAPTURE_REACHED: "capture reached", +})); + +vi.mock("@hyperframes/engine", async (importOriginal) => ({ + ...(await importOriginal()), + assertConfiguredFfmpegBinariesExist: () => {}, + resolveBrowserGpuMode: async () => "software", + resolveHeadlessShellPath: () => "/opt/chrome-headless-shell", + createCaptureSession: async () => ({ browserConsoleBuffer: [], options: {} }), + initializeSession: async () => {}, + closeCaptureSession: async () => {}, +})); +vi.mock("./fileServer.js", async (importOriginal) => ({ + ...(await importOriginal()), + createFileServer: async () => ({ + url: "http://127.0.0.1:1", + port: 1, + close: () => {}, + addPreHeadScript: () => {}, + }), +})); +vi.mock("./render/stages/compileStage.js", () => ({ + runCompileStage: async () => ({ + compiled: { + html: "
", + renderModeHints: { reasons: [] }, + hasShaderTransitions: state.shaderTransitions, + unresolvedCompositions: [], + }, + composition: { width: 320, height: 180, duration: 10, videos: [], images: [], audios: [] }, + deviceScaleFactor: 1, + outputWidth: 320, + outputHeight: 180, + compileOnlyMs: 0, + forceScreenshot: true, + }), +})); +vi.mock("./render/stages/probeStage.js", () => ({ + runProbeStage: async ({ compiled }: { compiled: object }) => ({ + compiled, + fileServer: null, + probeSession: null, + lastBrowserConsole: [], + duration: 10, + totalFrames: 300, + browserProbeMs: 0, + }), +})); +vi.mock("./render/stages/extractVideosStage.js", async (importOriginal) => ({ + ...(await importOriginal()), + runExtractVideosStage: async () => ({ + extractionResult: null, + frameLookup: null, + videoReadinessSkipIds: new Set(), + videoMetadataHints: new Map(), + nativeHdrVideoIds: new Set(), + videoTransfers: new Map(), + nativeHdrImageIds: new Set(), + imageTransfers: new Map(), + hdrImageSrcPaths: new Map(), + imageColorSpaces: [], + videoExtractMs: 0, + failureToEnforce: undefined, + }), +})); +vi.mock("./render/stages/audioStage.js", () => ({ + runAudioStage: async (input: { + totalFrames: number; + frameWindow?: { startFrame: number; endFrame: number }; + }) => { + state.audio.push({ totalFrames: input.totalFrames, frameWindow: input.frameWindow }); + return { audioOutputPath: undefined, hasAudio: false, audioProcessMs: 0 }; + }, +})); +vi.mock("./render/captureCost.js", async (importOriginal) => ({ + ...(await importOriginal()), + resolveRenderWorkerCount: () => 1, +})); +vi.mock("./render/stages/captureStage.js", async (importOriginal) => ({ + ...(await importOriginal()), + runCaptureStage: async (input: { + totalFrames: number; + frameRange?: { startFrame: number; endFrame: number }; + }) => { + state.disk.push({ totalFrames: input.totalFrames, frameRange: input.frameRange }); + throw new Error(CAPTURE_REACHED); + }, +})); +vi.mock("./render/stages/captureStreamingStage.js", async (importOriginal) => ({ + ...(await importOriginal()), + runCaptureStreamingStage: async () => { + state.streaming++; + throw new Error(CAPTURE_REACHED); + }, +})); + +const dirs: string[] = []; +beforeEach(() => { + state.shaderTransitions = false; + state.disk = []; + state.streaming = 0; + state.audio = []; +}); +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +async function render( + range?: { startSeconds: number; endSeconds?: number }, + format: "mp4" | "webm" = "mp4", +): Promise { + const root = mkdtempSync(join(tmpdir(), "hf-range-")); + dirs.push(root); + writeFileSync(join(root, "index.html"), "
"); + const job = createRenderJob({ + fps: 30, + quality: "standard", + hdrMode: "force-sdr", + format, + ...(range && { range }), + producerConfig: resolveConfig({ browserGpuMode: "software", lowMemoryMode: false }), + logger: { info() {}, warn() {}, error() {}, debug() {} }, + }); + await executeRenderJob(job, root, join(root, `output.${format}`)).catch((error: Error) => { + if (!error.message.includes(CAPTURE_REACHED)) throw error; + }); + return job; +} + +it("captures the range's frames on the disk route and cuts the whole film's audio to it", async () => { + const job = await render({ startSeconds: 2.5, endSeconds: 4 }); + expect(job.frameWindow).toEqual({ startFrame: 75, endFrame: 120 }); + expect(job.totalFrames).toBe(45); + expect(job.duration).toBe(1.5); + expect(state.streaming).toBe(0); + expect(state.disk).toEqual([{ totalFrames: 45, frameRange: { startFrame: 75, endFrame: 120 } }]); + expect(state.audio).toEqual([ + { totalFrames: 300, frameWindow: { startFrame: 75, endFrame: 120 } }, + ]); +}); + +it("renders the whole film as before without a range", async () => { + const job = await render(); + expect(job.frameWindow).toBeUndefined(); + expect(job.totalFrames).toBe(300); + expect(state.audio).toEqual([{ totalFrames: 300, frameWindow: undefined }]); + expect(state.disk.length + state.streaming).toBe(1); + expect(state.disk[0]?.frameRange).toBeUndefined(); +}); + +it("refuses a range on the layered route instead of rendering the whole film", async () => { + // webm and mov composite shader transitions on the layered route; mp4 composites them in the page. + state.shaderTransitions = true; + await expect(render({ startSeconds: 2.5, endSeconds: 4 }, "webm")).rejects.toThrow( + /"hdr_layered" capture route, which renders the whole film only/, + ); + expect(state.disk).toEqual([]); + expect(state.streaming).toBe(0); +}); diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts index b1c34453f5..872a831ea5 100644 --- a/packages/producer/src/services/renderOrchestrator.ts +++ b/packages/producer/src/services/renderOrchestrator.ts @@ -237,6 +237,12 @@ import { shouldCalibrateSoftwareGpu, } from "./render/captureCost.js"; import { gpuChoiceStore, readGpuChoice, writeGpuChoice } from "./render/gpuChoice.js"; +import { + type FrameWindow, + type RenderRange, + assertRangeSupported, + resolveFrameWindow, +} from "./render/frameWindow.js"; import { computeCompositionObservabilityHash, RenderObservabilityRecorder, @@ -451,6 +457,8 @@ export interface RenderConfig { */ motionBlur?: MotionBlurOptions; pageMotionBlur?: "off"; + /** Render only this part of the film; the output starts at its start. Absent renders the whole film. */ + range?: RenderRange; workers?: number; /** Wall-time budget in ms for the whole render. Absent or 0 disables the ETA guard. */ maxRenderMs?: number; @@ -833,6 +841,8 @@ export interface RenderJob extends Partial { outputPath?: string; duration?: number; totalFrames?: number; + /** The film frames a `range` render captures; `totalFrames` and `duration` then describe this window. */ + frameWindow?: FrameWindow; framesRendered?: number; perfSummary?: RenderPerfSummary; audioLoweredDb?: number; @@ -3561,15 +3571,26 @@ async function executeRenderPipeline(input: { } // The probe stage produces `duration` / `totalFrames` values; the // sequencer owns the `RenderJob` and writes them onto it. - job.duration = probeResult.duration; - job.totalFrames = probeResult.totalFrames; - const totalFrames = probeResult.totalFrames; - captureTotalFrames = totalFrames; validateRenderDuration({ duration: probeResult.duration, - totalFrames, + totalFrames: probeResult.totalFrames, fps: fpsToNumber(job.config.fps), }); + const frameWindow = job.config.range + ? resolveFrameWindow(job.config.range, job.config.fps, probeResult.totalFrames) + : undefined; + job.frameWindow = frameWindow; + // A part of the film renders on the disk route (assertRangeSupported); every streaming, + // segmented and video-layer gate reads this flag first. + if (frameWindow) cfg.enableStreamingEncode = false; + const totalFrames = frameWindow + ? frameWindow.endFrame - frameWindow.startFrame + : probeResult.totalFrames; + job.totalFrames = totalFrames; + job.duration = frameWindow + ? (totalFrames * job.config.fps.den) / job.config.fps.num + : probeResult.duration; + captureTotalFrames = totalFrames; // Before the video layer may close the probe page; no box means full size, as before. const shownBoxes = largerThanCanvas.length > 0 && probeSession?.isInitialized @@ -3808,6 +3829,7 @@ async function executeRenderPipeline(input: { workDir, compiledDir, totalFrames: probeResult.totalFrames, + ...(frameWindow && { frameWindow }), fps: job.config.fps, ffmpegProcessTimeout: cfg.ffmpegProcessTimeout, audioGain: cfg.audioGain, @@ -4281,6 +4303,11 @@ async function executeRenderPipeline(input: { totalMemoryMb: Math.round(totalmem() / (1024 * 1024)), minMemoryMb: deParallelMinMemoryMb, }); + // Both routes pin streaming capture, which renders only the whole film. + if (frameWindow) { + deInversionEligible = false; + deParallelRouterEligible = false; + } // The browser probe is conditional, so most renders arrive here without the engine's // init-time drawElement gates having run. Run them before pinning 1 or 3 workers: a // refused comp captures by screenshot and keeps the resolver's parallelism. @@ -4992,6 +5019,7 @@ async function executeRenderPipeline(input: { // Every route the render can end up on passes through here, including the ones a // replan lands on, so this is where motion blur's one supported-route answer belongs. assertMotionBlurSupported(job.config.motionBlur, capturePlan.kind); + assertRangeSupported(job.frameWindow, capturePlan.kind); assertOutputScaleSupported(deviceScaleFactor, capturePlan.kind); workerCount = capturePlan.workerCount; captureForceScreenshot = capturePlan.forceScreenshot; @@ -5747,6 +5775,7 @@ async function executeRenderPipeline(input: { framesDir, job, totalFrames, + ...(job.frameWindow && { frameRange: job.frameWindow }), cfg, plan: diskPlan, log,