import type { FrameCacheStats } from "./frame-cache"; import type { FrameId } from "./frame-timeline"; import type { GopStats } from "./keyframe-index"; import type { FrameQuality, SchedulerStats } from "./scrub-cursor"; import type { PresentationMode } from "./types"; /** Which render backend is painting the display canvas. */ export type RendererName = "2d" | "webgpu"; /** Resolved track facts worth surfacing for diagnostics. decodeWidth/Height * explain cache slot counts: the exact tier is RAM-budgeted, so large frames * mean few slots. */ export interface DiagnosticsTrack { readonly decodeWidth: number; readonly decodeHeight: number; readonly nativeFps: number | null; readonly durationS: number; } /** * Engine-level diagnostics snapshot the worker assembles on demand. Combines the * renderer (controller-owned), track facts, and the scheduler stats (cursor- * owned, null on the uncached cursor). All plain data, so it crosses the worker * boundary by structured clone. * * What `getStats` answers with, one round trip per call and no broadcast timer * required. {@link DiagnosticsSnapshot} opens with these same three fields and * carries the rest of the instrument payload, but only while the diagnostics * broadcast is running. */ export interface EngineDiagnostics { readonly renderer: RendererName | null; readonly track: DiagnosticsTrack | null; readonly scheduler: SchedulerStats | null; } /** Per-paint realtime needles. effectivePaintFps is the painted rate over a * trailing window of broadcast intervals (see PaintRateMeter), null unless * playback was up across the whole window, so every snapshot in a series * carries its own reading. ticks and paints reset at each play start, so they * count the current play session rather than the source's lifetime. * catchUpMs is how far the clock ran past the last painted frame. * playQueueDepth is the decode-ahead buffer's current length: 0 while playing is * the imminent-stall tell. */ export interface RealtimeDiagnostics { readonly effectivePaintFps: number | null; readonly catchUpMs: number; readonly lateFrames: number; readonly stalls: number; readonly ticks: number; readonly paints: number; readonly playQueueDepth: number; /** Decoded frames thrown away before reaching the canvas: ones that arrived * for a position playback had left, buffered ones overtaken by the clock * moving backwards, and the ones the present cadence declines once the rate * asks for more frames a second than it. The first two are decode bandwidth * spent on frames nobody ever saw; the third is the cadence doing its job, * and at a high rate it dominates the count. */ readonly droppedFrames: number; } /** * Lifetime frame ledger across the decode-to-screen pipe: what the decoder * produced, what reached the canvas, what was discarded on the way. These three * are only meaningful read together; the ratio between decoded and painted is * the cost of every frame nobody saw. Monotonic from load, never reset by a * play session. decodedFrames is null when the decode path cannot report it * (the uncached cursor). */ export interface PipelineDiagnostics { readonly decodedFrames: number | null; readonly paintedFrames: number; readonly droppedFrames: number; } /** Last painted frame and its quality; see DiagnosticsSnapshot.screen. */ export interface ScreenDiagnostics { /** Which frame of the source is up, by the engine's own frame table. */ readonly frameId: FrameId; readonly mediaTimeMs: number; readonly quality: FrameQuality; } /** Cache occupancy in bytes, derived from resident slot counts and frame dims. * exactBytesPct is the exact tier's fill against its RAM ceiling; a high value * with a low hit rate is the starved-cache tell. */ export interface CacheBytesDiagnostics { readonly exactBytes: number; readonly previewBytes: number; readonly exactBudgetBytes: number; readonly exactBytesPct: number; } /** Track geometry that explains decode cost. nativeWidth/Height come from the * source track (omitted when the track exposes no native dims). downscaleRatio * is decodeWidth/nativeWidth; decodeVsDisplayAreaRatio compares the decoded * frame area to the bound canvas area (>1 means decoding larger than painted). */ export interface TrackGeometryDiagnostics { readonly nativeWidth: number | null; readonly nativeHeight: number | null; readonly decodeWidth: number; readonly decodeHeight: number; readonly downscaleRatio: number | null; readonly decodeVsDisplayAreaRatio: number | null; readonly boundCanvasWidth: number | null; readonly boundCanvasHeight: number | null; } /** GOP distribution plus the labelled estimates. estimatedGopWalkDepthFrames is * an ESTIMATE: frames a worst-case off-anchor scrub would decode, derived from * avg GOP and native fps, never measured inside the decode loop. */ export interface GopDiagnostics extends GopStats { /** Media seconds from the playhead to the closest anchor the keyframe index * has discovered so far. The index fills lazily, so this reads null until it * holds one and tightens as it walks further. */ readonly distanceToNearestKeyframeS: number | null; readonly estimatedGopWalkDepthFrames: number; } /** Scrub responsiveness aggregates lifted from the scheduler. cacheHitRatePct * reads 0 when nothing has looked the cache up yet, which is indistinguishable * from every lookup missing; cacheLookups() is the denominator that tells the * two apart. */ export interface ScrubDiagnostics { readonly samples: number; readonly avgMs: number; readonly maxMs: number; readonly p50Ms: number; readonly p95Ms: number; readonly targetVsLandedMs: number; readonly timeToCrispMs: number; readonly cacheHitRatePct: number; } /** * Seeks served by re-anchoring the running playback walk, the path a seek * issued while playing takes, with the wall time each waited for its crisp * frame. They never reach the cursor, so nothing in ScrubDiagnostics and no * cache lookup counts them. samples is the denominator of avgMs and maxMs: it * trails seeks whenever one is superseded, or the transport stopped under it, * before its crisp frame arrived. */ export interface PlaySeekDiagnostics { readonly seeks: number; readonly samples: number; readonly avgMs: number; readonly maxMs: number; } /** Decode/seek/prefetch counters lifted from the scheduler. */ export interface CounterDiagnostics { readonly foregroundDecodes: number; readonly prefetchExact: number; readonly prefetchPreview: number; readonly keyframeAnchored: number; readonly exactSeeks: number; readonly keySeeks: number; readonly seekCoalesceDepth: number; readonly probeRoundTrips: number; readonly prefetchInFlight: boolean; /** * Background sweeps cancelled since the source opened, as a running total, so * a rate is only ever the delta between two snapshots. Playback schedules no * sweeps, so a clip that only plays never moves this. */ readonly prefetchGeneration: number; readonly nextPending: number; /** How long the cursor has been draining a seek uninterrupted, in ms; 0 when * none is in flight. Every play pull is refused for the whole of it. */ readonly seekDrainingForMs: number; } /** * The page's JS heap in use. Blink exposes performance.memory on Window only, * never in a worker scope, so the worker cannot read this at all: it leaves the * field null and the main thread fills it on receipt, as it does * webgpuAvailable. Null off Blink, and null in a trace, which is assembled * inside the worker. */ export interface MemoryDiagnostics { readonly jsHeapUsedBytes: number | null; } /** Severity of a diagnosis, ordered info < warn < critical for sorting. */ export type WarningSeverity = "info" | "warn" | "critical"; /** * One self-explaining diagnosis. id is the stable rule key; scenario names what * the runtime is doing wrong in plain language; advice is the fix; evidence is * the human-readable metric values that tripped the rule, so a trace explains * itself to a human or an agent without re-deriving the thresholds. */ export interface Warning { readonly id: string; readonly severity: WarningSeverity; readonly title: string; readonly scenario: string; readonly advice: string; readonly evidence: string; } /** * Source bytes this process holds, for a host that wants to show a viewer how * much of the clip is local. Null unless the engine was loaded with * `sourceResidency`; nothing else in the runtime can answer it, because the * demuxer's own reads and the browser cache are both opaque from here. */ export interface SourceResidencyDiagnostics { readonly ranges: readonly { readonly start: number; readonly end: number; }[]; readonly residentBytes: number; readonly totalBytes: number | null; readonly prefetchedBytes: number; readonly warming: boolean; } /** * The clone-safe wire snapshot the worker broadcasts at BROADCAST_HZ. A superset * of {@link EngineDiagnostics}: renderer, track and scheduler carry the same * values, and it adds the realtime needles, the pipeline ledger, derived cache * bytes, track geometry, GOP block, scrub aggregates, the play-time seek block, * counters, memory, the clock/screen pair, and the worker-evaluated warnings. * Only plain data crosses the boundary. * * webgpuAvailable and memory.jsHeapUsedBytes are the fields the worker leaves at * their empty value for the main thread to fill after the broadcast, so a rule * in evaluateWarnings (which runs in the worker) can never read them, and an * exported trace, assembled worker-side, carries the unfilled value. Warnings * are evaluated once, worker-side, so the HUD and an exported trace always show * the same diagnoses. */ export interface DiagnosticsSnapshot { /** * Which presentation the engine was loaded for. `renderer` and the geometry * fields that need a bound canvas are null for the whole life of a "frames" * engine, which holds none by design; without this a reader cannot tell that * from a "canvas" engine whose renderer has not resolved yet. */ readonly presentation: PresentationMode; readonly renderer: RendererName | null; readonly track: DiagnosticsTrack | null; readonly scheduler: SchedulerStats | null; readonly realtime: RealtimeDiagnostics; readonly pipeline: PipelineDiagnostics; readonly cacheBytes: CacheBytesDiagnostics; readonly geometry: TrackGeometryDiagnostics; readonly gop: GopDiagnostics; readonly scrub: ScrubDiagnostics; readonly playSeek: PlaySeekDiagnostics; readonly counters: CounterDiagnostics; readonly memory: MemoryDiagnostics; readonly sourceResidency: SourceResidencyDiagnostics | null; readonly nativeFps: number | null; /** Media seconds per wall second the transport was told to run at. */ readonly rate: number; /** * The same figure measured off the canvas: media seconds of picture actually * presented per wall second, over a trailing window; null unless playback was * up across the whole of it. Read against `rate` it answers the one question * a commanded rate cannot, which is whether the picture is really moving that * fast. Falling short means frames are arriving slower than the clock wants * them, so the picture lags further behind the playhead every second. * * It is a window over whole paints, so it quantises when paints are sparse: a * slow rate on a low-fps source reads low from a healthy pipeline. Read it * against catchUpMs before concluding anything from a shortfall. */ readonly presentedRate: number | null; /** The engine clock at assembly, ms; null before load. Paused, it holds the * last commanded target; playing, it advances at rate. The one value the * instruments draw the playhead from, so the playhead and the coverage * lanes cannot disagree about where "now" is. */ readonly playheadMs: number | null; /** What is actually on the canvas: last painted position and its quality; * null before the first paint. Its distance from playheadMs is the live * landing error (paused) or catch-up depth (playing). A sampled * observation for instruments; frame identity for consumers still travels * only on the paint event. */ readonly screen: ScreenDiagnostics | null; readonly status: string; readonly webgpuAvailable: boolean; readonly warnings: Warning[]; } /** * Painted-frame rate over a trailing window of broadcast intervals, fed once * per snapshot. A single interval can only hold whole paints, so its rate * quantises hard; the trailing window smooths that without collapsing the * series into a whole-capture average, which could confirm "playback is slow" * but never locate it in time. */ export declare class PaintRateMeter { private readonly windowSize; private readonly samples; constructor(windowSize?: number); /** Rate in paints/second, or null unless playback was up across the whole * window. A pause or a paints reset (each play session restarts the * counter) invalidates the window, not just the sample. */ sample(atMs: number, paints: number, playing: boolean): number | null; } /** * Playback speed measured off what reached the canvas: media seconds presented * per wall second, over the same trailing window PaintRateMeter uses. Fed the * last painted media position once per snapshot. * * It reads painted positions, not paint counts: a source can paint at a healthy * 30fps while the clock runs at 4x, and only the distance the picture travelled * shows that the two disagree. */ export declare class PresentedRateMeter { private readonly windowSize; private readonly samples; constructor(windowSize?: number); /** Rate in media seconds per wall second, or null unless playback was up * across the whole window with the picture moving forward through it. */ sample(atMs: number, paintedMs: number | null, playing: boolean): number | null; /** Drops the window, so a rate change is not measured across its own edge. */ reset(): void; } /** * Cache lookups across every tier. Only an exact seek looks the cache up, so * playback and key seeks never move this and a play-only session sits at zero. * A rule or readout that reads the hit rate without this denominator reports a * cold cache as a failing one. */ export declare function cacheLookups(cache: FrameCacheStats | null | undefined): number; /** * Pure threshold evaluator. Reads a snapshot and returns the active diagnoses, * critical first. Used both in the worker (so the broadcast carries warnings the * UI and the trace share) and in tests. No I/O, no side effects. */ export declare function evaluateWarnings(snapshot: DiagnosticsSnapshot): Warning[];