Skip to main content

temporal_vision/
presentation.rs

1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3
4use crate::{
5    ArtifactKind, ArtifactManifest, EncodedImage, ErrorCode, GeneratedArtifact, OutputHash,
6    OwnedFrame, PixelDimensions, PixelRect, RenderLimits, Result, StoryboardSelection, VisionError,
7    render::canvas::{Canvas, canvas_limit_error, original_fit_dimensions},
8};
9
10/// One selected original's image rectangle in the encoded montage, excluding padding.
11#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct PresentationTile<F> {
14    frame_id: F,
15    rect: PixelRect,
16}
17
18impl<F> PresentationTile<F> {
19    pub fn frame_id(&self) -> &F {
20        &self.frame_id
21    }
22
23    pub const fn rect(&self) -> PixelRect {
24        self.rect
25    }
26}
27
28/// Original-image presentation and the unchanged analysis selection behind it.
29#[derive(Clone, Debug, Eq, PartialEq)]
30pub struct PresentedStoryboard<F> {
31    image: EncodedImage,
32    selection: StoryboardSelection<F>,
33    tiles: Vec<PresentationTile<F>>,
34}
35
36impl<F> PresentedStoryboard<F> {
37    pub const fn image(&self) -> &EncodedImage {
38        &self.image
39    }
40
41    pub const fn selection(&self) -> &StoryboardSelection<F> {
42        &self.selection
43    }
44
45    pub fn tiles(&self) -> &[PresentationTile<F>] {
46        &self.tiles
47    }
48
49    pub fn output_hash(&self) -> OutputHash {
50        OutputHash::from_bytes(Sha256::digest(self.image.bytes()).into())
51    }
52}
53
54impl<F: Clone + Eq> PresentedStoryboard<F> {
55    /// Attach caller-supplied provenance for these exact bytes and selection.
56    ///
57    /// The caller retains responsibility for source/analysis populations and
58    /// transformation parameters. Tile geometry is added and validated here.
59    pub fn into_artifact<A, M: Clone + Eq, G: Clone + Eq>(
60        self,
61        manifest: ArtifactManifest<A, F, M, G>,
62    ) -> Result<GeneratedArtifact<A, F, M, G>> {
63        if manifest.artifact_kind() != ArtifactKind::Storyboard
64            || manifest.output_dimensions() != self.image.dimensions()
65            || manifest.output_hash() != self.output_hash()
66            || manifest.storyboard_selection() != Some(&self.selection)
67        {
68            return Err(VisionError::new(
69                ErrorCode::InvalidManifest,
70                "manifest must describe the presented storyboard bytes and unchanged selection",
71            ));
72        }
73        let manifest = manifest.with_presentation_tiles(self.tiles)?;
74        Ok(GeneratedArtifact::new(self.image, manifest))
75    }
76}
77
78/// Render selected originals without reselecting or normalizing analysis pixels.
79///
80/// Frames are loaded exactly once in selection order, fitted into small RGB8
81/// copies, then dropped before the next load. The grid has up to three columns
82/// in row-major order. Each column takes its widest fitted image's width and
83/// each row its tallest image's height. Images start at their column/row offsets
84/// with no centering padding, preserve aspect ratio (rounded to whole pixels),
85/// and are never enlarged. Retained fitted pixels total at most the canvas size;
86/// the canvas byte cap is checked before allocating fitted copies or the canvas.
87/// Labels and annotations are left to the caller; rectangles name image pixels.
88/// RGBA8 sRGB straight alpha is composited on black in encoded sRGB space.
89///
90/// Both image dimensions fit `max_edge`. The default [`RenderLimits`] canvas
91/// and encoded-byte caps also apply. Loader failures are propagated unchanged.
92pub fn render_storyboard_from_selection<F: Clone + Eq>(
93    selection: &StoryboardSelection<F>,
94    max_edge: u32,
95    mut load: impl FnMut(&F) -> Result<OwnedFrame<F>>,
96) -> Result<PresentedStoryboard<F>> {
97    let count = selection.selected_frames().len();
98    if count == 0 {
99        return Err(VisionError::new(
100            ErrorCode::EmptySequence,
101            "storyboard selection is empty",
102        ));
103    }
104    if max_edge == 0 {
105        return Err(VisionError::new(
106            ErrorCode::InvalidParameter,
107            "max_edge must be non-zero",
108        ));
109    }
110    let columns = count.min(3);
111    let rows = count.div_ceil(columns);
112    let grid_edge = u32::try_from(columns.max(rows)).map_err(|_| canvas_limit_error())?;
113    let tile_edge = max_edge / grid_edge;
114    if tile_edge == 0 {
115        return Err(canvas_limit_error());
116    }
117    let limits = RenderLimits::default();
118    let mut widths = vec![0_u32; columns];
119    let mut heights = vec![0_u32; rows];
120    let mut fitted = Vec::with_capacity(count);
121    for (index, selected) in selection.selected_frames().iter().enumerate() {
122        let original = load(selected.frame_id())?;
123        if original.id() != selected.frame_id() {
124            return Err(VisionError::at(
125                ErrorCode::IncompatibleFrame,
126                "loaded frame id differs from the selected frame id",
127                index,
128            ));
129        }
130        let dimensions = original_fit_dimensions(original.dimensions(), tile_edge)?;
131        widths[index % columns] = widths[index % columns].max(dimensions.width());
132        heights[index / columns] = heights[index / columns].max(dimensions.height());
133        // Extents only grow, so refuse before even allocating the next fitted
134        // copy when the eventual canvas already exceeds the cap.
135        packed_dimensions(&widths, &heights, limits.max_canvas_bytes())?;
136        let mut image = Canvas::new(dimensions, [0, 0, 0], limits.max_canvas_bytes())?;
137        image.draw_original(
138            &original,
139            PixelRect::new(0, 0, dimensions.width(), dimensions.height())?,
140        )?;
141        drop(original);
142        fitted.push(image);
143    }
144    let dimensions = packed_dimensions(&widths, &heights, limits.max_canvas_bytes())?;
145    // max_edge supplies the dimension ceiling; retain the renderer's byte caps.
146    let mut canvas = Canvas::new(dimensions, [0, 0, 0], limits.max_canvas_bytes())?;
147    let mut tiles = Vec::with_capacity(count);
148    for (index, (selected, image)) in selection.selected_frames().iter().zip(fitted).enumerate() {
149        let x = widths[..index % columns].iter().sum();
150        let y = heights[..index / columns].iter().sum();
151        let rect = canvas.copy_from(&image, x, y)?;
152        tiles.push(PresentationTile {
153            frame_id: selected.frame_id().clone(),
154            rect,
155        });
156    }
157    let (bytes, _) =
158        crate::encode::encode_png(dimensions, canvas.pixels(), limits.max_encoded_bytes())?;
159    Ok(PresentedStoryboard {
160        image: EncodedImage::new(dimensions, bytes),
161        selection: selection.clone(),
162        tiles,
163    })
164}
165
166fn packed_dimensions(widths: &[u32], heights: &[u32], max_bytes: usize) -> Result<PixelDimensions> {
167    let sum = |lengths: &[u32]| {
168        lengths.iter().try_fold(0_u32, |total, length| {
169            total.checked_add(*length).ok_or_else(canvas_limit_error)
170        })
171    };
172    let dimensions =
173        PixelDimensions::new(sum(widths)?, sum(heights)?).map_err(|_| canvas_limit_error())?;
174    let bytes = dimensions
175        .pixel_count()?
176        .checked_mul(3)
177        .ok_or_else(canvas_limit_error)?;
178    if bytes > max_bytes {
179        return Err(canvas_limit_error());
180    }
181    Ok(dimensions)
182}