Skip to content

Write HTML. Render video. Built for agents.

feat(producer): sequential segmented capture stage

Vance Ingalls8391abd67280
diff --git a/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts
new file mode 100644
index 0000000000..37b3ec8963
--- /dev/null
+++ b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts
@@ -0,0 +1,368 @@
+// fallow-ignore-file code-duplication
+import { afterAll, describe, expect, it, mock } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+const fixtureRoot = mkdtempSync(join(tmpdir(), "hf-segmented-test-"));
+const framesDir = join(fixtureRoot, "frames");
+afterAll(() => rmSync(fixtureRoot, { recursive: true, force: true }));
+import { createCapturePlan } from "../capturePlan.js";
+import { runCaptureSegmentedStage, segmentOutputPath } from "./captureSegmentedStage.js";
+
+const writeFrame = mock((_buffer: Buffer) => true);
+const closeEncoder = mock(async () => ({ success: true, durationMs: 123, fileSize: 42 }));
+const spawnStreamingEncoder = mock(async () => ({
+ writeFrame,
+ close: closeEncoder,
+ getExitStatus: () => "success",
+ getExitError: () => undefined,
+}));
+let failCaptureFrameToBuffer = false;
+let failInitializeSession = false;
+let hangParallelUntilAbort = false;
+let hangSequentialUntilStall = false;
+let sessionWorkerEncodeEnabled = false;
+let captureSessionMode: "drawelement" | "screenshot" = "drawelement";
+let failPrepareCaptureSessionForReuse = false;
+let initializeSessionErrorMessage = "initialize failed";
+const browserConsoleBuffer = ["[FrameCapture:ERROR] page.goto failed"];
+const closeCaptureSession = mock(async () => {});
+class DrawElementVerificationError extends Error {}
+
+mock.module("@hyperframes/engine", () => ({
+ calculateOptimalWorkers: () => 1,
+ convertTransfer: () => {},
+ captureFrame: async () => {},
+ captureFrameToBufferPipelined: async () => {
+ if (hangSequentialUntilStall) {
+ return new Promise(() => {});
+ }
+ return { encodeResult: Promise.resolve(Buffer.from("frame")) };
+ },
+ captureFramesBatchPipelined: async () => {
+ if (hangSequentialUntilStall) {
+ return new Promise(() => {});
+ }
+ return [];
+ },
+ captureFrameToBuffer: async () => {
+ if (failCaptureFrameToBuffer) {
+ throw new Error("captureFrameToBuffer failed");
+ }
+ if (hangSequentialUntilStall) {
+ return new Promise(() => {});
+ }
+ return { buffer: Buffer.from("frame"), captureTimeMs: 1 };
+ },
+ closeCaptureSession,
+ completeDeferredDrawElementInit: async () => {},
+ createCaptureSession: async () => ({
+ isInitialized: false,
+ browserConsoleBuffer,
+ options: { captureBeyondViewport: false },
+ workerEncodeEnabled: sessionWorkerEncodeEnabled,
+ captureMode: captureSessionMode,
+ }),
+ createFrameReorderBuffer: () => ({
+ waitForFrame: async () => {},
+ advanceTo: () => {},
+ abort: () => {},
+ }),
+ distributeFrames: () => [],
+ distributeFramesInterleaved: () => [],
+ DrawElementVerificationError,
+ executeParallelCapture: async (
+ _url: string,
+ _workDir: string,
+ _tasks: unknown,
+ _opts: unknown,
+ _hook: unknown,
+ signal?: AbortSignal,
+ onProgress?: (progress: unknown) => void,
+ ) => {
+ if (hangParallelUntilAbort) {
+ onProgress?.({
+ totalFrames: 100,
+ capturedFrames: 0,
+ activeWorkers: 2,
+ workerProgress: new Map([
+ [0, 0],
+ [1, 0],
+ ]),
+ latestWorkerPhase: {
+ workerId: 0,
+ phase: "session_init",
+ browserExecutable: "C:/Chrome/chrome.exe",
+ browserVersion: "Chrome/152.0.7977.30",
+ canvasDrawElement: true,
+ gpuBackend: "d3d11/nvidia",
+ },
+ });
+ // Simulate a wedged worker: make no frame progress, then reject with the
+ // pool's generic string once aborted (by the parent or the watchdog).
+ await new Promise<void>((_resolve, reject) => {
+ const fail = () => reject(new Error("[Parallel] Capture failed: aborted"));
+ if (signal?.aborted) return fail();
+ signal?.addEventListener("abort", fail, { once: true });
+ });
+ }
+ return [];
+ },
+ getCapturePerfSummary: () => ({}),
+ getFfmpegBinary: () => "ffmpeg",
+ initializeSession: async (session: { isInitialized: boolean }) => {
+ if (failInitializeSession) {
+ throw new Error(initializeSessionErrorMessage);
+ }
+ session.isInitialized = true;
+ },
+ getEncoderPreset: () => ({
+ preset: "ultrafast",
+ quality: 28,
+ codec: "h264",
+ pixelFormat: "yuv420p",
+ }),
+ initTransparentBackground: async () => {},
+ prepareCaptureSessionForReuse: () => {
+ if (failPrepareCaptureSessionForReuse) {
+ throw new Error("prepare reuse failed: ENOSPC");
+ }
+ },
+ recaptureDrawElementFrameForVerify: async () => Buffer.from("frame"),
+ spawnStreamingEncoder,
+ writeCapturedFrame: async () => {},
+}));
+
+mock.module("@hyperframes/core", () => ({
+ CANVAS_DIMENSIONS: {},
+ checkOutputResolutionCompatibility: () => ({ ok: true }),
+ fpsToNumber: () => 30,
+ redactTelemetryString: (value: string) => value,
+}));
+
+mock.module("../../renderOrchestrator.js", () => ({
+ closeHdrVideoFrameSource: () => {},
+ createHdrPerfCollector: () => ({}),
+ executeDiskCaptureWithAdaptiveRetry: async () => [],
+ resolveCompositeTransfer: () => "srgb",
+}));
+
+mock.module("../../hdrCompositor.js", () => ({
+ closeHdrVideoFrameSource: () => {},
+ resolveCompositeTransfer: () => "srgb",
+}));
+
+mock.module("./captureHdrResources.js", () => ({
+ cleanupHdrVideoFrameSource: () => {},
+ decodeHdrImageBuffers: () => new Map(),
+ extractHdrVideoFrames: async () => ({
+ sources: new Map(),
+ estimatedBytes: 0,
+ releaseReservation: () => {},
+ }),
+ planHdrResources: () => ({
+ hdrVideoStartTimes: new Map(),
+ nativeHdrVideos: [],
+ nativeHdrImages: [],
+ }),
+ probeHdrExtractionDims: async () => {},
+}));
+
+mock.module("./captureHdrFrameShared.js", () => ({
+ ensureFrameWritten: () => {},
+ partitionTransitionFrames: () => new Set(),
+ shouldUseHybridLayeredPath: () => false,
+}));
+
+mock.module("./captureHdrSequentialLoop.js", () => ({
+ runSequentialLayeredFrameLoop: async () => {},
+}));
+
+mock.module("./captureHdrHybridLoop.js", () => ({
+ runHybridLayeredFrameLoop: async () => {},
+}));
+
+function segmentedPlan() {
+ const plan = createCapturePlan({
+ workerCount: 1,
+ forceScreenshot: false,
+ useStreamingEncode: true,
+ useLayeredComposite: false,
+ usePageSideCompositing: false,
+ hasHdrContent: false,
+ needsAlpha: false,
+ useSegmentedCapture: true,
+ });
+ if (plan.kind !== "sdr_segmented") throw new Error(`expected sdr_segmented, got ${plan.kind}`);
+ return plan;
+}
+
+function fakeStageInput(overrides: { totalFrames: number }) {
+ return {
+ fileServer: {
+ url: "http://127.0.0.1:4173",
+ port: 4173,
+ close: () => {},
+ addPreHeadScript: () => {},
+ },
+ workDir: fixtureRoot,
+ framesDir,
+ videoOnlyPath: join(fixtureRoot, "video-only.mp4"),
+ job: {
+ id: "segmented-test",
+ config: { fps: { num: 30, den: 1 }, quality: "draft" as const },
+ status: "queued" as const,
+ progress: 0,
+ currentStage: "Segmented",
+ createdAt: new Date(0),
+ duration: 1,
+ },
+ cfg: { forceScreenshot: false, ffmpegStreamingTimeout: 1000 },
+ plan: segmentedPlan(),
+ log: { error: () => {}, warn: () => {}, info: () => {}, debug: () => {} },
+ // Already-initialized fake session: the stage must not reach the real
+ // createCaptureSession, and the per-frame loop only reads captureMode.
+ probeSession: {
+ isInitialized: true,
+ browserConsoleBuffer,
+ options: { captureBeyondViewport: false },
+ workerEncodeEnabled: false,
+ captureMode: "screenshot" as const,
+ },
+ outputFormat: "mp4",
+ streamingEncoderOptions: { fps: { num: 30, den: 1 }, width: 16, height: 16 },
+ buildCaptureOptions: () => ({ width: 16, height: 16 }),
+ createRenderVideoFrameInjector: () => null,
+ abortSignal: undefined,
+ assertNotAborted: () => {},
+ dedupPerfs: [],
+ ...overrides,
+ };
+}
+
+describe("segmentOutputPath", () => {
+ it("zero-pads so lexical order equals frame order", () => {
+ expect(segmentOutputPath("/w", 7)).toBe("/w/segments/segment_00007.mp4");
+ });
+});
+
+describe("runCaptureSegmentedStage", () => {
+ it("spawns one encoder per segment, writes every frame once in order, then concats", async () => {
+ const written: Array<{ segment: string; frame: number }> = [];
+ const encoders: string[] = [];
+ const spawnEncoder = mock(async (outputPath: string) => {
+ encoders.push(outputPath);
+ return {
+ writeFrame: async (buf: Buffer) => {
+ written.push({ segment: outputPath, frame: buf.readUInt32BE(0) });
+ return true;
+ },
+ close: async () => ({ success: true, durationMs: 5, fileSize: 1 }),
+ getExitStatus: () => "success" as const,
+ getExitError: () => undefined,
+ };
+ });
+ const captureFrame = mock(async (_session: unknown, frameIndex: number) => {
+ const buffer = Buffer.alloc(4);
+ buffer.writeUInt32BE(frameIndex, 0);
+ return { buffer };
+ });
+ const concat = mock(async () => ({ success: true as const }));
+ const observed: unknown[] = [];
+
+ const result = await runCaptureSegmentedStage({
+ ...fakeStageInput({ totalFrames: 7 }),
+ segmentFrames: 3,
+ deps: { spawnEncoder, captureFrame, concat },
+ updateCaptureObservability: (p) => observed.push(p),
+ });
+
+ expect(result.success).toBe(true);
+ expect(encoders).toEqual([
+ segmentOutputPath(fixtureRoot, 0),
+ segmentOutputPath(fixtureRoot, 1),
+ segmentOutputPath(fixtureRoot, 2),
+ ]);
+ // Every frame exactly once, in order, across the segment boundaries.
+ expect(written.map((w) => w.frame)).toEqual([0, 1, 2, 3, 4, 5, 6]);
+ expect(
+ written.filter((w) => w.segment.endsWith("segment_00001.mp4")).map((w) => w.frame),
+ ).toEqual([3, 4, 5]);
+ expect(concat).toHaveBeenCalledWith(
+ encoders,
+ join(fixtureRoot, "video-only.mp4"),
+ undefined,
+ expect.anything(),
+ );
+ expect(observed[0]).toEqual({ capturePath: "segmented", segmentIndex: 0 });
+ // The GOP is the segment's own length, so every boundary is an IDR — the
+ // tail segment is shorter and must say so.
+ expect(spawnEncoder.mock.calls[1]?.[1]).toMatchObject({
+ lockGopForChunkConcat: true,
+ gopSize: 3,
+ });
+ expect(spawnEncoder.mock.calls[2]?.[1]).toMatchObject({
+ lockGopForChunkConcat: true,
+ gopSize: 1,
+ });
+ });
+
+ it("returns success:false when the first encoder cannot spawn", async () => {
+ const spawnEncoder = mock(async () => {
+ throw new Error("ffmpeg missing");
+ });
+ const result = await runCaptureSegmentedStage({
+ ...fakeStageInput({ totalFrames: 3 }),
+ segmentFrames: 3,
+ deps: { spawnEncoder },
+ });
+ expect(result).toEqual({ success: false });
+ });
+
+ it("throws when a later encoder fails to close cleanly", async () => {
+ // A later segment cannot fall back: earlier segments are already encoded,
+ // so the failure has to surface rather than silently drop frames.
+ let closes = 0;
+ const spawnEncoder = mock(async () => ({
+ writeFrame: async () => true,
+ close: async () =>
+ closes++ === 1
+ ? { success: false, durationMs: 1, fileSize: 0, error: "boom" }
+ : { success: true, durationMs: 1, fileSize: 1 },
+ getExitStatus: () => "success" as const,
+ getExitError: () => undefined,
+ }));
+ const captureFrame = mock(async () => ({ buffer: Buffer.alloc(4) }));
+ await expect(
+ runCaptureSegmentedStage({
+ ...fakeStageInput({ totalFrames: 4 }),
+ segmentFrames: 2,
+ deps: { spawnEncoder, captureFrame },
+ }),
+ ).rejects.toThrow(/[Ss]egment 1/);
+ });
+
+ it("does not concat when a later encoder fails to spawn", async () => {
+ let spawns = 0;
+ const spawnEncoder = mock(async () => {
+ if (spawns++ === 1) throw new Error("ffmpeg vanished");
+ return {
+ writeFrame: async () => true,
+ close: async () => ({ success: true, durationMs: 1, fileSize: 1 }),
+ getExitStatus: () => "success" as const,
+ getExitError: () => undefined,
+ };
+ });
+ const captureFrame = mock(async () => ({ buffer: Buffer.alloc(4) }));
+ const concat = mock(async () => ({ success: true as const }));
+ await expect(
+ runCaptureSegmentedStage({
+ ...fakeStageInput({ totalFrames: 4 }),
+ segmentFrames: 2,
+ deps: { spawnEncoder, captureFrame, concat },
+ }),
+ ).rejects.toThrow(/ffmpeg vanished/);
+ expect(concat).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/producer/src/services/render/stages/captureSegmentedStage.ts b/packages/producer/src/services/render/stages/captureSegmentedStage.ts
new file mode 100644
index 0000000000..0ba242817d
--- /dev/null
+++ b/packages/producer/src/services/render/stages/captureSegmentedStage.ts
@@ -0,0 +1,353 @@
+/**
+ * Segmented capture (spec §5 Phase 2a).
+ *
+ * The frame range is split into fixed-size segments; each one gets its own
+ * closed-GOP ffmpeg process writing `segments/segment_NNNNN.mp4`, and the
+ * segments are concat-copied into the video-only file the assemble stage
+ * muxes. Against the single-encoder streaming path this buys two things on a
+ * long render: scratch is encoded video rather than one open pipe's worth of
+ * in-flight state, and a failure is attributable to one segment — which is
+ * what Phase 2b (resume) and 2c (per-segment retry) build on.
+ *
+ * This phase keeps ONE browser session for the whole render and no retry;
+ * recycling and retry are 2c, multi-worker is 2d.
+ */
+import { mkdirSync } from "node:fs";
+import { join } from "node:path";
+import {
+ captureFrameToBuffer,
+ closeCaptureSession,
+ completeDeferredDrawElementInit,
+ concatVideoFiles,
+ createCaptureSession,
+ getCapturePerfSummary,
+ initializeSession,
+ prepareCaptureSessionForReuse,
+ spawnStreamingEncoder,
+ type BeforeCaptureHook,
+ type CaptureOptions,
+ type CapturePerfSummary,
+ type CaptureSession,
+ type EngineConfig,
+ type StreamingEncoder,
+} from "@hyperframes/engine";
+import type { FileServerHandle } from "../../fileServer.js";
+import type { ProducerLogger } from "../../../logger.js";
+import type { ProgressCallback, RenderJob } from "../../renderOrchestrator.js";
+import { wrapCaptureStageError } from "../captureStageError.js";
+import { ensureFrameWritten } from "./captureHdrFrameShared.js";
+import { updateJobStatus } from "../shared.js";
+import { encoderFailureError } from "../encoderInterruption.js";
+import type { SdrSegmentedCapturePlan } from "../capturePlan.js";
+import { planSegments, type SegmentSlice } from "../segmentPlan.js";
+import {
+ raceAgainstStall,
+ resolveCaptureStallTimeoutMs,
+ type StreamingEncoderOptions,
+} from "./captureStreamingStage.js";
+
+export interface SegmentedStageDeps {
+ spawnEncoder: typeof spawnStreamingEncoder;
+ captureFrame: typeof captureFrameToBuffer;
+ concat: typeof concatVideoFiles;
+}
+
+export interface CaptureSegmentedStageInput {
+ fileServer: FileServerHandle;
+ workDir: string;
+ framesDir: string;
+ videoOnlyPath: string;
+ job: RenderJob;
+ totalFrames: number;
+ cfg: EngineConfig;
+ plan: SdrSegmentedCapturePlan;
+ log: ProducerLogger;
+ probeSession: CaptureSession | null;
+ /** For the spawn-failure log message context only. */
+ outputFormat: string;
+ streamingEncoderOptions: StreamingEncoderOptions;
+ buildCaptureOptions: () => CaptureOptions;
+ createRenderVideoFrameInjector: () => BeforeCaptureHook | null;
+ abortSignal: AbortSignal | undefined;
+ assertNotAborted: () => void;
+ onProgress?: ProgressCallback;
+ /** Mutated in place, same contract as the streaming stage. */
+ dedupPerfs: CapturePerfSummary[];
+ segmentFrames: number;
+ /** Test seam; defaults to the real engine functions. */
+ deps?: Partial<SegmentedStageDeps>;
+ updateCaptureObservability?: (patch: {
+ capturePath?: "segmented";
+ segmentIndex?: number;
+ }) => void;
+}
+
+export type CaptureSegmentedStageResult =
+ | {
+ success: true;
+ encodeMs: number;
+ probeSession: null;
+ lastBrowserConsole: string[];
+ workerCount: 1;
+ segments: number;
+ segmentPaths: string[];
+ }
+ /** The first segment's encoder could not spawn — caller replans to sdr_streaming. */
+ | { success: false };
+
+/** Zero-padded so lexical order equals frame order in the concat list and on disk. */
+export function segmentOutputPath(workDir: string, index: number): string {
+ return join(workDir, "segments", `segment_${String(index).padStart(5, "0")}.mp4`);
+}
+
+/**
+ * One closed-GOP encoder per segment. `gopSize` is the segment's own frame
+ * count so the segment is exactly one GOP and concat-copy has an IDR at every
+ * boundary; without it ffmpeg picks its own keyframes and a boundary can land
+ * mid-GOP, which decodes as a glitch rather than an error.
+ */
+function segmentEncoderOptions(
+ base: StreamingEncoderOptions,
+ segment: SegmentSlice,
+): StreamingEncoderOptions {
+ return {
+ ...base,
+ lockGopForChunkConcat: true,
+ gopSize: segment.endFrame - segment.startFrame,
+ };
+}
+
+/** A segment's encoder never started. Only segment 0 can still fall back. */
+class SegmentEncoderSpawnError extends Error {
+ readonly reason: unknown;
+
+ constructor(reason: unknown) {
+ super(reason instanceof Error ? reason.message : String(reason));
+ this.name = "SegmentEncoderSpawnError";
+ this.reason = reason;
+ }
+}
+
+interface SegmentCaptureContext {
+ session: CaptureSession;
+ job: RenderJob;
+ cfg: EngineConfig;
+ totalFrames: number;
+ segmentCount: number;
+ workDir: string;
+ streamingEncoderOptions: StreamingEncoderOptions;
+ spawnEncoder: SegmentedStageDeps["spawnEncoder"];
+ captureFrame: SegmentedStageDeps["captureFrame"];
+ stallTimeoutMs: number;
+ abortSignal: AbortSignal | undefined;
+ assertNotAborted: () => void;
+ onProgress?: ProgressCallback;
+}
+
+/** Capture one segment into its own encoder. Returns the encoder's encode ms. */
+async function captureSegment(ctx: SegmentCaptureContext, segment: SegmentSlice): Promise<number> {
+ const segmentPath = segmentOutputPath(ctx.workDir, segment.index);
+ let encoder: StreamingEncoder;
+ try {
+ encoder = await ctx.spawnEncoder(
+ segmentPath,
+ segmentEncoderOptions(ctx.streamingEncoderOptions, segment),
+ ctx.abortSignal,
+ ctx.cfg,
+ );
+ ctx.assertNotAborted();
+ } catch (err) {
+ if (ctx.abortSignal?.aborted) throw err;
+ throw new SegmentEncoderSpawnError(err);
+ }
+
+ let encoderClosed = false;
+ try {
+ let lastProgressAt = Date.now();
+ for (let i = segment.startFrame; i < segment.endFrame; i++) {
+ ctx.assertNotAborted();
+ const time = (i * ctx.job.config.fps.den) / ctx.job.config.fps.num;
+ const { buffer } = await raceAgainstStall(
+ ctx.captureFrame(ctx.session, i, time),
+ ctx.stallTimeoutMs - (Date.now() - lastProgressAt),
+ {
+ captureMode: ctx.session.captureMode,
+ frameIndex: i,
+ totalFrames: ctx.totalFrames,
+ stallTimeoutMs: ctx.stallTimeoutMs,
+ },
+ ctx.abortSignal,
+ );
+ ensureFrameWritten(await encoder.writeFrame(buffer), i, encoder);
+ ctx.job.framesRendered = i + 1;
+ lastProgressAt = Date.now();
+
+ updateJobStatus(
+ ctx.job,
+ "rendering",
+ `Streaming frame ${i + 1}/${ctx.totalFrames} (segment ${segment.index + 1}/${ctx.segmentCount})`,
+ Math.round(25 + ((i + 1) / ctx.totalFrames) * 55),
+ ctx.onProgress,
+ );
+ }
+ const encodeResult = await encoder.close();
+ encoderClosed = true;
+ if (!encodeResult.success) {
+ throw encoderFailureError(`Segment ${segment.index} encode failed`, encodeResult);
+ }
+ return encodeResult.durationMs;
+ } finally {
+ // A throw above (capture failure, abort, write error) leaves ffmpeg
+ // running; close() is idempotent so this is safe next to the success
+ // path's close.
+ if (!encoderClosed) {
+ await encoder.close().catch(() => {});
+ }
+ }
+}
+
+function resolveDeps(input: CaptureSegmentedStageInput): SegmentedStageDeps {
+ return {
+ spawnEncoder: input.deps?.spawnEncoder ?? spawnStreamingEncoder,
+ captureFrame: input.deps?.captureFrame ?? captureFrameToBuffer,
+ concat: input.deps?.concat ?? concatVideoFiles,
+ };
+}
+
+/** Reuse the probe session when there is one, else open a fresh one. */
+async function openSegmentedSession(input: CaptureSegmentedStageInput): Promise<CaptureSession> {
+ // Same reasoning as the streaming stage: the resolved forceScreenshot comes
+ // from the immutable plan, not from the caller-owned cfg.
+ const captureCfg: EngineConfig =
+ input.cfg.forceScreenshot === input.plan.forceScreenshot
+ ? input.cfg
+ : { ...input.cfg, forceScreenshot: input.plan.forceScreenshot };
+ const videoInjector = input.createRenderVideoFrameInjector();
+ if (input.probeSession) {
+ prepareCaptureSessionForReuse(input.probeSession, input.framesDir, videoInjector);
+ return input.probeSession;
+ }
+ return createCaptureSession(
+ input.fileServer.url,
+ input.framesDir,
+ input.buildCaptureOptions(),
+ videoInjector,
+ captureCfg,
+ );
+}
+
+/** Stream-copy the finished segments into the video-only file, or throw. */
+async function concatSegments(
+ concat: SegmentedStageDeps["concat"],
+ segmentPaths: readonly string[],
+ videoOnlyPath: string,
+ abortSignal: AbortSignal | undefined,
+ cfg: EngineConfig,
+): Promise<void> {
+ const result = await concat(segmentPaths, videoOnlyPath, abortSignal, cfg);
+ if (result.success) return;
+ throw encoderFailureError("Segment concat failed", {
+ error: result.error,
+ failureReason: result.externalInterruption ? "external_interruption" : undefined,
+ });
+}
+
+export async function runCaptureSegmentedStage(
+ input: CaptureSegmentedStageInput,
+): Promise<CaptureSegmentedStageResult> {
+ const {
+ workDir,
+ videoOnlyPath,
+ job,
+ totalFrames,
+ cfg,
+ log,
+ outputFormat,
+ streamingEncoderOptions,
+ abortSignal,
+ assertNotAborted,
+ onProgress,
+ dedupPerfs,
+ segmentFrames,
+ updateCaptureObservability,
+ } = input;
+ const { spawnEncoder, captureFrame, concat } = resolveDeps(input);
+
+ const segments = planSegments(totalFrames, segmentFrames);
+ mkdirSync(join(workDir, "segments"), { recursive: true });
+ const session = await openSegmentedSession(input);
+
+ let lastBrowserConsole: string[] = [];
+ let encodeMs = 0;
+ const segmentPaths: string[] = [];
+
+ try {
+ if (!session.isInitialized) {
+ await initializeSession(session);
+ }
+ await completeDeferredDrawElementInit(session);
+ assertNotAborted();
+ lastBrowserConsole = session.browserConsoleBuffer;
+
+ const ctx: SegmentCaptureContext = {
+ session,
+ job,
+ cfg,
+ totalFrames,
+ segmentCount: segments.length,
+ workDir,
+ streamingEncoderOptions,
+ spawnEncoder,
+ captureFrame,
+ stallTimeoutMs: resolveCaptureStallTimeoutMs(),
+ abortSignal,
+ assertNotAborted,
+ onProgress,
+ };
+
+ for (const segment of segments) {
+ assertNotAborted();
+ updateCaptureObservability?.({ capturePath: "segmented", segmentIndex: segment.index });
+ try {
+ encodeMs += await captureSegment(ctx, segment);
+ } catch (err) {
+ if (!(err instanceof SegmentEncoderSpawnError)) throw err;
+ // Nothing captured yet, so the caller can still replan onto the plain
+ // streaming path. A later segment cannot: earlier segments are
+ // already encoded and would be discarded.
+ if (segment.index > 0) throw err.reason;
+ log.warn(
+ "[Render] Segment encoder spawn failed; falling back to single-encoder streaming.",
+ {
+ error: err.message,
+ outputFormat,
+ segments: segments.length,
+ durationSeconds: job.duration,
+ },
+ );
+ return { success: false };
+ }
+ segmentPaths.push(segmentOutputPath(workDir, segment.index));
+ }
+
+ dedupPerfs.push(getCapturePerfSummary(session));
+ } catch (error) {
+ lastBrowserConsole = session.browserConsoleBuffer;
+ throw wrapCaptureStageError(error, lastBrowserConsole);
+ } finally {
+ lastBrowserConsole = session.browserConsoleBuffer;
+ await closeCaptureSession(session);
+ }
+
+ await concatSegments(concat, segmentPaths, videoOnlyPath, abortSignal, cfg);
+
+ return {
+ success: true,
+ encodeMs,
+ probeSession: null,
+ lastBrowserConsole,
+ workerCount: 1,
+ segments: segments.length,
+ segmentPaths,
+ };
+}
diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.ts b/packages/producer/src/services/render/stages/captureStreamingStage.ts
index 0dc8e76f54..170c2acfa7 100644
--- a/packages/producer/src/services/render/stages/captureStreamingStage.ts
+++ b/packages/producer/src/services/render/stages/captureStreamingStage.ts
@@ -95,7 +95,7 @@ import type { SdrStreamingCapturePlan } from "../capturePlan.js";
const DEFAULT_CAPTURE_STALL_MS = 60_000;
const DE_STALL_POLL_MS = 5_000;
-function resolveCaptureStallTimeoutMs(): number {
+export function resolveCaptureStallTimeoutMs(): number {
// HF_DE_PARALLEL_STALL_MS is the pre-rename name (this config used to guard
// only the parallel path). Bridged for one release so an already-deployed
// ops surface (runbook, ConfigMap, ...) tuning the old name doesn't
@@ -145,7 +145,7 @@ class SequentialCaptureStallError extends Error {
}
}
-function raceAgainstStall<T>(
+export function raceAgainstStall<T>(
promise: Promise<T>,
deadlineMs: number,
input: {