import { type MediaClock } from "./clock"; import { type DisplayBoxResolutionOptions } from "./decode-resolution"; import type { FrameId, FrameLanding } from "./frame-timeline"; import { type EngineDiagnostics } from "./diagnostics"; import { type SeekIntent } from "./scrub-cursor"; import { type EngineTrace } from "./trace-recorder"; import { type EngineReadySnapshot } from "./types"; import { type DiagnosticsEvent, type EngineLoadConfig, type MirrorEvent, type PresentedFrameEvent, type SerializedViewport } from "./worker-protocol"; export interface EngineCoreOptions { /** Sink for broadcast state. The worker host serializes each event onto * the state plane; tests collect them to assert transitions. */ emit: (event: MirrorEvent) => void; /** Sink for the diagnostics broadcast (the non-mirror 'diag' arm). Optional: * when absent the broadcaster has nowhere to post, so a consumer that never * wires it pays nothing. The worker host wires it to the same postMessage. */ emitDiagnostics?: (event: DiagnosticsEvent) => void; /** Sink for the pixel plane, which carries frames only in "frames" * presentation mode. The VideoFrame is handed over on the transfer list, so * a host wiring this to postMessage detaches the worker's reference by * posting it. Unwired there is no receiver, so the core closes each frame * instead of leaking it. */ emitPresentedFrame?: (event: PresentedFrameEvent, transfer: Transferable[]) => void; /** Clock seam. Defaults to the wall-clock PerformanceMediaClock; tests * inject a fake so they can drive media time deterministically. */ clock?: MediaClock; } /** * The engine, with every main-thread concern removed. Owns the clock, cursor, * and render controller; runs entirely inside the worker. It never touches the * DOM, a React store, the playhead, or the imperative handle. * * It speaks two languages. Broadcast state (time, frame index, status, * duration, seeking) leaves through the `emit` callback. Command results that * the main thread cannot predict (load metadata, the frame a step lands on) * are method return values the worker host correlates back to the caller. * * Time is emitted only while playing. Paused positions are owned by the main * thread (written optimistically on scrub, or applied from step's return), so * the core never emits a competing time that would yank a settled playhead. */ export declare class EngineCore { private decodeStrategy; private displayResize; private readonly emit; private readonly emitDiagnostics; private readonly emitPresentedFrame; private readonly clock; private cursor; private residency; private controller; private canvas; private viewport; /** The box the host said it paints these frames into, kept from the load * command. Under "frames" presentation nothing ever measures a canvas here, * so this is the only display geometry the engine is ever given. */ private displayBox; private metadata; /** * The decoder failure the runtime has given up on, latched. Nothing the * transport is asked to do afterwards can decode a frame, so nothing it is * asked to do may report otherwise: a play() that answered "playing" over a * decoder that had already been condemned is how a source with one unusable * entry point read as healthy for the rest of the session. */ private decodeFailure; private presentation; private durationMs; private paintSeq; private playing; /** The frame the last step landed on. A serialized burst resolves each * step before its rAF paints, so getLastPaintedMs lags by one or more * steps; basing the next step on the actual landing keeps every step in a * burst advancing exactly one frame instead of re-stepping a stale base. */ private lastStepLanded; /** Where the current seek's walk actually landed, known once a crisp frame * for it has painted. A requested time is not a frame time: it comes from a * marker rail or a pointer, so it usually sits between two samples. Walking * backward from it reaches the sample already on screen and the press reads * as dead. Null until that crisp paint arrives, so a step pressed before it * still falls back to the clock. */ private seekLanded; /** The seek still waiting on that paint, or null when none is. Every paint * the engine makes runs through this latch, and the render loop paints one * frame per animation frame from a stash a previous seek may have filled, * so without the target on it any leftover frame answers for the seek in * flight and publishes itself as the playhead. */ private awaitedSeek; private seekGeneration; private stepCommandGeneration; /** Wall stamp of a seek being served by re-anchoring the playback walk, or * null when no such seek is waiting on its crisp frame. */ private playSeekStartedAtMs; private playSeeks; private playSeekSamples; private playSeekSumMs; private playSeekMaxMs; /** The frame the last paint put up, for the diagnostics screen readout. */ private lastPaintedId; /** Last frame the host confirmed reached its display surface. */ private lastHostFrame; /** Rejects an older refresh that completes after a newer one in one epoch. */ private lastHostPaintSeq; /** Main-thread visibility pauses only the wait for host presentation. */ private presentationVisible; /** Mirrors WebVideoEngine's interactive-seek latch: true when a drag paused a * playing engine, so endInteractiveSeek knows to resume. */ private resumeAfterInteractiveSeek; /** Worker-realm broadcast timer handle, or null when diagnostics are off. */ private diagnosticsTimer; /** Wall time the cursor was first seen draining a seek, or null while it is * not. How long a state has lasted is a diagnostics question, so it is * timed here rather than on the scheduler, whose clock is the seam tests * drive latency measurements through. */ private drainingSinceMs; private readonly paintRateMeter; private readonly presentedRateMeter; /** Lazily allocated on traceArm, freed on disarm; zero memory off. */ private traceRecorder; /** The last assembled trace, kept after disarm so a stopped capture stays * downloadable until the next arm. Null while armed or never captured. */ private stoppedTrace; constructor(options: EngineCoreOptions); /** * Receives the transferred display canvas and its measured box. Stored * even when the controller does not exist yet (bindCanvas can arrive * before load) and bound as soon as load builds the controller. Passing * null tears the binding down and stops the render loop. */ setCanvas(canvas: OffscreenCanvas | null, viewport?: SerializedViewport): void; load(config: EngineLoadConfig): Promise; setDisplay(display: DisplayBoxResolutionOptions): Promise; private afterDisplayResize; play(): void; pause(): void; togglePlayback(): void; /** * Sets how fast media time runs against wall time. The clock re-anchors, so * a change mid-playback bends the slope without moving the playhead, and the * decode-ahead buffer keeps its frames: they are positions in media time, * which a rate change does not touch. Applied while paused it simply waits, * since a paused clock advances at no rate at all. * * Throws on a rate outside the supported forward range. */ setPlaybackRate(rate: number): void; getPlaybackRate(): number; /** Fire-and-forget seek onto a named frame. Emits no playhead: the main * thread snapped the gesture and wrote it. Paints a cache preview, then * walks the cursor. */ scrub(frameIndex: number, intent?: SeekIntent): void; /** Moves a running playback walk to `tSec`. The clock is already there. */ private reanchorPlayback; /** Closes the wait of a seek served by re-anchoring, at the crisp paint that * ends it. A seek that walked the cursor leaves no stamp; the scheduler * times those. Stopping the transport abandons the wait: its frame can * still paint minutes later, and the idle time between is not a wait * anyone had, so the seek keeps its count and loses its sample. */ private closePlaySeekWait; commit(frameIndex: number): Promise; seekToKey(timeMs: number): Promise; /** * Moves one frame along the source in presentation order and returns where * it landed, or null at either end. Only the worker knows which frame a * decode produced, so the landing is the command's return value. The stepped * frame paints worker-side via the controller and emits a paint like any * other. */ step(direction: 1 | -1): Promise; /** Append a runtime event to the trace ring, stamped with worker-clock time * since arm. Predicted-false and free when no trace is armed. */ private pushTraceEvent; /** Broadcast a status transition and record it on the trace ring, so an * exported trace shows the playback-state timeline alongside paints/seeks. */ private emitStatus; /** * The runtime can no longer deliver pixels, whether decoding stopped or the * frames handoff failed. Stop the transport first, then report, so the status * a consumer sees and what the engine is doing agree. */ private handleTerminalFailure; /** Says the failure again for whoever just asked the transport to move. A * consumer that only listens for changes has already been told; one that * reads the status after its own command has to find the same answer. */ private republishFailure; beginInteractiveSeek(): void; endInteractiveSeek(): void; dispose(): Promise; /** True only when the cursor exists and reports settled. Mirrors * WebVideoEngine.isIdle for tests; the facade derives its own from state. */ isIdle(): boolean; /** Engine diagnostics snapshot (renderer, track facts, scheduler stats), or * null before load. The scheduler field is null on the uncached cursor. */ getStats(): EngineDiagnostics | null; private observeSeekIdle; private handleEnded; private awaitSeekLanding; /** Main-thread document visibility; decoding/watchdogs remain active. */ setPresentationVisibility(visible: boolean): void; private isCurrentSeek; private forgetSeekLanding; private abandonAwaitedSeek; /** Ends an impossible landing. Awaitable movement rejects with the engine's * terminal error; a scrub has no consumer, so it is released quietly. */ private failAwaitedSeek; /** Releases the latch of a seek that has already answered its caller. The * landing rode back on the return value, so a paint arriving after it would * move the playhead to somewhere the caller was never told about. */ private closeSeekLanding; /** * Whether this paint is the landing of the seek waiting on one. * * An exact walk answers at or before the frame it aimed at, and no further * back than the sample next to it, so the target falls inside the answering * frame's own span. That span is the test: a frame decoded for some earlier * position sits outside it however recently it was painted. The aimed-at * frame answers without it, because a track's last frame has an empty span * when its file states no duration for it. */ private answersAwaitedSeek; /** The frame table of the loaded source. Reached only from paths that have * already established a cursor, which is what carries it. */ private timeline; /** * Points the background walk at where the viewer is, as a byte offset. The * file's own byte layout is not exposed, so this reads position as a share of * duration: enough to order the walk outward from the playhead, and wrong by * at most the amount the bitrate varies. */ private aimResidency; private onPaint; /** Makes only a frame the host actually rendered authoritative for playback * time and pause settlement. An older navigation or refresh cannot move the * clock backward after a newer frame has won. */ acknowledgePresentedFrame(paintSeq: number, frameId: FrameId, navigationGeneration: number): void; private beginPresentationGeneration; /** * Posts one frame with the identity of the paint it came from, in the same * message. With no sink wired there is no receiver, so the frame is closed * here: the controller has already let go of it, and a frame left open pins * a decoder buffer. */ private present; /** * Starts the worker-realm broadcast timer at hz (default BROADCAST_HZ) and * flips the controller's per-rAF counter gate on. Decode-independent: the * timer callback does synchronous reads plus one post, never an await and * never the sink, so it runs between event-loop tasks, not inside a decode. */ diagnosticsStart(hz?: number): void; diagnosticsStop(): void; /** Lazily allocate the trace rings and begin capturing. windowMs sizes the * snapshot ring alone: the event ring is fed by paints and gestures at no * fixed rate, so wall clock cannot size it. */ traceArm(windowMs: number): void; /** Stop capturing and free the rings, but keep the assembled trace so it can * still be exported. A record-then-stop-then-download flow would otherwise * lose the capture, since stop used to null the recorder outright. */ traceDisarm(): void; /** The current capture if still armed, else the last stopped capture. Non * destructive so a download can be retried; a new arm clears the stopped one. */ traceExport(): EngineTrace | null; /** * Assembles ONE snapshot and posts it as the 'diag' event. When a trace is * armed, the SAME reference is ring-appended, so there is no second * serialization. Synchronous: reads current stats, never awaits, never paints. */ private broadcastDiagnostics; private assembleSnapshot; private statusString; /** * CSS width the picture occupies inside the box the host declared, native * aspect fitted into it, or null when no box was declared. A portrait source * in a landscape box paints far narrower than the box, so the fit is what the * ratio has to be measured against. */ private paintedBoxCssWidth; /** The ratio whichever side measured one reported, or null when neither did. * The engine has no window of its own to read it off. */ private devicePixelRatio; private traceEnvironment; }