// fallow-ignore-file complexity code-duplication /** * Frame Capture Service * * Uses Puppeteer to capture frames from any web page implementing the * window.__hf seek protocol. Navigates to a file server URL, waits for * the page to expose window.__hf, then captures frames deterministically * via Chrome's BeginFrame API or Page.captureScreenshot fallback. */ import { type Browser, type CDPSession, type HTTPRequest, type Page, type Protocol, type Viewport, type ConsoleMessage, } from "puppeteer-core"; import { createHash } from "crypto"; import { existsSync, mkdirSync, writeFileSync } from "fs"; import { availableParallelism } from "os"; import { join } from "path"; import { COMPOSITION_SOURCE_URL, MEDIA_RENDER_ID_ATTR, quantizeSeekTime, quantizeTimeToFrame, fpsToNumber, resolveAuthoredTimingWindow, AUTHORED_SOURCE_BEGIN, AUTHORED_SOURCE_END, RUNTIME_BOOTSTRAP_ATTR, SCENE_CALLBACK_ERROR_PREFIX, type RawAuthoredTiming, terminalText, } from "@hyperframes/core"; import { readReferenceBackground } from "./referenceBackground.js"; import { holdRenderFrameVideos } from "./renderFrameVideoHold.js"; import { asDrawElementCaptureFailure, DrawElementCaptureError } from "./drawElementCaptureError.js"; import { encodePng } from "../utils/alphaBlit.js"; import { DEFAULT_SAMPLES_PER_FRAME, MotionBlurAccumulator, SPATIAL_TWEEN_PROPERTIES, adaptiveSampleCount, motionBlurProbeTimes, motionBlurSampleTimes, motionBlurWindowIsStatic, probeDiffMagnitude, resolveMotionBlurPlan, type MotionBlurPlan, } from "./motionBlur.js"; import { describePageMotionBlur, describePageMotionBlurAtEnd, installPageMotionBlur, pageMotionBlurRecorder, } from "./pageMotionBlur.js"; // ── Extracted modules ─────────────────────────────────────────────────────── import { acquireBrowser, releaseBrowser, forceReleaseBrowser, buildChromeArgs, resolveBrowserGpuMode, captureWithoutWaylandDisplay, resolveHeadlessShellPath, compositionRequiresWebGpu, assertWebGpuAdapterAvailable, usesSoftwareWebGpu, type BrowserLease, type CaptureMode, } from "./browserManager.js"; import { openPage } from "./openPage.js"; import { boundedPageText, keptWithinBudget, listedInMessage, PAGE_LIST_MAX, PAGE_TEXT_MAX_CHARS, SERVED_SCRIPTS_MAX, warningBudgetOf, type WarningBudget, } from "./pageTextBounds.js"; import { beginFrameCapture, forgetBeginFrameCapture, ensureRenderFrameSiblings, getCdpSession, pageContentExceedsCaptureHeight, pageScreenshotCapture, initTransparentBackground, capturesAlpha, shouldDefaultCaptureBeyondViewport, } from "./screenshotService.js"; import { classifyGpuRenderer, detectGpuBackend, drawElementGate, type DrawElementGateReason, injectDrawElementCanvas, captureDrawElementFrame, forcePreservedDrawingBuffer, instrumentAcceleratedCanvases, initDrawElementWorkerEncode, cleanupDrawElementWorkerEncode, produceDrawElementFrame, produceDrawElementFrameBatch, DE_CANVAS_NOT_INITIALIZED_CODE, } from "./drawElementService.js"; import { initThreeDProjection, scanCssEffects } from "./threeDProjection.js"; import { planRiskFrames, scanCssEffectLiveFrames, riskSessionFits, withFramesAfterCallback, MAX_RISK_FRAME_FRACTION, } from "./riskFrames.js"; import { getAvailableMemoryMb } from "./systemMemory.js"; import { isPsnrFilterAvailable } from "../utils/psnrFilterAvailability.js"; import { DEFAULT_CONFIG, applyConcreteGpuScreenshotClamp, type EngineConfig } from "../config.js"; import type { CaptureOptions, CaptureVideoMetadataHint, CaptureResult, CaptureBufferResult, CapturePerfSummary, CaptureWarning, HfSeekOptions, PageMotionBlurSummary, SubTimelineWaitMemo, SubTimelineWaitOutcome, } from "../types.js"; import { PROVENANCE_VERSION } from "../utils/renderProvenance.js"; import { cloneCaptureWarnings } from "./captureWarning.js"; import { installMediaRenderIdBridge } from "./mediaRenderIdBridge.js"; import { createChromeMemorySampler, type ChromeMemorySampler, type ChromePids, } from "./chromeMemorySampler.js"; import { sampleProcessRss } from "../utils/processRss.js"; import type { CompositionLengthSource } from "@hyperframes/core/runtime/composition-length"; import { assertVariablesMatchPage } from "./variablesCheck.js"; import { describeLateImage, type RawResourceTiming } from "./lateImageTiming.js"; export { isMemoryExhaustionError, isTransientBrowserError } from "./captureFailure.js"; export type { CaptureOptions, CaptureResult, CaptureBufferResult, CapturePerfSummary }; /** Called after seeking, before screenshot. Use for video frame injection or other pre-capture work. * `heldVideoTime` (motion-blur samples only) is the output frame's time: a video on screen at * both times shows its frame for `heldVideoTime`, so footage does not smear. */ export type BeforeCaptureHook = (( page: Page, time: number, heldVideoTime?: number, ) => Promise) & { /** A hook with state of its own, for a second page; absent when the hook cannot be copied. */ fresh?: () => BeforeCaptureHook | null; }; /** The per-frame wait a capture is in, worded for the stall error a user reads. */ type CaptureStep = | "seeking the timeline" | "decoding CSS background images" | "injecting video frames" | "waiting for page seek handlers" | "loading color-grading LUTs" | "compositing the page" | "capturing the frame" | "waiting for a late image"; export interface CaptureSession { browser: Browser; /** Exact ownership token for this browser acquisition. */ browserLease?: BrowserLease; page: Page; options: CaptureOptions; serverUrl: string; outputDir: string; /** The composition served at `serverUrl` declares `data-requires-webgpu`. */ requiresWebGpu?: boolean; /** The browser was launched to run that WebGPU on SwiftShader ({@link usesSoftwareWebGpu}). */ softwareWebGpu?: boolean; onBeforeCapture: BeforeCaptureHook | null; isInitialized: boolean; /** * Static-frame dedup (default-on; opt out with `HF_STATIC_DEDUP=false`): indices of frames byte-identical * to their predecessor (no GSAP tween / clip cut active in either), predicted from * window.__timelines and empirically anchor-verified. These reuse `lastFrameBuffer` * instead of re-seeking + re-screenshotting. Undefined when disabled or ineligible. */ staticFrames?: Set; /** Last non-deduped frame buffer, reused for every `staticFrames` index in its run. */ lastFrameBuffer?: Buffer; /** Absolute index represented by lastFrameBuffer; reuse requires direct adjacency. */ lastFrameAbsoluteIndex?: number; /** Count of frames served from a reused buffer (dedup telemetry). */ staticDedupCount?: number; pageMotionBlur?: PageMotionBlurSummary; /** Live Chrome memory sampler; started in initializeSession, stopped in closeCaptureSession. */ chromeMemory?: ChromeMemorySampler; /** * Resolved sub-frame motion-blur plan, or undefined when off. Set once by * `resolveSessionMotionBlur` at the end of initialization, where the capture mode has * settled, so an unsupported combination fails before the first frame rather than * silently rendering unblurred. */ motionBlur?: MotionBlurPlan; /** Frames confirmed to move only non-spatial properties (opacity, colour); set for * adaptive motion blur. Absent from this set means "probe" — see computeStaticFrameSet. */ motionBlurNonSpatialFrames?: Set; // ── Static-dedup observability (set by armStaticDedup; surfaced via // getCapturePerfSummary → RenderPerfSummary → the render_complete event) ── // `armed` derives from the verified staticFrames set. Predicted count is stored // separately because partial budget arming intentionally makes them diverge. /** Dedup was enabled for this render (default-on; opt out with `HF_STATIC_DEDUP=false`). */ staticDedupEnabled?: boolean; /** Original predicted-static count, before profitability or partial verification. */ staticDedupPredictedCount?: number; /** Bounded verifier taxonomy and counters for debug/perf reporting. */ staticDedupVerification?: StaticVerificationResult; /** * Short machine code for WHY dedup did not arm, for a low-cardinality breakdown. * One of: `capture_mode` | `video_injection` | `page_composite` | * `ineligible` | `unprofitable` | `verification_failed` | `verification_budget`. * Undefined when armed or disabled. */ staticDedupSkipReason?: string; /** With skip reason `ineligible`: `no_static_frames` or `+`-joined {@link StaticDedupIneligibleCause}s. */ staticDedupIneligibleCause?: string; /** The init-time page analysis of a check deferred by `deferStaticDedup`; `armDeferredStaticDedup` runs it. */ staticDedupDeferred?: StaticFrameStats; // Tracks whether the page/browser handles have already been released by // closeCaptureSession. Used to make closeCaptureSession idempotent under // browser-pool semantics (see the function body for the full invariant). pageReleased?: boolean; browserReleased?: boolean; browserConsoleBuffer: string[]; /** * Script resources that failed to load (request failure or HTTP >= 400). * pollSubCompositionTimelines fail-fasts on these: a comp whose timeline * script 404'd can never register window.__timelines[id], so waiting the * full playerReadyTimeout (45s) buys nothing (~1% of wild local renders * were hitting that wall — a 705-render spike at the 45s setup bucket). */ scriptLoadFailures: string[]; /** Closed origin and error of each of `scriptLoadFailures`, same order. */ scriptLoadCauses?: ScriptLoadCause[]; /** Uncaught page errors; a timed-out timeline wait with any of these becomes a script failure. */ pageErrors: string[]; throwSiteLookups?: Set; /** The text and kinds of `warnings`, against WARNINGS_TEXT_MAX_CHARS. */ warningBudget?: WarningBudget; /** True once this session honoured `options.strictVariables`: the check ran and passed. */ strictVariablesChecked?: boolean; /** The first VFX chain error; its frames would lack the effect, so it stops the render. */ vfxFailure?: string; /** Set once the page loads more distinct scripts than SERVED_SCRIPTS_MAX; it stops the render. */ tooManyServedScripts?: boolean; /** Outcome of the sub-composition timeline wait: ready | timeout | script_failure. */ subTimelineWaitOutcome?: SubTimelineWaitOutcome; /** * Composition ids still unregistered when the timeline wait gave up. Already * computed for the stderr warning; kept on the session so the STRUCTURED * warning can name them too — a programmatic caller reads `warnings`, not * our console output. */ pendingTimelineIds?: string[]; isolatedCompositions?: IsolatedComposition[]; /** The render's shared memo when the caller passed one, else this session's own. */ subTimelineWaitMemo: SubTimelineWaitMemo; /** Structured readiness warnings surfaced to the producer's render policy. */ warnings: CaptureWarning[]; /** Images still loading when capture began: a frame that shows one waits for it (waitForShownLateImages). */ lateImages?: Set; initTelemetry?: { initDurationMs: number; tweenCount: number; /** Live DOM element count at end of init; undefined when the measurement itself failed. Observational — see collectSessionInitTelemetry. */ elementCount?: number; }; capturePerf: { frames: number; seekMs: number; beforeCaptureMs: number; screenshotMs: number; totalMs: number; /** Per-frame capture durations (batch frames get the batch mean). Basis for * the warmup-robust p50 in the perf summary. */ frameMs: number[]; }; captureMode: CaptureMode; /** * Browser LAUNCH mode, immutable after createCaptureSession. `captureMode` * is reassigned by initializeSession (e.g. to "drawelement"), so callers * that need to know whether this browser actually drives BeginFrame (the * SwiftShader liveness probe) read this field instead. */ launchCaptureMode: CaptureMode; // BeginFrame state beginFrameTimeTicks: number; beginFrameIntervalMs: number; beginFrameHasDamageCount: number; beginFrameNoDamageCount: number; beginFrameSeekPresented?: boolean; /** Optional producer config — when set, overrides module-level env var constants. */ config?: Partial; /** True if running on SwiftShader (detected at init). Undefined before init. */ isSwiftShader?: boolean; /** * Low-cardinality GPU bucket (`/`, e.g. `d3d11/nvidia`) * derived from the WebGL renderer at DE session init. Surfaces in * CapturePerfSummary → render telemetry so backend-specific drawElement * damage (Metal vs D3D11 vs GL) clusters attributably. The raw * driver-supplied string is deliberately NOT retained — see * classifyGpuRenderer. */ gpuRenderer?: string; /** drawElementImage canvas was injected and is ready for capture. */ drawElementReady?: boolean; /** * Worker-encode pipeline is active for this session. Set by * `initDrawElementOrTransparentBackground` when `enableDrawElementWorkerEncode` * is true and capture mode resolved to "drawelement". */ workerEncodeEnabled?: boolean; /** * Frame indices that must be captured via screenshot rather than drawElement. * Populated at init by the clip-cut boundary predictor (Lim 6): frames where * the outgoing clip is dropped a frame before the incoming clip's paint record * is ready → black frame. Controlled by `HF_FAST_CAPTURE_BOUNDARY_SS=false`. * Empty/undefined when the predictor produces no frames. */ clipBoundaryFrames?: Set; /** * Frames drawElement cannot reproduce, for the caller to capture with a screenshot session. * Set only when the caller can (worker-encode pipeline); drawElement capture throws on these. */ deRiskFrames?: Set; /** The effects behind {@link deRiskFrames}, for the capture log. */ deRiskReason?: string; /** Rolling drawElement frame byte-sizes (last ~60), for silent-blank-drop detection: * drawElement intermittently returns an anomalously small (blank) frame with no * throw; a frame far below the running median is re-captured via screenshot. */ deFrameSizes?: number[]; /** Absolute floor of the serial drawElement size guard. Starts at 20000 bytes and drops to * half of a small frame that redraws byte-identically. */ deAbsFloor?: number; /** The last small drawElement frame that redrew byte-identically; an equal frame is kept * without a redraw. */ deAcceptedSmall?: Buffer; /** Last non-deduped encode result, reused for a static frame on the drawElement * worker-encode path (mirrors `lastFrameBuffer` on the screenshot path). Only set * when static-frame dedup is armed on the drawElement path. */ lastEncodeResult?: Promise; /** Frame index lastEncodeResult belongs to — static-dedup reuse must verify * every frame in (lastEncodeResultFrame, i] is predicted-static (under the * interleaved parallel stride the "previous" produced frame is i−N, and * reusing it for frame i is only valid when the whole gap is static). */ lastEncodeResultFrame?: number; /** Per-render self-verification ground truth (ungated-release safety net): * K screenshot frames captured at init BEFORE the drawElement canvas is * injected (the only window where a page screenshot shows the live DOM, not * the capture canvas's stale bitmap). The producer drain compares the DE * frame at each index against these; a breach aborts the render with * DrawElementVerificationError and the orchestrator re-renders via the * screenshot path. */ deVerifyFrames?: Map; /** Low-cardinality init-gate reason when drawElement routed to baseline (telemetry). */ deGateReason?: string; /** * Full trigger string when drawElement gated off to the screenshot fallback * path — preserves the specific CSS effect (`filter:blur`, * `filter:drop-shadow`, `backdrop-filter`, `clip-path`) that * {@link deGateReason} sanitizes down to a low-cardinality bucket. Populated * on the same fallback-gate branches as `deGateReason`; consumed by the * `capture_fallback_profile` observability checkpoint gated behind * `HF_PROFILE_FALLBACK_CAPTURE=true`. See * `packages/producer/src/services/render/fallbackCaptureProfile.ts`. */ deFallbackTrigger?: string; /** Wall-clock ms spent capturing self-verification ground truth at init (telemetry). */ deVerifyInitMs?: number; /** Count of paint-record/canvas failures requiring fresh screenshot capture (telemetry). */ deNcprFallbacks?: number; /** * Count of drawElement frame captures that blew `HF_DE_FRAME_TIMEOUT_MS` * because the renderer stopped scheduling after drawElementImage returned * (PRINFRA-488). Each one aborts the drawElement attempt so the whole render * retries via screenshot. */ deFrameTimeouts?: number; captureStep?: CaptureStep; /** * drawElement init passed every gate but stopped before verification + * canvas injection: the session has no video-frame injector yet (probe * sessions initialize before extraction) and the comp has