Skip to main content

Crate temporal_vision

Crate temporal_vision 

Source
Expand description

Browser-agnostic temporal visual analysis contracts.

§temporal-vision

Deterministic temporal visual analysis: turn a sequence of frames into storyboards, difference maps, motion-history images, and region filmstrips — with a fully self-describing provenance manifest for every artifact.

Pure Rust, synchronous, integer-only pixel math. No async runtime, no I/O, no rendering dependencies — the same input always produces byte-identical output, on any platform, with any thread count.

§What it does

Given a FrameSequence (RGBA8 frames + timestamps, optional markers and declared gaps), temporal-vision produces:

  • Storyboards — 3–12 informative frames selected by change analysis (not uniform sampling), composited into one labeled montage. Each selected frame carries the reasons it was chosen; displaced candidates are named as omitted anchors.
  • Difference maps — two-panel heatmaps: how often each pixel changed (frequency) and when (spectral timing), relative to a reference frame.
  • Motion-history images — one image summarizing where movement happened over a window, decay-weighted by recency, gap-aware (decay resets across declared timeline gaps instead of smearing).
  • Region filmstrips — the same crop across evenly-spaced frames, either fixed or tracked: per-frame moving crops that follow a region you supply (e.g. the projected screen position of an object), with out-of-image areas rendered as honest padding.

Every artifact ships with a manifest distinguishing three frame populations — source (recorded) ⊇ analyzed (decoded) ⊇ selected (rendered) — plus algorithm descriptors, parameters, normalization steps, and a SHA-256 output hash. A generator cannot get its provenance counts wrong; the shapes are checked.

§Built for AI agents

temporal-vision is designed as the visual-evidence layer for LLM-driven debugging tools. It currently powers two MCP (Model Context Protocol) servers:

  • Krometrail — gives agents temporal visual awareness of web pages: storyboards and difference maps of browser sessions for diagnosing flicker, layout shifts, and transient UI defects.
  • Theatre/Stage — gives agents spatial + visual awareness of running Godot games: clip storyboards, motion history, and node-following filmstrips for diagnosing spatial and rendering bugs.

Why it fits agent consumers:

  • Token efficiency is the design constraint. One montage image amortizes a whole window of frames; manifests are compact JSON with exact counts and continuation-friendly structure instead of frame dumps.
  • Deterministic output → content-addressed caching. Identical inputs yield identical bytes, so hosts can cache artifacts by hash and serve repeat queries for free.
  • Honesty is rendered, not asserted. Missing frames become padded tiles, gaps are declared and gap-aware, labels say what the artifact actually shows (e.g. TRACKING <label> | PER-FRAME REGION), and truncation is always explicit. An agent can trust what it reads.
  • Borrowed-slice input. Frame<Id, &[u8]> accepts raw pixel buffers without copying; IDs are caller-owned generics, so hosts key frames to their own timelines.

§Design properties

  • Deterministic parallel merge — custom std::thread::scope parallelism (no Rayon), capped workers, in-order merge; output bytes are identical regardless of worker count.
  • Integer-only pixel math — sRGB→linear via LUT, weighted-channel change classification; no float drift across platforms.
  • Bounded everything — processing, render, and output limits are explicit; exhaustion is a typed error, never an OOM.
  • Plan/render separation — MotionHistoryPlan, RegionFilmstripPlan, StoryboardSelection, DifferenceMapData can be consumed directly and rendered by your own UI (or skip the built-in renderer entirely).
  • Evidence provenance survives persistence — a serialized FrameSequence always names its complete retained source identity, and carries explicit source indices and a declared source range when supplied. Both are null in the implicit full-source shape; explicit indices may also cover the complete source. Deserialization runs the same validation as construction — including the with_provenance complete-input constructor — and rejects duplicate, mismatched, unordered, or out-of-range provenance instead of silently dropping it.

§Example

ⓘ
use temporal_vision::*;

// Build a validated frame sequence (caller-owned ids, borrowed pixels ok).
let seq = FrameSequence::new(frames, markers, gaps, None, None)?;
let normalized = normalize_sequence(&seq, NormalizationParameters::new(
    Rgb8::new(0, 0, 0),
    None,
    IntegerScale::IDENTITY,
    ProcessingLimits::default(),
))?;

// Generate a storyboard: informative frames, one montage, full manifest.
let artifact = generate_storyboard(
    artifact_id,
    None,
    &seq,
    &normalized,
    StoryboardParameters::new(
        seq.range().start(),
        StoryboardTileLimit::default(),
        MeasurementParameters::new(0),
        ArtifactLabels::new("Storyboard", "Captured frames")?,
        RenderLimits::default(),
    ),
)?;
let png_bytes = artifact.storyboard().image().bytes();
let manifest = artifact.storyboard().manifest(); // provenance + selection reasons

§Render a selection from originals

Analyze small copies to choose frames, then load only the selected originals:

ⓘ
let presented = render_storyboard_from_selection(&selection, 2048, |frame_id| {
    load_original(frame_id) // Result<OwnedFrame<FrameId>>
})?;
let png_bytes = presented.image().bytes();
for tile in presented.tiles() {
    let frame_id = tile.frame_id();
    let rect = tile.rect(); // exact half-open image rectangle in montage pixels
    // Map playtest annotations into this rectangle.
}
assert_eq!(presented.selection(), &selection);

render_storyboard_from_selection<F: Clone + Eq> never reselects or normalizes. It keeps frame ids, source indices, timestamps, reasons, omitted anchors, orientation roles, and visual summaries exactly as supplied. The loader runs once per selected id in selection order. Each original is fitted into a small RGB8 copy and released before the next load. Retained fitted pixels total at most the packed canvas size. Conversion happens at the fitted size; the renderer retains no collection of originals.

The montage is an unlabeled row-major grid with at most three columns. Each original is contain-fitted within max_edge / max(columns, rows) using integer nearest-neighbor center sampling, rounded to whole pixels, without enlargement. Columns take their widest fitted tile’s width; rows take their tallest tile’s height. Tiles start at their column and row offsets without centering padding, and both montage dimensions fit within max_edge. Mixed dimensions and aspect ratios are supported; smaller tiles leave only their own gaps within a column or row. Tile rectangles identify every selected frame exactly once. RGBA8 sRGB straight alpha is composited on black in encoded sRGB space. The caller supplies timeline labels and annotations.

max_edge is the dimension ceiling; the default RenderLimits canvas and encoded-output byte caps (64 MiB each) still apply. Growing packed extents are checked before allocating another fitted copy or the final canvas. Empty selections fail with EmptySequence, zero max_edge with InvalidParameter, incompatible loaded ids or pixel formats with IncompatibleFrame, and unfit grids or oversized canvases with ResourceLimitExceeded. Loader errors pass through unchanged. Currently RGBA8 sRGB straight is the only constructible PixelFormat.

To persist the presentation, prepare an ArtifactManifest describing these exact bytes (presented.output_hash()), dimensions, and selection, including the original source and analysis provenance and presentation parameters. Then presented.into_artifact(manifest)? validates their agreement and adds presentation_tiles, containing each tile’s frame_id and rect, to the serialized manifest. Source indices must already agree with the manifest’s complete source identity; when using bounded analysis, its remapped manifest selection is suitable input to this renderer. The image, selection, and tiles have private fields exposed through image(), selection(), and tiles(); tile fields use frame_id() and rect().

§Releases

temporal-vision is versioned and published independently of the krometrail workspace. Releases are cut from tags (temporal-vision-vX.Y.Z) and published to crates.io via GitHub OIDC Trusted Publishing; see docs/RELEASING.md for the bump policy.

§License

MIT

Macros§

stable_registry

Structs§

AlgorithmDescriptor
Named and versioned artifact algorithm.
ArtifactLabels
Required human-readable labels placed on every artifact.
ArtifactManifest
Reproducible machine-readable provenance for one generated artifact.
BinaryMask
A full-frame row-major, MSB-first, one-bit-per-pixel mask.
ChangedPixelProportion
Exact changed and compared pixel counts.
DeclaredGap
A caller-declared interval for which visual continuity is unknown.
DifferenceMapLimits
Working-memory and output bounds for one difference-map request.
DifferenceMapParameters
Deterministic choices for one temporal difference map.
EncodedImage
One deterministic encoded image held entirely in memory.
FilmstripTileLimit
Maximum number of crops shown in one filmstrip.
FilmstripTilePlan
Everything needed to render one chronological fixed-region tile.
FiniteNumber
A finite deterministic floating-point parameter.
Frame
A validated decoded frame using caller-owned identity and pixel storage.
FrameComparison
Direct comparison metadata for two normalized frames.
FrameRegion
A rectangle validated against one source-frame geometry.
FrameSequence
An immutable, validated sequence in one coordinate space and clock.
GeneratedArtifact
Encoded artifact bytes and the provenance that describes those exact bytes.
GeneratorDescriptor
Authoritative name/version descriptor for one generated artifact family.
IntegerScale
A bounded whole-number image scale.
Marker
A caller-defined annotation on the sequence timeline.
MeasurementParameters
Deterministic threshold settings for direct frame comparisons.
MeasurementVector
Thresholded direct visual-change aggregates for one frame pair.
MotionDecay
One deterministic integer exponential-decay curve over pair recency rank.
MotionHistoryParameters
Fixed source-derived choices for one motion-history artifact.
MotionHistoryPlan
Render-independent result of deterministic gap-aware motion accumulation.
NormalizationParameters
Fixed normalization choices for one common-geometry sequence.
NormalizationStep
One ordered normalization operation included in provenance.
NormalizedFrame
One source frame represented as tightly packed opaque linear-light RGB16.
NormalizedSequence
An immutable normalized geometry epoch and its transformed analysis domain.
OmittedAnchor
An available required or boundary anchor displaced by the hard tile budget.
OutputHash
SHA-256 of the exact encoded bytes returned for an artifact.
PaddingInsets
Missing source-image edges retained as explicit padding in unscaled pixels.
PairChangeMasks
Bit-packed changed-pixel masks aligned with adjacent-pair comparison indexes.
Parameters
Artifact parameters with deterministic lexicographic object ordering.
PixelDimensions
Non-zero source-frame pixel dimensions.
PixelRect
A non-empty half-open pixel rectangle in the coordinate space named by its owner.
PresentationTile
One selected original’s image rectangle in the encoded montage, excluding padding.
PresentedStoryboard
Original-image presentation and the unchanged analysis selection behind it.
ProcessingLimits
Explicit bounds for one normalization result.
RationalScale
A positive exact rational scale in source pixels per declared coordinate unit.
RegionFilmstripArtifact
Encoded filmstrip evidence, provenance, and its reusable fixed-region plan.
RegionFilmstripLabels
Required title and source context drawn onto a region filmstrip.
RegionFilmstripParameters
Complete deterministic request for one fixed-region filmstrip.
RegionFilmstripPlan
Reusable, deterministic fixed-region selection and crop plan.
RegionFilmstripRenderLimits
Processing and output ceilings for one region-filmstrip generation request.
RenderLimits
Explicit raster and encoded-output ceilings for one generation request.
Rgb8
An sRGB background used to make straight-alpha input pixels opaque.
SelectedFrame
One selected source frame and every unique reason assigned to it.
SharedAdjacentAnalysis
Canonical adjacent-pair classification shared by artifact consumers.
SignedPixelRect
A non-empty half-open rectangle whose origin may lie outside the source image.
SourceProvenance
Caller-supplied provenance linking decoded frames to their complete retained source, for use with FrameSequence::with_provenance.
StoryboardArtifacts
Storyboard, optional orientation composite, and their shared selection plan.
StoryboardParameters
Complete deterministic storyboard request.
StoryboardSelection
Reusable deterministic source-frame plan shared by storyboard renderers.
StoryboardTileLimit
Hard maximum number of storyboard source panels.
StoryboardVisualSummary
Direct moments already measured while constructing one storyboard selection.
TimeRange
Inclusive range in a caller-declared sequence clock.
Timestamp
Nanoseconds in one caller-declared sequence clock.
TrackedFilmstripParameters
Parameters for a filmstrip whose crop follows a recorded region per frame.
TrackedRegion
A fixed-size crop location for one source frame.
ViewportMapping
Caller-declared mapping from viewport units to source-image pixels.
VisionError
Infrastructure-neutral validation error.
VisualChangeMoment
One authoritative visual-change decision retained from selector measurements.

Enums§

ArtifactKind
Stable visual artifact family.
ComparisonOutcome
Whether a comparison is measurable or crosses declared missing evidence.
ErrorCode
Stable machine-readable classification for contract validation failures.
EvidenceClass
Relationship between an output and source observations.
FrequencyMode
Quantity encoded as brightness in the change-frequency panel.
NormalizationKind
Stable source-derived normalization operation.
ParameterValue
Recursive, tagged parameter value with deterministic object ordering.
PixelFormat
Decoded pixel representation accepted by this crate.
RegionCoordinateSpace
Coordinate space in which a fixed filmstrip region was declared.
RegionDefinition
One fixed region declaration. Neither variant implies logical-element tracking.
SelectionReason
Stable descriptive reason why a source frame appears in a storyboard.
SequenceConsumption
How a generator consumes the sequence it was handed.
TimePalette
Deterministic palette used by the change-timing panel.

Functions§

analyze_adjacent_pairs
Classify every adjacent pair once, optionally retaining changed-pixel masks for reducers.
build_motion_history_plan
Build a bounded motion-history plan without rendering or encoding an image.
build_motion_history_plan_with_analysis
generate_motion_history
Render and encode one deterministic, bounded, source-derived motion-history image.
generate_motion_history_with_analysis
generate_region_filmstrip
Generate one deterministic source-derived fixed-region filmstrip.
generate_storyboard
Generate the primary storyboard and, when requested, its orientation composite.
generate_storyboard_with_analysis
generate_tracked_region_filmstrip
Generate a per-frame moving crop. All tiles share the first union crop for normalization, while their plans retain their own source rectangle/padding.
generator_descriptor
One registry drives both generated manifests and callers’ pre-generation cache keys.
measure_adjacent
Measure every adjacent captured-frame pair in declaration order.
measure_pair
Measure one ordered pair of normalized frames.
normalize_sequence
Normalize one validated source geometry epoch.
plan_region_filmstrip
Resolve one fixed region and select a bounded chronological set of source frames.
render_difference_map
Render one deterministic, source-derived temporal difference map.
render_difference_map_with_analysis
render_storyboard_from_selection
Render selected originals without reselecting or normalizing analysis pixels.
select_indices
Select a deterministic, evenly spaced chronological subset including both endpoints.
select_storyboard_frames
Select representative source frames using the temporal-storyboard 1.1.0 rules.
select_storyboard_frames_with_analysis

Type Aliases§

BorrowedFrame
BorrowedFrameSequence
DifferenceMapArtifact
Difference-map artifact using the crate-wide encoded-image and manifest seam.
MotionHistoryArtifact
Encoded motion-history evidence and its machine-readable provenance.
OwnedFrame
OwnedFrameSequence
Result