import type { DecodeDimensions } from "./decode-resolution"; import { type Rotation } from "./rotation"; import type { VideoSampleLike } from "./scrub-cursor"; /** * One packet as the session submits it. Mirrors the fields of mediabunny's * EncodedPacket the decoder needs, so the session never imports mediabunny. */ export interface EncodedPacketLike { readonly data: Uint8Array; readonly type: "key" | "delta"; readonly timestamp: number; readonly duration: number; } export interface PacketRetrievalOptionsLike { readonly metadataOnly?: boolean; readonly verifyKeyPackets?: boolean; } /** The slice of mediabunny's EncodedPacketSink the session decodes through. */ export interface PacketSource { getKeyPacket(timestamp: number, options?: PacketRetrievalOptionsLike): Promise; getNextKeyPacket(packet: EncodedPacketLike, options?: PacketRetrievalOptionsLike): Promise; packets(startPacket?: EncodedPacketLike, endPacket?: EncodedPacketLike, options?: PacketRetrievalOptionsLike): AsyncGenerator; } /** The slice of WebCodecs' VideoDecoder the session drives. Chunks cross as * inits so the session never reaches for a platform constructor. */ export interface VideoDecoderLike { configure(config: VideoDecoderConfig): void; decode(chunk: EncodedVideoChunkInit): void; flush(): Promise; reset(): void; close(): void; } export interface DecodeSessionOptions { readonly packets: PacketSource; readonly config: VideoDecoderConfig; readonly createDecoder: (init: VideoDecoderInit) => VideoDecoderLike; /** Dimensions used to take ownership of decoder output pixels when set. */ readonly outputWidth?: number; readonly outputHeight?: number; /** Test seam for taking ownership of decoder output pixels. */ readonly snapshotFrame?: (frame: VideoFrame, width: number, height: number) => VideoFrame; /** * The track's quarter turn, which the session's frames carry and its draw * applies. A raw decoded picture holds the stored pixels and nothing about * the display matrix, so this is the only route the turn has here, and a * caller that forgets it paints every portrait recording sideways. */ readonly rotation: Rotation; /** * Ceiling on waiting for one decoder output while chunks are in flight; * defaults to OUTPUT_TIMEOUT_MS. Overridable so a test can drive the * silent-decoder path without waiting out the production ceiling. */ readonly outputTimeoutMs?: number; } /** * Whether the session can drive a track with this decoder config. The gate that * routes a source here and the constructor that refuses everything else read the * same predicate. */ export declare function sessionDrivable(config: VideoDecoderConfig): boolean; /** * The three retrievals the session answers, mirror for mirror with the sink * slices the other decode paths ride. Held as an interface so the provider that * wraps it stays fake-injectable under test. */ export interface SessionFrameSource { resizeOutput?(dimensions: DecodeDimensions): Promise; frameAt(targetS: number): Promise; framesFrom(startS: number): AsyncGenerator; framesCovering(startS: number, endS: number): AsyncGenerator; /** Earliest position still reachable without re-anchoring, or -Infinity when * the session has not been positioned yet. A decoder only moves forward, so * asking for anything below this costs a walk from the enclosing keyframe. */ readonly reachableFromS: number; /** Every frame the decoder has output since open, discarded pre-roll * included; monotonic. */ readonly framesDecoded: number; } /** * One long-lived VideoDecoder, held across seeks. * * A decoder can only ever move forward, and every flush re-arms its demand for a * key frame, so a runtime that flushes per retrieval pays a walk back to the * nearest true IDR on every seek. This session flushes only at end of stream: * a seek at-or-ahead of the read head, inside the current anchor span, decodes * only the packets between the two, and a backward jump or a jump past the span * re-anchors. Positioning is the only thing that costs a walk. * * One decoder serving several readers is the whole point, and it is also the * hazard: a scrub's frameAt and playback's framesFrom drive the same decoder, * the same packet iterator, and the same queue of decoded frames. So every * retrieval takes the decoder exclusively for the length of one frame, and a * reader displaced by someone else's re-anchor is told, rather than left to read * the emptied queue as end of stream and stop for good. * * Frames are handed out as VideoSampleLike and their close is the caller's, the * same obligation the zero-copy sample path carries. */ export declare class DecodeSession implements SessionFrameSource { private readonly options; private readonly keyPacket; private readonly prefixWidth; private decoder; private iterator; private peeked; /** Timestamp of the key packet after the anchor: the end of the span a * forward seek can reach without re-anchoring. */ private spanEndS; private exhausted; /** Timings the decoder still owes pictures for, in presentation order. */ private readonly pending; private readonly decoded; private wake; /** * Latched once the decoder is judged unable to decode this source at all. * Every later retrieval refuses with it instead of re-anchoring onto the * same failure, which is what turns a silent forever-retry into one honest * error the caller can show. */ private stalledError; /** * The current entry point's failure, held only until the walk that is owed a * picture decides what it means. It condemns the anchor, never the session: * a source whose sync table names one bad entry point still decodes from * every other one, and latching the first failure is what turned a seek into * a poisoned GOP into a player that never painted again. */ private anchorError; /** The entry currently feeding the decoder, or null before the first one. */ private entry; /** Entry points a decoder error has ruled out, by whole-microsecond * timestamp. Only ever grows: a bitstream does not change. */ private readonly rejectedAnchors; /** Where the live retrieval wants to be, so a re-anchor after a failed entry * aims at the position the caller asked for rather than the anchor's. */ private entryTargetS; /** The last picture handed out since the caller last chose a position, so a * re-anchor mid-walk resumes rather than replays. */ private servedS; private closed; private anchors; private framesDecodedCount; /** Where the decoder sits, kept in step with what it hands out. Read * synchronously by callers deciding what to ask for, so it cannot await. */ private reachable; /** Serializes retrievals; see the class note on shared-decoder exclusivity. */ private tail; /** Bumped by every re-anchor, so a reader can tell whether the decoder is * still where it left it or has been moved under it by another reader. */ private epoch; private readonly outputTimeoutMs; private readonly rotation; private outputWidth; private outputHeight; private readonly snapshotFrame; constructor(options: DecodeSessionOptions); /** Times the session has configured the decoder onto an anchor. */ get anchorCount(): number; /** Every frame the decoder has ever output, including walk pre-roll that is * discarded before the target: the honest denominator for what a paint * actually cost. Monotonic for the session's lifetime. */ get framesDecoded(): number; /** See SessionFrameSource. The oldest frame decoded but not yet handed out * when there is one, since those are still servable, else the last position * handed out. */ get reachableFromS(): number; resizeOutput({ width, height }: DecodeDimensions): Promise; /** The frame at or before `targetS`, or null when nothing precedes it. */ frameAt(targetS: number): Promise; /** * Frames from `startS` onward, beginning at the frame at or before it. The * walk from the anchor up to `startS` is decoded but not yielded, since the * caller asked to start there. * * Playback rides this for the length of a session, so it outlives any number * of scrubs. When one of those moved the decoder, the walk resumes from the * last frame it handed out rather than ending. */ framesFrom(startS: number): AsyncGenerator; /** * Every frame decoded while covering `[startS, endS]`, including the walk * from the anchor. Those prefix frames cost the same decode either way, so * yielding them hands the caller a span of frames for the price of the one * it asked for. * * This serves speculative sweeps, so a re-anchor by anyone else ends it: * chasing the span back would spend a foreground decode's worth of decoder * time on frames nobody is waiting for. */ framesCovering(startS: number, endS: number): AsyncGenerator; /** * Runs `op` with the decoder to itself. Retrievals interleave at frame * granularity, which bounds how long a foreground seek waits behind a * background sweep at one frame, while keeping any one walk's view of the * packet iterator, the in-flight count, and the decoded queue consistent. */ private exclusive; /** * The first frame after `afterS` once another reader has moved the decoder. * Re-positions and discards the frames already handed out, so a walk picks * up exactly where it left off however far away the decoder was taken. */ private resumeAfter; close(): void; /** Decodes through `targetS` and returns the last frame at or before it, * closing the frames walked past. */ private land; private positionFor; /** The earliest position still reachable without re-anchoring: the oldest * frame decoded but not yet handed out, or the next packet in line when * there is none. Decode runs ahead of the read, so the packet alone would * put the head past frames the session can still serve. */ private readHeadS; private anchorAt; /** * The packet to open a decode of `targetS` from: the container's own sync * sample, unless a decoder has already proved that one is not a legal entry * point, in which case the last verified IDR at or before the target. * * A sync sample that is itself an IDR is already the furthest-back entry * worth reaching for, so a failure there is a failure of the source. */ private resolveEntry; /** * Where the span a forward seek can reach without re-anchoring ends: the * first sync sample past the target that is still worth anchoring at. * * Skipping the rejected ones is what keeps the pre-roll paid for once. Ending * the span at an entry point already known not to decode would send the very * next seek into that GOP back to the same rejected anchor and back through * the same walk to recover from it. */ private spanEndAfter; /** Drops the work in flight and the frames it produced, in one turn, so no * output from the old anchor can land against the new one. */ private quiesce; private configureDecoder; /** One frame at or before `boundS`, or null once the bound is passed. A frame * decoded past the bound stays queued for the next read rather than being * handed out or thrown away. */ private pull; /** * Re-opens the decode from the last entry point ahead of the failed one, * which for an open GOP means the previous IDR plus a walk to the target. * * The failed anchor is struck off for the life of the session, so the cost is * paid once per bad entry point rather than once per seek into it. When there * is nothing further back to enter from, the failure is the source's and it * latches here. */ private enterFurtherBack; /** * Keeps the decoder's pipeline fed, regardless of which frame is being read. * A decoder emits nothing until it holds enough pictures, so submitting only * as far as the requested frame leaves the session waiting on output it is * refusing to make possible. Feeding stops once the frames already decoded * pile up, which is what bounds the memory the session holds. */ private fill; private peek; private drain; private awaitOutput; /** * Files a submitted chunk's timing in presentation order, which is the order * pictures come back in and is not the order chunks go in on a B-frame * source. */ private awaitTiming; /** * A decoder that echoes the timestamp it was handed names its own pending * entry, which survives an output being dropped. One that counts from an * origin of its own names nothing, and position is all that is left. Taking * position alone would let a single dropped output shift every picture after * it onto the wrong detections, permanently and without a symptom. */ private claimTiming; private receive; private fail; /** Latches the terminal failure and returns it. First writer wins, so the * cause a caller is handed is the one that started the failure rather than * whichever consequence surfaced last. */ private stall; private latch; private discardDecoded; }