Skip to main content

temporal_vision/
filmstrip.rs

1use std::{
2    collections::BTreeMap,
3    fmt::Display,
4    num::{NonZeroU8, NonZeroU32, NonZeroUsize},
5};
6
7use serde::{Deserialize, Deserializer, Serialize};
8use sha2::{Digest, Sha256};
9
10use crate::{
11    AlgorithmDescriptor, ArtifactKind, ArtifactManifest, BinaryMask, DeclaredGap, EncodedImage,
12    ErrorCode, EvidenceClass, FrameRegion, FrameSequence, GeneratedArtifact, IntegerScale, Marker,
13    NormalizationKind, NormalizationParameters, NormalizationStep, ParameterValue, Parameters,
14    PixelDimensions, PixelRect, ProcessingLimits, Result, Rgb8, Timestamp, VisionError,
15    generator_descriptor,
16    normalize::make_parameters,
17    normalize_sequence,
18    render::{
19        canvas::{
20            BLACK, Canvas, MUTED, PANEL, WARNING, WHITE, canvas_limit_error,
21            canvas_output_limit_error,
22        },
23        font::{CELL_WIDTH, draw_text, ellipsize},
24    },
25};
26
27stable_registry! {
28    /// Coordinate space in which a fixed filmstrip region was declared.
29    pub enum RegionCoordinateSpace {
30        SourceImage => "source_image",
31        Viewport => "viewport",
32    }
33}
34
35/// A non-empty half-open rectangle whose origin may lie outside the source image.
36#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
37pub struct SignedPixelRect {
38    x: i64,
39    y: i64,
40    width: NonZeroU32,
41    height: NonZeroU32,
42}
43
44impl SignedPixelRect {
45    pub fn new(x: i64, y: i64, width: NonZeroU32, height: NonZeroU32) -> Result<Self> {
46        let rect = Self {
47            x,
48            y,
49            width,
50            height,
51        };
52        rect.right_exclusive()?;
53        rect.bottom_exclusive()?;
54        Ok(rect)
55    }
56
57    /// Converts finite fractional bounds to the smallest containing pixel rect.
58    /// Left/top round down and right/bottom round up, including below zero.
59    pub fn from_outward_f64_bounds(left: f64, top: f64, right: f64, bottom: f64) -> Result<Self> {
60        if ![left, top, right, bottom]
61            .iter()
62            .all(|value| value.is_finite())
63            || right <= left
64            || bottom <= top
65        {
66            return Err(VisionError::new(
67                ErrorCode::InvalidRegion,
68                "fractional region bounds must be finite and non-empty",
69            ));
70        }
71        const I64_UPPER_EXCLUSIVE: f64 = 9_223_372_036_854_775_808.0;
72        let convert = |value: f64, round: fn(f64) -> f64| {
73            let value = round(value);
74            if value < i64::MIN as f64 || value >= I64_UPPER_EXCLUSIVE {
75                Err(VisionError::new(
76                    ErrorCode::InvalidRegion,
77                    "fractional region exceeds the supported coordinate space",
78                ))
79            } else {
80                Ok(value as i64)
81            }
82        };
83        let left = convert(left, f64::floor)?;
84        let top = convert(top, f64::floor)?;
85        let right = convert(right, f64::ceil)?;
86        let bottom = convert(bottom, f64::ceil)?;
87        let width = u32::try_from(i128::from(right) - i128::from(left))
88            .ok()
89            .and_then(NonZeroU32::new)
90            .ok_or_else(|| {
91                VisionError::new(
92                    ErrorCode::InvalidRegion,
93                    "fractional region width exceeds the supported coordinate space",
94                )
95            })?;
96        let height = u32::try_from(i128::from(bottom) - i128::from(top))
97            .ok()
98            .and_then(NonZeroU32::new)
99            .ok_or_else(|| {
100                VisionError::new(
101                    ErrorCode::InvalidRegion,
102                    "fractional region height exceeds the supported coordinate space",
103                )
104            })?;
105        Self::new(left, top, width, height)
106    }
107
108    pub const fn x(self) -> i64 {
109        self.x
110    }
111
112    pub const fn y(self) -> i64 {
113        self.y
114    }
115
116    pub const fn width(self) -> u32 {
117        self.width.get()
118    }
119
120    pub const fn height(self) -> u32 {
121        self.height.get()
122    }
123
124    pub fn right_exclusive(self) -> Result<i64> {
125        self.x
126            .checked_add(i64::from(self.width.get()))
127            .ok_or_else(|| {
128                VisionError::new(
129                    ErrorCode::InvalidRegion,
130                    "signed region exceeds the coordinate space",
131                )
132            })
133    }
134
135    pub fn bottom_exclusive(self) -> Result<i64> {
136        self.y
137            .checked_add(i64::from(self.height.get()))
138            .ok_or_else(|| {
139                VisionError::new(
140                    ErrorCode::InvalidRegion,
141                    "signed region exceeds the coordinate space",
142                )
143            })
144    }
145}
146
147impl<'de> Deserialize<'de> for SignedPixelRect {
148    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
149    where
150        D: Deserializer<'de>,
151    {
152        #[derive(Deserialize)]
153        #[serde(deny_unknown_fields)]
154        struct Wire {
155            x: i64,
156            y: i64,
157            width: NonZeroU32,
158            height: NonZeroU32,
159        }
160        let wire = Wire::deserialize(deserializer)?;
161        Self::new(wire.x, wire.y, wire.width, wire.height).map_err(serde::de::Error::custom)
162    }
163}
164
165/// A positive exact rational scale in source pixels per declared coordinate unit.
166#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
167pub struct RationalScale {
168    numerator: NonZeroU32,
169    denominator: NonZeroU32,
170}
171
172impl RationalScale {
173    pub const fn new(numerator: NonZeroU32, denominator: NonZeroU32) -> Self {
174        Self {
175            numerator,
176            denominator,
177        }
178    }
179
180    pub const fn numerator(self) -> u32 {
181        self.numerator.get()
182    }
183
184    pub const fn denominator(self) -> u32 {
185        self.denominator.get()
186    }
187}
188
189/// Caller-declared mapping from viewport units to source-image pixels.
190#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
191pub struct ViewportMapping {
192    viewport_dimensions: PixelDimensions,
193    scale_x: RationalScale,
194    scale_y: RationalScale,
195}
196
197impl ViewportMapping {
198    pub const fn new(
199        viewport_dimensions: PixelDimensions,
200        scale_x: RationalScale,
201        scale_y: RationalScale,
202    ) -> Self {
203        Self {
204            viewport_dimensions,
205            scale_x,
206            scale_y,
207        }
208    }
209
210    /// Builds the canonical exact viewport-to-source rational mapping.
211    pub fn for_source(
212        viewport_dimensions: PixelDimensions,
213        source_dimensions: PixelDimensions,
214    ) -> Self {
215        fn reduced(numerator: u32, denominator: u32) -> RationalScale {
216            fn gcd(mut left: u32, mut right: u32) -> u32 {
217                while right != 0 {
218                    let remainder = left % right;
219                    left = right;
220                    right = remainder;
221                }
222                left
223            }
224            let divisor = gcd(numerator, denominator);
225            RationalScale::new(
226                NonZeroU32::new(numerator / divisor).expect("source dimension is non-zero"),
227                NonZeroU32::new(denominator / divisor).expect("viewport dimension is non-zero"),
228            )
229        }
230        Self::new(
231            viewport_dimensions,
232            reduced(source_dimensions.width(), viewport_dimensions.width()),
233            reduced(source_dimensions.height(), viewport_dimensions.height()),
234        )
235    }
236
237    pub const fn viewport_dimensions(self) -> PixelDimensions {
238        self.viewport_dimensions
239    }
240
241    pub const fn scale_x(self) -> RationalScale {
242        self.scale_x
243    }
244
245    pub const fn scale_y(self) -> RationalScale {
246        self.scale_y
247    }
248}
249
250/// One fixed region declaration. Neither variant implies logical-element tracking.
251#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
252#[serde(tag = "coordinate_space", rename_all = "snake_case")]
253pub enum RegionDefinition {
254    FixedSourceImage {
255        rect: SignedPixelRect,
256    },
257    FixedViewport {
258        rect: SignedPixelRect,
259        mapping: ViewportMapping,
260    },
261}
262
263impl RegionDefinition {
264    pub const fn coordinate_space(self) -> RegionCoordinateSpace {
265        match self {
266            Self::FixedSourceImage { .. } => RegionCoordinateSpace::SourceImage,
267            Self::FixedViewport { .. } => RegionCoordinateSpace::Viewport,
268        }
269    }
270
271    pub const fn rect(self) -> SignedPixelRect {
272        match self {
273            Self::FixedSourceImage { rect } | Self::FixedViewport { rect, .. } => rect,
274        }
275    }
276}
277
278/// Missing source-image edges retained as explicit padding in unscaled pixels.
279#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
280pub struct PaddingInsets {
281    left: u32,
282    top: u32,
283    right: u32,
284    bottom: u32,
285}
286
287impl PaddingInsets {
288    pub const fn left(self) -> u32 {
289        self.left
290    }
291
292    pub const fn top(self) -> u32 {
293        self.top
294    }
295
296    pub const fn right(self) -> u32 {
297        self.right
298    }
299
300    pub const fn bottom(self) -> u32 {
301        self.bottom
302    }
303
304    pub const fn is_empty(self) -> bool {
305        self.left == 0 && self.top == 0 && self.right == 0 && self.bottom == 0
306    }
307}
308
309/// Everything needed to render one chronological fixed-region tile.
310#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
311pub struct FilmstripTilePlan<FrameId> {
312    frame_id: FrameId,
313    frame_index: usize,
314    timestamp: Timestamp,
315    anchor_offset_nanos: i128,
316    source_rect: Option<PixelRect>,
317    padding: PaddingInsets,
318    gap_after: bool,
319}
320
321impl<F> FilmstripTilePlan<F> {
322    pub fn frame_id(&self) -> &F {
323        &self.frame_id
324    }
325
326    pub const fn frame_index(&self) -> usize {
327        self.frame_index
328    }
329
330    pub const fn timestamp(&self) -> Timestamp {
331        self.timestamp
332    }
333
334    pub const fn anchor_offset_nanos(&self) -> i128 {
335        self.anchor_offset_nanos
336    }
337
338    pub const fn source_rect(&self) -> Option<PixelRect> {
339        self.source_rect
340    }
341
342    pub const fn padding(&self) -> PaddingInsets {
343        self.padding
344    }
345
346    pub const fn gap_after(&self) -> bool {
347        self.gap_after
348    }
349}
350
351/// Reusable, deterministic fixed-region selection and crop plan.
352#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
353pub struct RegionFilmstripPlan<FrameId> {
354    tiles: Box<[FilmstripTilePlan<FrameId>]>,
355    locator_frame_index: usize,
356    coordinate_space: RegionCoordinateSpace,
357    declared_region: SignedPixelRect,
358    resolved_source_region: SignedPixelRect,
359    tile_source_dimensions: PixelDimensions,
360    omitted_frame_count: u64,
361}
362
363impl<F> RegionFilmstripPlan<F> {
364    pub fn tiles(&self) -> &[FilmstripTilePlan<F>] {
365        &self.tiles
366    }
367
368    pub const fn locator_frame_index(&self) -> usize {
369        self.locator_frame_index
370    }
371
372    pub const fn coordinate_space(&self) -> RegionCoordinateSpace {
373        self.coordinate_space
374    }
375
376    pub const fn declared_region(&self) -> SignedPixelRect {
377        self.declared_region
378    }
379
380    pub const fn resolved_source_region(&self) -> SignedPixelRect {
381        self.resolved_source_region
382    }
383
384    pub const fn tile_source_dimensions(&self) -> PixelDimensions {
385        self.tile_source_dimensions
386    }
387
388    pub const fn omitted_frame_count(&self) -> u64 {
389        self.omitted_frame_count
390    }
391}
392
393/// Maximum number of crops shown in one filmstrip.
394#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
395#[serde(transparent)]
396pub struct FilmstripTileLimit(NonZeroU8);
397
398impl FilmstripTileLimit {
399    pub const DEFAULT: Self = Self(NonZeroU8::new(12).expect("default is nonzero"));
400
401    pub fn new(value: u8) -> Result<Self> {
402        let value = NonZeroU8::new(value).ok_or_else(|| {
403            VisionError::new(
404                ErrorCode::InvalidParameter,
405                "filmstrip tile limit must be between one and twenty-four",
406            )
407        })?;
408        if value.get() > 24 {
409            return Err(VisionError::new(
410                ErrorCode::InvalidParameter,
411                "filmstrip tile limit must be between one and twenty-four",
412            ));
413        }
414        Ok(Self(value))
415    }
416
417    pub const fn get(self) -> u8 {
418        self.0.get()
419    }
420}
421
422impl Default for FilmstripTileLimit {
423    fn default() -> Self {
424        Self::DEFAULT
425    }
426}
427
428impl<'de> Deserialize<'de> for FilmstripTileLimit {
429    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
430    where
431        D: Deserializer<'de>,
432    {
433        Self::new(u8::deserialize(deserializer)?).map_err(serde::de::Error::custom)
434    }
435}
436
437/// Resolve one fixed region and select a bounded chronological set of source frames.
438pub fn plan_region_filmstrip<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
439    source: &FrameSequence<F, M, G, P>,
440    region: RegionDefinition,
441    anchor: Timestamp,
442    tile_limit: FilmstripTileLimit,
443    locator_frame_index: Option<usize>,
444) -> Result<RegionFilmstripPlan<F>> {
445    if !source.range().contains(anchor) {
446        return Err(VisionError::new(
447            ErrorCode::InvalidParameter,
448            "filmstrip anchor lies outside the source range",
449        ));
450    }
451    if locator_frame_index.is_some_and(|index| index >= source.frames().len()) {
452        return Err(VisionError::new(
453            ErrorCode::InvalidParameter,
454            "filmstrip locator frame index is outside the source sequence",
455        ));
456    }
457
458    let resolved = resolve_region(region, source.dimensions())?;
459    let tile_source_dimensions = PixelDimensions::new(resolved.width(), resolved.height())
460        .map_err(|_| {
461            VisionError::new(
462                ErrorCode::ResourceLimitExceeded,
463                "resolved filmstrip region exceeds supported dimensions",
464            )
465        })?;
466    let selected_indices = select_indices(source.frames().len(), usize::from(tile_limit.get()));
467    let locator_frame_index = locator_frame_index.unwrap_or_else(|| {
468        selected_indices
469            .iter()
470            .copied()
471            .find(|index| source.frames()[*index].timestamp() >= anchor)
472            .unwrap_or(selected_indices[0])
473    });
474
475    let mut tiles = selected_indices
476        .iter()
477        .map(|index| {
478            let frame = &source.frames()[*index];
479            let (source_rect, padding) = intersect_region(resolved, source.dimensions())?;
480            Ok(FilmstripTilePlan {
481                frame_id: frame.id().clone(),
482                frame_index: *index,
483                timestamp: frame.timestamp(),
484                anchor_offset_nanos: i128::from(frame.timestamp().as_nanos())
485                    - i128::from(anchor.as_nanos()),
486                source_rect,
487                padding,
488                gap_after: false,
489            })
490        })
491        .collect::<Result<Vec<_>>>()?;
492    for tile in 0..tiles.len().saturating_sub(1) {
493        tiles[tile].gap_after = source.gaps().iter().any(|gap| {
494            gap.range().start() <= tiles[tile + 1].timestamp
495                && gap.range().end() >= tiles[tile].timestamp
496        });
497    }
498
499    let omitted_frame_count =
500        u64::try_from(source.source_frame_count() - tiles.len()).map_err(|_| {
501            VisionError::new(
502                ErrorCode::ResourceLimitExceeded,
503                "filmstrip frame count exceeds the manifest representation",
504            )
505        })?;
506    Ok(RegionFilmstripPlan {
507        tiles: tiles.into_boxed_slice(),
508        locator_frame_index,
509        coordinate_space: region.coordinate_space(),
510        declared_region: region.rect(),
511        resolved_source_region: resolved,
512        tile_source_dimensions,
513        omitted_frame_count,
514    })
515}
516
517fn resolve_region(region: RegionDefinition, source: PixelDimensions) -> Result<SignedPixelRect> {
518    match region {
519        RegionDefinition::FixedSourceImage { rect } => Ok(rect),
520        RegionDefinition::FixedViewport { rect, mapping } => {
521            validate_viewport_mapping(mapping, source)?;
522            let left = scale_floor(rect.x(), mapping.scale_x())?;
523            let top = scale_floor(rect.y(), mapping.scale_y())?;
524            let right = scale_ceil(rect.right_exclusive()?, mapping.scale_x())?;
525            let bottom = scale_ceil(rect.bottom_exclusive()?, mapping.scale_y())?;
526            let width = u32::try_from(right.checked_sub(left).ok_or_else(invalid_scale_error)?)
527                .ok()
528                .and_then(NonZeroU32::new)
529                .ok_or_else(invalid_scale_error)?;
530            let height = u32::try_from(bottom.checked_sub(top).ok_or_else(invalid_scale_error)?)
531                .ok()
532                .and_then(NonZeroU32::new)
533                .ok_or_else(invalid_scale_error)?;
534            SignedPixelRect::new(left, top, width, height)
535        }
536    }
537}
538
539fn validate_viewport_mapping(mapping: ViewportMapping, source: PixelDimensions) -> Result<()> {
540    let mapped_width = scale_ceil(
541        i64::from(mapping.viewport_dimensions().width()),
542        mapping.scale_x(),
543    )?;
544    let mapped_height = scale_ceil(
545        i64::from(mapping.viewport_dimensions().height()),
546        mapping.scale_y(),
547    )?;
548    if mapped_width != i64::from(source.width()) || mapped_height != i64::from(source.height()) {
549        return Err(VisionError::new(
550            ErrorCode::InvalidScale,
551            "viewport mapping dimensions contradict the source-frame dimensions",
552        ));
553    }
554    Ok(())
555}
556
557fn scale_floor(value: i64, scale: RationalScale) -> Result<i64> {
558    let numerator = i128::from(value)
559        .checked_mul(i128::from(scale.numerator()))
560        .ok_or_else(invalid_scale_error)?;
561    let result = numerator.div_euclid(i128::from(scale.denominator()));
562    i64::try_from(result).map_err(|_| invalid_scale_error())
563}
564
565fn scale_ceil(value: i64, scale: RationalScale) -> Result<i64> {
566    let numerator = i128::from(value)
567        .checked_mul(i128::from(scale.numerator()))
568        .ok_or_else(invalid_scale_error)?;
569    let denominator = i128::from(scale.denominator());
570    let result = -(-numerator).div_euclid(denominator);
571    i64::try_from(result).map_err(|_| invalid_scale_error())
572}
573
574fn invalid_scale_error() -> VisionError {
575    VisionError::new(
576        ErrorCode::InvalidScale,
577        "viewport scale conversion exceeds the supported coordinate space",
578    )
579}
580
581/// Select a deterministic, evenly spaced chronological subset including both endpoints.
582pub fn select_indices(frame_count: usize, limit: usize) -> Vec<usize> {
583    if frame_count <= limit {
584        return (0..frame_count).collect();
585    }
586    if limit == 1 {
587        return vec![0];
588    }
589    let span = frame_count - 1;
590    let denominator = limit - 1;
591    (0..limit)
592        .map(|slot| {
593            let numerator = (slot as u128) * (span as u128);
594            round_ratio_ties_down(numerator, denominator as u128) as usize
595        })
596        .collect()
597}
598
599fn round_ratio_ties_down(numerator: u128, denominator: u128) -> u128 {
600    let quotient = numerator / denominator;
601    let remainder = numerator % denominator;
602    quotient + u128::from(remainder > denominator - remainder)
603}
604
605fn intersect_region(
606    region: SignedPixelRect,
607    dimensions: PixelDimensions,
608) -> Result<(Option<PixelRect>, PaddingInsets)> {
609    let right = region.right_exclusive()?;
610    let bottom = region.bottom_exclusive()?;
611    let source_right = i64::from(dimensions.width());
612    let source_bottom = i64::from(dimensions.height());
613    let left = region.x().clamp(0, source_right);
614    let top = region.y().clamp(0, source_bottom);
615    let clipped_right = right.clamp(0, source_right);
616    let clipped_bottom = bottom.clamp(0, source_bottom);
617    let visible_width = u32::try_from(clipped_right.saturating_sub(left)).map_err(|_| {
618        VisionError::new(
619            ErrorCode::InvalidRegion,
620            "filmstrip intersection exceeds limits",
621        )
622    })?;
623    let visible_height = u32::try_from(clipped_bottom.saturating_sub(top)).map_err(|_| {
624        VisionError::new(
625            ErrorCode::InvalidRegion,
626            "filmstrip intersection exceeds limits",
627        )
628    })?;
629    let padding = PaddingInsets {
630        left: u32::try_from((left - region.x()).clamp(0, i64::from(region.width())))
631            .map_err(|_| invalid_region_error())?,
632        top: u32::try_from((top - region.y()).clamp(0, i64::from(region.height())))
633            .map_err(|_| invalid_region_error())?,
634        right: region
635            .width()
636            .checked_sub(
637                u32::try_from((clipped_right - region.x()).clamp(0, i64::from(region.width())))
638                    .map_err(|_| invalid_region_error())?,
639            )
640            .ok_or_else(invalid_region_error)?,
641        bottom: region
642            .height()
643            .checked_sub(
644                u32::try_from((clipped_bottom - region.y()).clamp(0, i64::from(region.height())))
645                    .map_err(|_| invalid_region_error())?,
646            )
647            .ok_or_else(invalid_region_error)?,
648    };
649    let source_rect = if visible_width == 0 || visible_height == 0 {
650        None
651    } else {
652        Some(PixelRect::new(
653            u32::try_from(left).map_err(|_| invalid_region_error())?,
654            u32::try_from(top).map_err(|_| invalid_region_error())?,
655            visible_width,
656            visible_height,
657        )?)
658    };
659    Ok((source_rect, padding))
660}
661
662fn invalid_region_error() -> VisionError {
663    VisionError::new(
664        ErrorCode::InvalidRegion,
665        "filmstrip region intersection exceeds supported limits",
666    )
667}
668
669const DEFAULT_MAX_DIMENSION: u32 = 4_096;
670const DEFAULT_MAX_BYTES: usize = 64 * 1024 * 1024;
671const DEFAULT_MAX_SOURCE_FRAMES: usize = 4_096;
672const MARGIN: u32 = 12;
673const HEADER_HEIGHT: u32 = 64;
674const LOCATOR_WIDTH: u32 = 200;
675const LOCATOR_HEIGHT: u32 = 200;
676const LOCATOR_ANNOTATION_HEIGHT: u32 = 44;
677const TILE_ANNOTATION_HEIGHT: u32 = 56;
678const MINIMUM_TILE_SLOT_WIDTH: u32 = 160;
679const SECTION_GAP: u32 = 16;
680const TILE_GAP: u32 = 12;
681const TIMELINE_HEIGHT: u32 = 24;
682
683/// Required title and source context drawn onto a region filmstrip.
684#[derive(Clone, Debug, Eq, PartialEq)]
685pub struct RegionFilmstripLabels {
686    title: String,
687    source: String,
688}
689
690impl RegionFilmstripLabels {
691    pub fn new(title: impl Into<String>, source: impl Into<String>) -> Result<Self> {
692        let title = title.into();
693        let source = source.into();
694        if title.trim().is_empty() || source.trim().is_empty() {
695            return Err(VisionError::new(
696                ErrorCode::InvalidParameter,
697                "filmstrip title and source context must not be empty",
698            ));
699        }
700        Ok(Self { title, source })
701    }
702
703    pub fn title(&self) -> &str {
704        &self.title
705    }
706
707    pub fn source(&self) -> &str {
708        &self.source
709    }
710}
711
712/// Processing and output ceilings for one region-filmstrip generation request.
713#[derive(Clone, Copy, Debug, Eq, PartialEq)]
714pub struct RegionFilmstripRenderLimits {
715    max_width: NonZeroU32,
716    max_height: NonZeroU32,
717    max_canvas_bytes: NonZeroUsize,
718    max_encoded_bytes: NonZeroUsize,
719    max_source_frames: NonZeroUsize,
720}
721
722impl RegionFilmstripRenderLimits {
723    pub const fn new(
724        max_width: NonZeroU32,
725        max_height: NonZeroU32,
726        max_canvas_bytes: NonZeroUsize,
727        max_encoded_bytes: NonZeroUsize,
728    ) -> Self {
729        Self {
730            max_width,
731            max_height,
732            max_canvas_bytes,
733            max_encoded_bytes,
734            max_source_frames: NonZeroUsize::new(DEFAULT_MAX_SOURCE_FRAMES)
735                .expect("default is nonzero"),
736        }
737    }
738
739    pub const fn with_max_source_frames(mut self, max_source_frames: NonZeroUsize) -> Self {
740        self.max_source_frames = max_source_frames;
741        self
742    }
743
744    pub const fn max_width(self) -> u32 {
745        self.max_width.get()
746    }
747
748    pub const fn max_height(self) -> u32 {
749        self.max_height.get()
750    }
751
752    pub const fn max_canvas_bytes(self) -> usize {
753        self.max_canvas_bytes.get()
754    }
755
756    pub const fn max_encoded_bytes(self) -> usize {
757        self.max_encoded_bytes.get()
758    }
759
760    pub const fn max_source_frames(self) -> usize {
761        self.max_source_frames.get()
762    }
763
764    fn processing_limits(self) -> ProcessingLimits {
765        let max_pixels = (self.max_canvas_bytes() / 6).max(1);
766        ProcessingLimits::new(
767            self.max_source_frames,
768            NonZeroUsize::new(max_pixels).expect("maximum pixels is nonzero"),
769            self.max_canvas_bytes,
770        )
771    }
772}
773
774impl Default for RegionFilmstripRenderLimits {
775    fn default() -> Self {
776        Self::new(
777            NonZeroU32::new(DEFAULT_MAX_DIMENSION).expect("default is nonzero"),
778            NonZeroU32::new(DEFAULT_MAX_DIMENSION).expect("default is nonzero"),
779            NonZeroUsize::new(DEFAULT_MAX_BYTES).expect("default is nonzero"),
780            NonZeroUsize::new(DEFAULT_MAX_BYTES).expect("default is nonzero"),
781        )
782    }
783}
784
785/// Complete deterministic request for one fixed-region filmstrip.
786#[derive(Clone, Debug, Eq, PartialEq)]
787pub struct RegionFilmstripParameters {
788    region: RegionDefinition,
789    tracking_label: Option<String>,
790    mask: Option<BinaryMask>,
791    anchor: Timestamp,
792    tile_limit: FilmstripTileLimit,
793    locator_frame_index: Option<usize>,
794    background: Rgb8,
795    padding_color: Rgb8,
796    display_scale: IntegerScale,
797    labels: RegionFilmstripLabels,
798    limits: RegionFilmstripRenderLimits,
799}
800
801impl RegionFilmstripParameters {
802    #[allow(clippy::too_many_arguments)]
803    pub fn new(
804        region: RegionDefinition,
805        anchor: Timestamp,
806        tile_limit: FilmstripTileLimit,
807        background: Rgb8,
808        padding_color: Rgb8,
809        display_scale: IntegerScale,
810        labels: RegionFilmstripLabels,
811        limits: RegionFilmstripRenderLimits,
812    ) -> Self {
813        Self {
814            region,
815            tracking_label: None,
816            mask: None,
817            anchor,
818            tile_limit,
819            locator_frame_index: None,
820            background,
821            padding_color,
822            display_scale,
823            labels,
824            limits,
825        }
826    }
827
828    pub const fn with_locator_frame_index(mut self, index: usize) -> Self {
829        self.locator_frame_index = Some(index);
830        self
831    }
832
833    /// Applies one immutable full-frame mask at identical source coordinates.
834    pub fn with_mask(mut self, mask: BinaryMask) -> Result<Self> {
835        if mask.bounds()?.is_none() {
836            return Err(VisionError::new(
837                ErrorCode::InvalidMask,
838                "filmstrip mask must select at least one source pixel",
839            ));
840        }
841        self.mask = Some(mask);
842        Ok(self)
843    }
844
845    pub fn with_tracking_label(mut self, label: impl Into<String>) -> Self {
846        self.tracking_label = Some(label.into());
847        self
848    }
849
850    pub const fn region(&self) -> RegionDefinition {
851        self.region
852    }
853
854    pub const fn mask(&self) -> Option<&BinaryMask> {
855        self.mask.as_ref()
856    }
857
858    pub const fn anchor(&self) -> Timestamp {
859        self.anchor
860    }
861
862    pub const fn tile_limit(&self) -> FilmstripTileLimit {
863        self.tile_limit
864    }
865
866    pub const fn locator_frame_index(&self) -> Option<usize> {
867        self.locator_frame_index
868    }
869
870    pub const fn background(&self) -> Rgb8 {
871        self.background
872    }
873
874    pub const fn padding_color(&self) -> Rgb8 {
875        self.padding_color
876    }
877
878    pub const fn display_scale(&self) -> IntegerScale {
879        self.display_scale
880    }
881
882    pub const fn labels(&self) -> &RegionFilmstripLabels {
883        &self.labels
884    }
885
886    pub const fn limits(&self) -> RegionFilmstripRenderLimits {
887        self.limits
888    }
889}
890
891/// Encoded filmstrip evidence, provenance, and its reusable fixed-region plan.
892#[derive(Clone, Debug, PartialEq)]
893pub struct RegionFilmstripArtifact<A, F, M, G> {
894    artifact: GeneratedArtifact<A, F, M, G>,
895    plan: RegionFilmstripPlan<F>,
896}
897
898impl<A, F, M, G> RegionFilmstripArtifact<A, F, M, G> {
899    pub const fn image(&self) -> &EncodedImage {
900        self.artifact.image()
901    }
902
903    pub const fn manifest(&self) -> &ArtifactManifest<A, F, M, G> {
904        self.artifact.manifest()
905    }
906
907    pub const fn plan(&self) -> &RegionFilmstripPlan<F> {
908        &self.plan
909    }
910}
911
912/// Generate one deterministic source-derived fixed-region filmstrip.
913pub fn generate_region_filmstrip<A, F, M, G, P>(
914    artifact_id: A,
915    source: &FrameSequence<F, M, G, P>,
916    parameters: RegionFilmstripParameters,
917) -> Result<RegionFilmstripArtifact<A, F, M, G>>
918where
919    F: Clone + Eq + Display,
920    M: Clone + Eq,
921    G: Clone + Eq,
922    P: AsRef<[u8]>,
923{
924    if source.frames().len() > parameters.limits.max_source_frames() {
925        return Err(render_limit_error());
926    }
927    let effective_region = if let Some(mask) = parameters.mask.as_ref() {
928        if mask.dimensions() != source.dimensions() {
929            return Err(VisionError::new(
930                ErrorCode::InvalidMask,
931                "filmstrip mask dimensions must match every source frame",
932            ));
933        }
934        let bounds = mask.bounds()?.ok_or_else(|| {
935            VisionError::new(
936                ErrorCode::InvalidMask,
937                "filmstrip mask must select at least one source pixel",
938            )
939        })?;
940        RegionDefinition::FixedSourceImage {
941            rect: SignedPixelRect::new(
942                i64::from(bounds.x()),
943                i64::from(bounds.y()),
944                NonZeroU32::new(bounds.width()).expect("mask bounds are non-empty"),
945                NonZeroU32::new(bounds.height()).expect("mask bounds are non-empty"),
946            )?,
947        }
948    } else {
949        parameters.region
950    };
951    let plan = plan_region_filmstrip(
952        source,
953        effective_region,
954        parameters.anchor,
955        parameters.tile_limit,
956        parameters.locator_frame_index,
957    )?;
958    let tile_dimensions =
959        scaled_tile_dimensions(plan.tile_source_dimensions(), parameters.display_scale)?;
960    let (crop, _) = intersect_region(effective_region.rect(), source.dimensions())?;
961    // A fully outside region is rendered entirely as padding. Keep normalization bounded to a
962    // single source pixel because draw_tile never reads normalized data for that tile.
963    let crop = crop.unwrap_or(PixelRect::new(0, 0, 1, 1)?);
964    let tile_source = FrameSequence::new(
965        plan.tiles()
966            .iter()
967            .map(|tile| source.frames()[tile.frame_index()].to_owned())
968            .collect(),
969        Vec::<Marker<M>>::new(),
970        Vec::<DeclaredGap<G>>::new(),
971        source.region(),
972        source.mask().cloned(),
973    )?;
974    let normalized = normalize_sequence(
975        &tile_source,
976        NormalizationParameters::new(
977            parameters.background,
978            Some(crop),
979            IntegerScale::IDENTITY,
980            parameters.limits.processing_limits(),
981        ),
982    )?;
983    let locator_source = FrameSequence::new(
984        vec![source.frames()[plan.locator_frame_index()].to_owned()],
985        Vec::<Marker<M>>::new(),
986        Vec::<DeclaredGap<G>>::new(),
987        None,
988        None,
989    )?;
990    let locator_normalized = normalize_sequence(
991        &locator_source,
992        NormalizationParameters::new(
993            parameters.background,
994            None,
995            IntegerScale::IDENTITY,
996            parameters.limits.processing_limits(),
997        ),
998    )?;
999    let layout = FilmstripLayout::new(tile_dimensions, plan.tiles().len(), parameters.limits)?;
1000    let mut canvas = Canvas::new(
1001        layout.dimensions,
1002        BLACK,
1003        parameters.limits.max_canvas_bytes(),
1004    )?;
1005    render_filmstrip(
1006        &mut canvas,
1007        layout,
1008        source,
1009        &normalized,
1010        &locator_normalized,
1011        &plan,
1012        &parameters,
1013    )?;
1014    let (bytes, hash) = crate::encode::encode_png(
1015        layout.dimensions,
1016        canvas.pixels(),
1017        parameters.limits.max_encoded_bytes(),
1018    )?;
1019
1020    let mut normalization = normalized.normalization_steps().to_vec();
1021    normalization.push(display_conversion_step()?);
1022    normalization.push(region_padding_step(&plan, parameters.padding_color)?);
1023    if let Some(mask) = parameters.mask.as_ref() {
1024        normalization.push(mask_application_step(mask, &plan)?);
1025    }
1026    if !parameters.display_scale.is_identity() {
1027        normalization.push(display_scale_step(
1028            parameters.display_scale,
1029            tile_dimensions,
1030        )?);
1031    }
1032    let mut artifact_source_indices = plan
1033        .tiles()
1034        .iter()
1035        .map(FilmstripTilePlan::frame_index)
1036        .collect::<Vec<_>>();
1037    if !artifact_source_indices.contains(&plan.locator_frame_index()) {
1038        artifact_source_indices.push(plan.locator_frame_index());
1039        artifact_source_indices.sort_unstable();
1040    }
1041    let selected_ids = artifact_source_indices
1042        .iter()
1043        .map(|index| source.frames()[*index].id().clone())
1044        .collect();
1045    let manifest_region = manifest_region(effective_region, source.dimensions())?;
1046    let manifest = ArtifactManifest::from_sequence_with_domain(
1047        artifact_id,
1048        ArtifactKind::RegionFilmstrip,
1049        EvidenceClass::SourceDerived,
1050        {
1051            let descriptor = generator_descriptor(ArtifactKind::RegionFilmstrip);
1052            AlgorithmDescriptor::new(descriptor.name, descriptor.version)?
1053        },
1054        source,
1055        manifest_region,
1056        parameters.mask.clone(),
1057        selected_ids,
1058        // A filmstrip looks at the frames it renders. Frames between tiles are
1059        // decoded by the plan and then never examined, so counting them as
1060        // analyzed would overstate what this artifact is evidence of.
1061        crate::provenance::SequenceConsumption::SelectedFramesOnly,
1062        normalization,
1063        filmstrip_parameters(
1064            &plan,
1065            &artifact_source_indices,
1066            source.source_frame_count(),
1067            &parameters,
1068            layout,
1069            tile_dimensions,
1070        )?,
1071        layout.dimensions,
1072        hash,
1073    )?;
1074    Ok(RegionFilmstripArtifact {
1075        artifact: GeneratedArtifact::new(EncodedImage::new(layout.dimensions, bytes), manifest),
1076        plan,
1077    })
1078}
1079
1080/// A fixed-size crop location for one source frame.
1081#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
1082pub struct TrackedRegion {
1083    pub frame_index: usize,
1084    pub rect: SignedPixelRect,
1085}
1086
1087/// Parameters for a filmstrip whose crop follows a recorded region per frame.
1088#[derive(Clone, Debug, Eq, PartialEq)]
1089pub struct TrackedFilmstripParameters {
1090    pub regions: Vec<TrackedRegion>,
1091    pub anchor: Timestamp,
1092    pub tile_limit: FilmstripTileLimit,
1093    pub background: Rgb8,
1094    pub padding_color: Rgb8,
1095    pub display_scale: IntegerScale,
1096    pub labels: RegionFilmstripLabels,
1097    pub limits: RegionFilmstripRenderLimits,
1098}
1099
1100impl TrackedFilmstripParameters {
1101    #[allow(clippy::too_many_arguments)]
1102    pub fn new(
1103        regions: Vec<TrackedRegion>,
1104        anchor: Timestamp,
1105        tile_limit: FilmstripTileLimit,
1106        background: Rgb8,
1107        padding_color: Rgb8,
1108        display_scale: IntegerScale,
1109        labels: RegionFilmstripLabels,
1110        limits: RegionFilmstripRenderLimits,
1111    ) -> Self {
1112        Self {
1113            regions,
1114            anchor,
1115            tile_limit,
1116            background,
1117            padding_color,
1118            display_scale,
1119            labels,
1120            limits,
1121        }
1122    }
1123}
1124
1125/// Generate a per-frame moving crop. All tiles share the first union crop for
1126/// normalization, while their plans retain their own source rectangle/padding.
1127pub fn generate_tracked_region_filmstrip<A, F, M, G, P>(
1128    artifact_id: A,
1129    source: &FrameSequence<F, M, G, P>,
1130    parameters: TrackedFilmstripParameters,
1131) -> Result<RegionFilmstripArtifact<A, F, M, G>>
1132where
1133    F: Clone + Eq + Display,
1134    M: Clone + Eq,
1135    G: Clone + Eq,
1136    P: AsRef<[u8]>,
1137{
1138    if parameters.regions.is_empty() {
1139        return Err(VisionError::new(
1140            ErrorCode::InvalidParameter,
1141            "tracked filmstrip requires regions",
1142        ));
1143    }
1144    let selected = select_indices(
1145        source.frames().len(),
1146        usize::from(parameters.tile_limit.get()),
1147    );
1148    let mut by_frame = std::collections::BTreeMap::new();
1149    for region in parameters.regions {
1150        by_frame.insert(region.frame_index, region.rect);
1151    }
1152    let first = by_frame.values().next().copied().ok_or_else(|| {
1153        VisionError::new(
1154            ErrorCode::InvalidParameter,
1155            "tracked filmstrip requires regions",
1156        )
1157    })?;
1158    let mut union = first;
1159    for rect in by_frame.values().copied() {
1160        if rect.width() != first.width() || rect.height() != first.height() {
1161            return Err(VisionError::new(
1162                ErrorCode::InvalidRegion,
1163                "tracked crop dimensions must remain fixed",
1164            ));
1165        }
1166        let left = union.x().min(rect.x());
1167        let top = union.y().min(rect.y());
1168        let right = union.right_exclusive()?.max(rect.right_exclusive()?);
1169        let bottom = union.bottom_exclusive()?.max(rect.bottom_exclusive()?);
1170        union = SignedPixelRect::from_outward_f64_bounds(
1171            left as f64,
1172            top as f64,
1173            right as f64,
1174            bottom as f64,
1175        )?;
1176    }
1177    let tile_dims = PixelDimensions::new(first.width(), first.height())?;
1178    let mut tiles = Vec::with_capacity(selected.len());
1179    for index in &selected {
1180        let frame = &source.frames()[*index];
1181        let Some(rect) = by_frame.get(index).copied() else {
1182            tiles.push(FilmstripTilePlan {
1183                frame_id: frame.id().clone(),
1184                frame_index: *index,
1185                timestamp: frame.timestamp(),
1186                anchor_offset_nanos: i128::from(frame.timestamp().as_nanos())
1187                    - i128::from(parameters.anchor.as_nanos()),
1188                source_rect: None,
1189                padding: PaddingInsets {
1190                    left: first.width(),
1191                    top: first.height(),
1192                    right: first.width(),
1193                    bottom: first.height(),
1194                },
1195                gap_after: false,
1196            });
1197            continue;
1198        };
1199        let (source_rect, padding) = intersect_region(rect, source.dimensions())?;
1200        tiles.push(FilmstripTilePlan {
1201            frame_id: frame.id().clone(),
1202            frame_index: *index,
1203            timestamp: frame.timestamp(),
1204            anchor_offset_nanos: i128::from(frame.timestamp().as_nanos())
1205                - i128::from(parameters.anchor.as_nanos()),
1206            source_rect,
1207            padding,
1208            gap_after: false,
1209        });
1210    }
1211    let plan = RegionFilmstripPlan {
1212        tiles: tiles.into_boxed_slice(),
1213        locator_frame_index: selected[0],
1214        coordinate_space: RegionCoordinateSpace::SourceImage,
1215        declared_region: union,
1216        resolved_source_region: union,
1217        tile_source_dimensions: tile_dims,
1218        omitted_frame_count: (source.frames().len() - selected.len()) as u64,
1219    };
1220    let tile_source = FrameSequence::new(
1221        selected
1222            .iter()
1223            .map(|i| source.frames()[*i].to_owned())
1224            .collect(),
1225        Vec::<Marker<M>>::new(),
1226        Vec::<DeclaredGap<G>>::new(),
1227        source.region(),
1228        source.mask().cloned(),
1229    )?;
1230    let normalized = normalize_sequence(
1231        &tile_source,
1232        NormalizationParameters::new(
1233            parameters.background,
1234            Some(
1235                intersect_region(union, source.dimensions())?
1236                    .0
1237                    .unwrap_or(PixelRect::new(0, 0, 1, 1)?),
1238            ),
1239            IntegerScale::IDENTITY,
1240            parameters.limits.processing_limits(),
1241        ),
1242    )?;
1243    let locator_source = FrameSequence::new(
1244        vec![source.frames()[selected[0]].to_owned()],
1245        Vec::<Marker<M>>::new(),
1246        Vec::<DeclaredGap<G>>::new(),
1247        None,
1248        None,
1249    )?;
1250    let locator = normalize_sequence(
1251        &locator_source,
1252        NormalizationParameters::new(
1253            parameters.background,
1254            None,
1255            IntegerScale::IDENTITY,
1256            parameters.limits.processing_limits(),
1257        ),
1258    )?;
1259    let display_dims = scaled_tile_dimensions(tile_dims, parameters.display_scale)?;
1260    let layout = FilmstripLayout::new(display_dims, selected.len(), parameters.limits)?;
1261    let mut canvas = Canvas::new(
1262        layout.dimensions,
1263        BLACK,
1264        parameters.limits.max_canvas_bytes(),
1265    )?;
1266    let fixed = RegionFilmstripParameters::new(
1267        RegionDefinition::FixedSourceImage { rect: union },
1268        parameters.anchor,
1269        parameters.tile_limit,
1270        parameters.background,
1271        parameters.padding_color,
1272        parameters.display_scale,
1273        parameters.labels,
1274        parameters.limits,
1275    )
1276    .with_tracking_label("TRACKING NODE | PER-FRAME REGION");
1277    render_filmstrip(
1278        &mut canvas,
1279        layout,
1280        source,
1281        &normalized,
1282        &locator,
1283        &plan,
1284        &fixed,
1285    )?;
1286    let (bytes, hash) = crate::encode::encode_png(
1287        layout.dimensions,
1288        canvas.pixels(),
1289        parameters.limits.max_encoded_bytes(),
1290    )?;
1291    let manifest = ArtifactManifest::from_sequence_with_domain(
1292        artifact_id,
1293        ArtifactKind::RegionFilmstrip,
1294        EvidenceClass::SourceDerived,
1295        {
1296            let d = generator_descriptor(ArtifactKind::RegionFilmstrip);
1297            AlgorithmDescriptor::new(d.name, d.version)?
1298        },
1299        source,
1300        manifest_region(
1301            RegionDefinition::FixedSourceImage { rect: union },
1302            source.dimensions(),
1303        )?,
1304        None,
1305        selected
1306            .iter()
1307            .map(|i| source.frames()[*i].id().clone())
1308            .collect(),
1309        crate::provenance::SequenceConsumption::SelectedFramesOnly,
1310        Vec::new(),
1311        Parameters::new(BTreeMap::new())?,
1312        layout.dimensions,
1313        hash,
1314    )?;
1315    Ok(RegionFilmstripArtifact {
1316        artifact: GeneratedArtifact::new(EncodedImage::new(layout.dimensions, bytes), manifest),
1317        plan,
1318    })
1319}
1320
1321#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1322struct FilmstripLayout {
1323    dimensions: PixelDimensions,
1324    locator_panel: PixelRect,
1325    locator_annotation: PixelRect,
1326    strip_x: u32,
1327    strip_y: u32,
1328    tile_slot_width: u32,
1329    tile_width: u32,
1330    tile_height: u32,
1331    columns: usize,
1332    rows: usize,
1333    timeline_y: u32,
1334}
1335
1336impl FilmstripLayout {
1337    fn new(
1338        tile: PixelDimensions,
1339        tile_count: usize,
1340        limits: RegionFilmstripRenderLimits,
1341    ) -> Result<Self> {
1342        let tile_slot_width = tile.width().max(MINIMUM_TILE_SLOT_WIDTH);
1343        let fixed_width = MARGIN
1344            .checked_mul(2)
1345            .and_then(|value| value.checked_add(LOCATOR_WIDTH))
1346            .and_then(|value| value.checked_add(SECTION_GAP))
1347            .ok_or_else(canvas_limit_error)?;
1348        let available = limits
1349            .max_width()
1350            .checked_sub(fixed_width)
1351            .ok_or_else(canvas_limit_error)?;
1352        let columns = usize::try_from(
1353            available
1354                .checked_add(TILE_GAP)
1355                .ok_or_else(canvas_limit_error)?
1356                / tile_slot_width
1357                    .checked_add(TILE_GAP)
1358                    .ok_or_else(canvas_limit_error)?,
1359        )
1360        .map_err(|_| canvas_limit_error())?
1361        .min(tile_count);
1362        if columns == 0 {
1363            return Err(canvas_limit_error());
1364        }
1365        let rows = tile_count.div_ceil(columns);
1366        let columns_u32 = u32::try_from(columns).map_err(|_| canvas_limit_error())?;
1367        let rows_u32 = u32::try_from(rows).map_err(|_| canvas_limit_error())?;
1368        let strip_width = columns_u32
1369            .checked_mul(tile_slot_width)
1370            .and_then(|value| {
1371                value.checked_add(TILE_GAP.checked_mul(columns_u32.saturating_sub(1))?)
1372            })
1373            .ok_or_else(canvas_limit_error)?;
1374        let row_height = tile
1375            .height()
1376            .checked_add(TILE_ANNOTATION_HEIGHT)
1377            .ok_or_else(canvas_limit_error)?;
1378        let strip_height = rows_u32
1379            .checked_mul(row_height)
1380            .and_then(|value| value.checked_add(TILE_GAP.checked_mul(rows_u32 - 1)?))
1381            .ok_or_else(canvas_limit_error)?;
1382        let locator_height = LOCATOR_HEIGHT
1383            .checked_add(LOCATOR_ANNOTATION_HEIGHT)
1384            .ok_or_else(canvas_limit_error)?;
1385        let content_height = strip_height.max(locator_height);
1386        let width = fixed_width
1387            .checked_add(strip_width)
1388            .ok_or_else(canvas_limit_error)?;
1389        let timeline_y = HEADER_HEIGHT
1390            .checked_add(MARGIN)
1391            .and_then(|value| value.checked_add(content_height))
1392            .and_then(|value| value.checked_add(MARGIN))
1393            .ok_or_else(canvas_limit_error)?;
1394        let height = timeline_y
1395            .checked_add(TIMELINE_HEIGHT)
1396            .ok_or_else(canvas_limit_error)?;
1397        if width > limits.max_width() || height > limits.max_height() {
1398            return Err(canvas_output_limit_error(
1399                width,
1400                height,
1401                limits.max_width(),
1402                limits.max_height(),
1403            ));
1404        }
1405        let dimensions = PixelDimensions::new(width, height).map_err(|_| canvas_limit_error())?;
1406        let bytes = dimensions
1407            .pixel_count()?
1408            .checked_mul(3)
1409            .ok_or_else(canvas_limit_error)?;
1410        if bytes > limits.max_canvas_bytes() {
1411            return Err(canvas_limit_error());
1412        }
1413        let locator_y = HEADER_HEIGHT + MARGIN;
1414        Ok(Self {
1415            dimensions,
1416            locator_panel: PixelRect::new(MARGIN, locator_y, LOCATOR_WIDTH, LOCATOR_HEIGHT)?,
1417            locator_annotation: PixelRect::new(
1418                MARGIN,
1419                locator_y + LOCATOR_HEIGHT,
1420                LOCATOR_WIDTH,
1421                LOCATOR_ANNOTATION_HEIGHT,
1422            )?,
1423            strip_x: MARGIN + LOCATOR_WIDTH + SECTION_GAP,
1424            strip_y: locator_y,
1425            tile_slot_width,
1426            tile_width: tile.width(),
1427            tile_height: tile.height(),
1428            columns,
1429            rows,
1430            timeline_y,
1431        })
1432    }
1433
1434    fn tile_slot(self, index: usize) -> Result<PixelRect> {
1435        let column = u32::try_from(index % self.columns).map_err(|_| canvas_limit_error())?;
1436        let row = u32::try_from(index / self.columns).map_err(|_| canvas_limit_error())?;
1437        let x = self
1438            .strip_x
1439            .checked_add(
1440                column
1441                    .checked_mul(self.tile_slot_width + TILE_GAP)
1442                    .ok_or_else(canvas_limit_error)?,
1443            )
1444            .ok_or_else(canvas_limit_error)?;
1445        let y = self
1446            .strip_y
1447            .checked_add(
1448                row.checked_mul(self.tile_height + TILE_ANNOTATION_HEIGHT + TILE_GAP)
1449                    .ok_or_else(canvas_limit_error)?,
1450            )
1451            .ok_or_else(canvas_limit_error)?;
1452        PixelRect::new(
1453            x,
1454            y,
1455            self.tile_slot_width,
1456            self.tile_height + TILE_ANNOTATION_HEIGHT,
1457        )
1458    }
1459}
1460
1461fn scaled_tile_dimensions(source: PixelDimensions, scale: IntegerScale) -> Result<PixelDimensions> {
1462    let factor = u32::from(scale.factor());
1463    let (width, height) = match scale.direction_name() {
1464        "identity" => (source.width(), source.height()),
1465        "up" => (
1466            source
1467                .width()
1468                .checked_mul(factor)
1469                .ok_or_else(invalid_scale_error)?,
1470            source
1471                .height()
1472                .checked_mul(factor)
1473                .ok_or_else(invalid_scale_error)?,
1474        ),
1475        "down" => {
1476            if source.width() % factor != 0 || source.height() % factor != 0 {
1477                return Err(VisionError::new(
1478                    ErrorCode::InvalidScale,
1479                    "filmstrip downscale factor must exactly divide declared region dimensions",
1480                ));
1481            }
1482            (source.width() / factor, source.height() / factor)
1483        }
1484        _ => unreachable!("integer scale direction is a closed internal registry"),
1485    };
1486    PixelDimensions::new(width, height).map_err(|_| invalid_scale_error())
1487}
1488
1489fn render_filmstrip<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
1490    canvas: &mut Canvas,
1491    layout: FilmstripLayout,
1492    source: &FrameSequence<F, M, G, P>,
1493    normalized: &crate::NormalizedSequence<F>,
1494    locator_normalized: &crate::NormalizedSequence<F>,
1495    plan: &RegionFilmstripPlan<F>,
1496    parameters: &RegionFilmstripParameters,
1497) -> Result<()> {
1498    draw_header(canvas, source, plan, parameters)?;
1499    draw_locator(
1500        canvas,
1501        layout,
1502        &locator_normalized.frames()[0],
1503        source.dimensions(),
1504        plan,
1505    )?;
1506    for (index, tile) in plan.tiles().iter().enumerate() {
1507        draw_tile(
1508            canvas,
1509            layout,
1510            index,
1511            tile,
1512            &normalized.frames()[index],
1513            normalized.source_crop(),
1514            parameters,
1515        )?;
1516    }
1517    draw_timeline(canvas, layout, source)
1518}
1519
1520fn draw_header<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
1521    canvas: &mut Canvas,
1522    source: &FrameSequence<F, M, G, P>,
1523    plan: &RegionFilmstripPlan<F>,
1524    parameters: &RegionFilmstripParameters,
1525) -> Result<()> {
1526    canvas.fill_rect(0, 0, canvas.dimensions().width(), HEADER_HEIGHT, BLACK)?;
1527    let width = canvas.dimensions().width().saturating_sub(8);
1528    draw_clipped_text(canvas, 4, 2, width, parameters.labels.title(), WHITE)?;
1529    draw_clipped_text(canvas, 4, 14, width, parameters.labels.source(), MUTED)?;
1530    draw_clipped_text(
1531        canvas,
1532        4,
1533        26,
1534        width,
1535        &format!(
1536            "RANGE {} - {} | ANCHOR {}",
1537            format_time(source.range().start()),
1538            format_time(source.range().end()),
1539            format_time(parameters.anchor)
1540        ),
1541        MUTED,
1542    )?;
1543    let status = if source.gaps().is_empty() {
1544        if let Some(label) = parameters.tracking_label.as_deref() {
1545            format!(
1546                "SOURCE-DERIVED | PER-FRAME REGION | {label} | STRIP OMITTED {}",
1547                plan.omitted_frame_count()
1548            )
1549        } else {
1550            format!(
1551                "SOURCE-DERIVED | FIXED {} | TRACKING NONE | STRIP OMITTED {}",
1552                plan.coordinate_space().as_str(),
1553                plan.omitted_frame_count()
1554            )
1555        }
1556    } else if let Some(label) = parameters.tracking_label.as_deref() {
1557        format!("GAP - UNSEEN BEHAVIOR MAY HAVE OCCURRED | PER-FRAME REGION | {label}")
1558    } else {
1559        format!(
1560            "GAP - UNSEEN BEHAVIOR MAY HAVE OCCURRED | FIXED {} | TRACKING NONE",
1561            plan.coordinate_space().as_str()
1562        )
1563    };
1564    draw_clipped_text(
1565        canvas,
1566        4,
1567        38,
1568        width,
1569        &status,
1570        if source.gaps().is_empty() {
1571            MUTED
1572        } else {
1573            WARNING
1574        },
1575    )?;
1576    draw_clipped_text(
1577        canvas,
1578        4,
1579        50,
1580        width,
1581        if parameters.mask.is_some() {
1582            "MASK APPLIED | SELECTED PIXELS SHOWN | EXCLUDED PIXELS HATCHED"
1583        } else {
1584            parameters
1585                .tracking_label
1586                .as_deref()
1587                .unwrap_or("FIXED VISUAL REGION; NO LOGICAL ELEMENT FOLLOWING")
1588        },
1589        if parameters.mask.is_some() {
1590            WARNING
1591        } else {
1592            MUTED
1593        },
1594    )
1595}
1596
1597fn draw_locator<F>(
1598    canvas: &mut Canvas,
1599    layout: FilmstripLayout,
1600    frame: &crate::NormalizedFrame<F>,
1601    source_dimensions: PixelDimensions,
1602    plan: &RegionFilmstripPlan<F>,
1603) -> Result<()> {
1604    canvas.fill_rect(
1605        layout.locator_panel.x(),
1606        layout.locator_panel.y(),
1607        layout.locator_panel.width(),
1608        layout.locator_panel.height(),
1609        PANEL,
1610    )?;
1611    let (draw_x, draw_y, draw_width, draw_height) = canvas.draw_linear_frame(
1612        frame.dimensions(),
1613        frame.linear_rgb16(),
1614        layout.locator_panel.x(),
1615        layout.locator_panel.y(),
1616        layout.locator_panel.width(),
1617        layout.locator_panel.height(),
1618    )?;
1619    let (intersection, _) = intersect_region(plan.resolved_source_region(), source_dimensions)?;
1620    if let Some(rect) = intersection {
1621        let x0 = draw_x + map_floor(rect.x(), draw_width, source_dimensions.width())?;
1622        let y0 = draw_y + map_floor(rect.y(), draw_height, source_dimensions.height())?;
1623        let x1 = draw_x
1624            + map_ceil(
1625                rect.right_exclusive()?,
1626                draw_width,
1627                source_dimensions.width(),
1628            )?;
1629        let y1 = draw_y
1630            + map_ceil(
1631                rect.bottom_exclusive()?,
1632                draw_height,
1633                source_dimensions.height(),
1634            )?;
1635        draw_outline(
1636            canvas,
1637            x0,
1638            y0,
1639            x1.saturating_sub(x0),
1640            y1.saturating_sub(y0),
1641            WARNING,
1642        )?;
1643    }
1644    let resolved = plan.resolved_source_region();
1645    let right = resolved.right_exclusive()?;
1646    let bottom = resolved.bottom_exclusive()?;
1647    let mut outside = Vec::new();
1648    if resolved.x() < 0 {
1649        draw_edge_chevrons(canvas, draw_x, draw_y, draw_width, draw_height, Edge::Left)?;
1650        outside.push("LEFT");
1651    }
1652    if right > i64::from(source_dimensions.width()) {
1653        draw_edge_chevrons(canvas, draw_x, draw_y, draw_width, draw_height, Edge::Right)?;
1654        outside.push("RIGHT");
1655    }
1656    if resolved.y() < 0 {
1657        draw_edge_chevrons(canvas, draw_x, draw_y, draw_width, draw_height, Edge::Top)?;
1658        outside.push("TOP");
1659    }
1660    if bottom > i64::from(source_dimensions.height()) {
1661        draw_edge_chevrons(
1662            canvas,
1663            draw_x,
1664            draw_y,
1665            draw_width,
1666            draw_height,
1667            Edge::Bottom,
1668        )?;
1669        outside.push("BOTTOM");
1670    }
1671    canvas.fill_rect(
1672        layout.locator_annotation.x(),
1673        layout.locator_annotation.y(),
1674        layout.locator_annotation.width(),
1675        layout.locator_annotation.height(),
1676        PANEL,
1677    )?;
1678    draw_clipped_text(
1679        canvas,
1680        layout.locator_annotation.x() + 3,
1681        layout.locator_annotation.y() + 3,
1682        layout.locator_annotation.width().saturating_sub(6),
1683        "REGION IN CONTEXT",
1684        WHITE,
1685    )?;
1686    draw_clipped_text(
1687        canvas,
1688        layout.locator_annotation.x() + 3,
1689        layout.locator_annotation.y() + 15,
1690        layout.locator_annotation.width().saturating_sub(6),
1691        &format!("LOCATOR FRAME {}", plan.locator_frame_index()),
1692        MUTED,
1693    )?;
1694    let outside_label = if outside.is_empty() {
1695        "REGION INSIDE SOURCE".to_owned()
1696    } else {
1697        format!("OUTSIDE: {}", outside.join(" + "))
1698    };
1699    draw_clipped_text(
1700        canvas,
1701        layout.locator_annotation.x() + 3,
1702        layout.locator_annotation.y() + 27,
1703        layout.locator_annotation.width().saturating_sub(6),
1704        &outside_label,
1705        if outside.is_empty() { MUTED } else { WARNING },
1706    )
1707}
1708
1709fn draw_tile<F: Display>(
1710    canvas: &mut Canvas,
1711    layout: FilmstripLayout,
1712    index: usize,
1713    tile: &FilmstripTilePlan<F>,
1714    frame: &crate::NormalizedFrame<F>,
1715    crop: PixelRect,
1716    parameters: &RegionFilmstripParameters,
1717) -> Result<()> {
1718    let slot = layout.tile_slot(index)?;
1719    let image_x = slot.x() + (slot.width() - layout.tile_width) / 2;
1720    canvas.fill_rect(slot.x(), slot.y(), slot.width(), layout.tile_height, PANEL)?;
1721    for y in 0..layout.tile_height {
1722        for x in 0..layout.tile_width {
1723            let (color, padding) = scaled_region_pixel(
1724                frame,
1725                tile,
1726                parameters.mask.as_ref(),
1727                parameters.padding_color.channels(),
1728                parameters.display_scale,
1729                crop,
1730                x,
1731                y,
1732            )?;
1733            let color = if padding && (x + y) % 8 < 2 {
1734                WARNING
1735            } else {
1736                color
1737            };
1738            canvas.set_pixel(image_x + x, slot.y() + y, color)?;
1739        }
1740    }
1741    let annotation_y = slot.y() + layout.tile_height;
1742    canvas.fill_rect(
1743        slot.x(),
1744        annotation_y,
1745        slot.width(),
1746        TILE_ANNOTATION_HEIGHT,
1747        PANEL,
1748    )?;
1749    let text_width = slot.width().saturating_sub(6);
1750    draw_clipped_text(
1751        canvas,
1752        slot.x() + 3,
1753        annotation_y + 2,
1754        text_width,
1755        &format!(
1756            "T {} | {}",
1757            format_time(tile.timestamp()),
1758            format_offset(tile.anchor_offset_nanos())
1759        ),
1760        WHITE,
1761    )?;
1762    draw_clipped_text(
1763        canvas,
1764        slot.x() + 3,
1765        annotation_y + 14,
1766        text_width,
1767        &format!(
1768            "FRAME {} | SOURCE INDEX {}",
1769            tile.frame_id(),
1770            tile.frame_index()
1771        ),
1772        MUTED,
1773    )?;
1774    let padding = tile.padding();
1775    let padding_label = if tile.source_rect().is_none() {
1776        "OUTSIDE SOURCE | ALL PADDING".to_owned()
1777    } else if padding.is_empty() {
1778        "SOURCE CROP | NO PADDING".to_owned()
1779    } else {
1780        format!(
1781            "PADDING L{} T{} R{} B{}",
1782            padding.left(),
1783            padding.top(),
1784            padding.right(),
1785            padding.bottom()
1786        )
1787    };
1788    draw_clipped_text(
1789        canvas,
1790        slot.x() + 3,
1791        annotation_y + 26,
1792        text_width,
1793        &padding_label,
1794        if padding.is_empty() { MUTED } else { WARNING },
1795    )?;
1796    draw_clipped_text(
1797        canvas,
1798        slot.x() + 3,
1799        annotation_y + 38,
1800        text_width,
1801        if parameters.mask.is_some() {
1802            "FIXED MASK | TRACKING NONE"
1803        } else if parameters.tracking_label.is_some() {
1804            "TRACKED REGION | PER-FRAME CROP"
1805        } else {
1806            "FIXED REGION | TRACKING NONE"
1807        },
1808        if parameters.mask.is_some() {
1809            WARNING
1810        } else {
1811            MUTED
1812        },
1813    )?;
1814    if tile.gap_after() {
1815        let hatch_x = slot.right_exclusive()?.saturating_sub(6);
1816        canvas.draw_hatch(hatch_x, slot.y(), 6, slot.height(), WARNING)?;
1817        draw_clipped_text(
1818            canvas,
1819            slot.x() + 3,
1820            annotation_y + 44,
1821            text_width,
1822            "GAP ->",
1823            WARNING,
1824        )?;
1825    }
1826    Ok(())
1827}
1828
1829#[allow(clippy::too_many_arguments)]
1830fn scaled_region_pixel<F>(
1831    frame: &crate::NormalizedFrame<F>,
1832    tile: &FilmstripTilePlan<F>,
1833    mask: Option<&BinaryMask>,
1834    padding_color: [u8; 3],
1835    scale: IntegerScale,
1836    crop: PixelRect,
1837    output_x: u32,
1838    output_y: u32,
1839) -> Result<([u8; 3], bool)> {
1840    let factor = u32::from(scale.factor());
1841    if scale.direction_name() != "down" {
1842        let source_x = if scale.direction_name() == "up" {
1843            output_x / factor
1844        } else {
1845            output_x
1846        };
1847        let source_y = if scale.direction_name() == "up" {
1848            output_y / factor
1849        } else {
1850            output_y
1851        };
1852        return region_pixel(frame, tile, mask, padding_color, crop, source_x, source_y);
1853    }
1854
1855    let mut sums = [0_u64; 3];
1856    let mut padding = false;
1857    for dy in 0..factor {
1858        for dx in 0..factor {
1859            let (pixel, generated) = region_pixel(
1860                frame,
1861                tile,
1862                mask,
1863                padding_color,
1864                crop,
1865                output_x * factor + dx,
1866                output_y * factor + dy,
1867            )?;
1868            padding |= generated;
1869            for channel in 0..3 {
1870                sums[channel] += u64::from(pixel[channel]);
1871            }
1872        }
1873    }
1874    let count = u64::from(factor) * u64::from(factor);
1875    Ok((
1876        std::array::from_fn(|channel| ((sums[channel] + count / 2) / count) as u8),
1877        padding,
1878    ))
1879}
1880
1881fn region_pixel<F>(
1882    frame: &crate::NormalizedFrame<F>,
1883    tile: &FilmstripTilePlan<F>,
1884    mask: Option<&BinaryMask>,
1885    padding_color: [u8; 3],
1886    crop: PixelRect,
1887    x: u32,
1888    y: u32,
1889) -> Result<([u8; 3], bool)> {
1890    let padding = tile.padding();
1891    let Some(source_rect) = tile.source_rect() else {
1892        return Ok((padding_color, true));
1893    };
1894    let visible_x = x.checked_sub(padding.left());
1895    let visible_y = y.checked_sub(padding.top());
1896    if visible_x.is_none_or(|value| value >= source_rect.width())
1897        || visible_y.is_none_or(|value| value >= source_rect.height())
1898    {
1899        return Ok((padding_color, true));
1900    }
1901    let source_x = source_rect.x() + visible_x.expect("checked above");
1902    let source_y = source_rect.y() + visible_y.expect("checked above");
1903    if mask.is_some_and(|mask| mask.includes(source_x, source_y) != Some(true)) {
1904        return Ok((padding_color, true));
1905    }
1906    let index = usize::try_from(source_y.saturating_sub(crop.y()))
1907        .ok()
1908        .and_then(|row| row.checked_mul(usize::try_from(frame.dimensions().width()).ok()?))
1909        .and_then(|row| row.checked_add(usize::try_from(source_x.saturating_sub(crop.x())).ok()?))
1910        .and_then(|pixel| pixel.checked_mul(3))
1911        .ok_or_else(canvas_limit_error)?;
1912    let linear = &frame.linear_rgb16()[index..index + 3];
1913    Ok((
1914        [linear[0], linear[1], linear[2]].map(crate::normalize::linear16_to_srgb8),
1915        false,
1916    ))
1917}
1918
1919fn draw_timeline<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
1920    canvas: &mut Canvas,
1921    layout: FilmstripLayout,
1922    source: &FrameSequence<F, M, G, P>,
1923) -> Result<()> {
1924    canvas.fill_rect(
1925        0,
1926        layout.timeline_y,
1927        layout.dimensions.width(),
1928        TIMELINE_HEIGHT,
1929        BLACK,
1930    )?;
1931    draw_clipped_text(
1932        canvas,
1933        4,
1934        layout.timeline_y + 6,
1935        layout.dimensions.width().saturating_sub(8),
1936        &format!(
1937            "TIME -> {} -> {} | CHRONOLOGICAL SOURCE ORDER | ROWS {}",
1938            format_time(source.range().start()),
1939            format_time(source.range().end()),
1940            layout.rows
1941        ),
1942        WHITE,
1943    )
1944}
1945
1946#[derive(Clone, Copy)]
1947enum Edge {
1948    Left,
1949    Right,
1950    Top,
1951    Bottom,
1952}
1953
1954fn draw_edge_chevrons(
1955    canvas: &mut Canvas,
1956    x: u32,
1957    y: u32,
1958    width: u32,
1959    height: u32,
1960    edge: Edge,
1961) -> Result<()> {
1962    for offset in (4..match edge {
1963        Edge::Left | Edge::Right => height,
1964        _ => width,
1965    })
1966        .step_by(12)
1967    {
1968        for arm in 0..4 {
1969            let (px, py) = match edge {
1970                Edge::Left => (x + arm, y + offset.saturating_sub(2) + arm),
1971                Edge::Right => (x + width - 1 - arm, y + offset.saturating_sub(2) + arm),
1972                Edge::Top => (x + offset.saturating_sub(2) + arm, y + arm),
1973                Edge::Bottom => (x + offset.saturating_sub(2) + arm, y + height - 1 - arm),
1974            };
1975            if px < x + width && py < y + height {
1976                canvas.set_pixel(px, py, WARNING)?;
1977            }
1978        }
1979    }
1980    Ok(())
1981}
1982
1983fn draw_outline(
1984    canvas: &mut Canvas,
1985    x: u32,
1986    y: u32,
1987    width: u32,
1988    height: u32,
1989    color: [u8; 3],
1990) -> Result<()> {
1991    if width == 0 || height == 0 {
1992        return Ok(());
1993    }
1994    canvas.fill_rect(x, y, width, height.min(2), color)?;
1995    canvas.fill_rect(x, y + height.saturating_sub(2), width, height.min(2), color)?;
1996    canvas.fill_rect(x, y, width.min(2), height, color)?;
1997    canvas.fill_rect(x + width.saturating_sub(2), y, width.min(2), height, color)
1998}
1999
2000fn map_floor(value: u32, target: u32, source: u32) -> Result<u32> {
2001    u32::try_from(u64::from(value) * u64::from(target) / u64::from(source))
2002        .map_err(|_| canvas_limit_error())
2003}
2004
2005fn map_ceil(value: u32, target: u32, source: u32) -> Result<u32> {
2006    let numerator = u64::from(value)
2007        .checked_mul(u64::from(target))
2008        .and_then(|value| value.checked_add(u64::from(source) - 1))
2009        .ok_or_else(canvas_limit_error)?;
2010    u32::try_from(numerator / u64::from(source)).map_err(|_| canvas_limit_error())
2011}
2012
2013fn draw_clipped_text(
2014    canvas: &mut Canvas,
2015    x: u32,
2016    y: u32,
2017    width: u32,
2018    text: &str,
2019    color: [u8; 3],
2020) -> Result<()> {
2021    let cells = usize::try_from(width / CELL_WIDTH).unwrap_or(0);
2022    if cells == 0 {
2023        return Ok(());
2024    }
2025    draw_text(canvas, x, y, &ellipsize(text, cells), color)
2026}
2027
2028fn format_time(timestamp: Timestamp) -> String {
2029    let milliseconds = timestamp.as_nanos() / 1_000_000;
2030    let micros = timestamp.as_nanos() % 1_000_000 / 1_000;
2031    format!("{milliseconds}.{micros:03} MS")
2032}
2033
2034fn format_offset(offset: i128) -> String {
2035    let sign = if offset < 0 { '-' } else { '+' };
2036    let magnitude = offset.unsigned_abs();
2037    let milliseconds = magnitude / 1_000_000;
2038    let micros = magnitude % 1_000_000 / 1_000;
2039    format!("{sign}{milliseconds}.{micros:03} MS")
2040}
2041
2042fn display_conversion_step() -> Result<NormalizationStep> {
2043    NormalizationStep::new(
2044        NormalizationKind::ColorSpaceConversion,
2045        "linear16-to-srgb8-v1",
2046        make_parameters([
2047            ("input", ParameterValue::Text("rgb16_linear_opaque".into())),
2048            ("output", ParameterValue::Text("rgb8_srgb_opaque".into())),
2049            (
2050                "mapping",
2051                ParameterValue::Text("nearest_checked_lut_entry".into()),
2052            ),
2053        ])?,
2054    )
2055}
2056
2057fn region_padding_step<F>(
2058    plan: &RegionFilmstripPlan<F>,
2059    padding_color: Rgb8,
2060) -> Result<NormalizationStep> {
2061    NormalizationStep::new(
2062        NormalizationKind::FixedCrop,
2063        "fixed-region-padding-v1",
2064        make_parameters([
2065            (
2066                "resolved_source_region",
2067                signed_rect_value(plan.resolved_source_region())?,
2068            ),
2069            ("padding_rgb8", rgb_value(padding_color)),
2070            (
2071                "missing_pixels",
2072                ParameterValue::Text("explicit_padding_with_warning_hatch".into()),
2073            ),
2074        ])?,
2075    )
2076}
2077
2078fn mask_application_step<F>(
2079    mask: &BinaryMask,
2080    plan: &RegionFilmstripPlan<F>,
2081) -> Result<NormalizationStep> {
2082    NormalizationStep::new(
2083        NormalizationKind::FixedCrop,
2084        "fixed-binary-mask-v1",
2085        make_parameters([
2086            ("mask_dimensions", dimensions_value(mask.dimensions())?),
2087            (
2088                "mask_bounds",
2089                signed_rect_value(plan.resolved_source_region())?,
2090            ),
2091            (
2092                "excluded_pixels",
2093                ParameterValue::Text("padding_color_with_warning_hatch".into()),
2094            ),
2095            (
2096                "mask_sha256",
2097                ParameterValue::Text(mask_sha256(mask).into()),
2098            ),
2099        ])?,
2100    )
2101}
2102
2103fn display_scale_step(
2104    scale: IntegerScale,
2105    dimensions: PixelDimensions,
2106) -> Result<NormalizationStep> {
2107    NormalizationStep::new(
2108        NormalizationKind::IntegerScaling,
2109        "filmstrip-display-scale-v1",
2110        make_parameters([
2111            (
2112                "direction",
2113                ParameterValue::Text(scale.direction_name().into()),
2114            ),
2115            (
2116                "factor",
2117                ParameterValue::Unsigned(u64::from(scale.factor())),
2118            ),
2119            (
2120                "kernel",
2121                ParameterValue::Text(
2122                    if scale.direction_name() == "down" {
2123                        "non_overlapping_srgb8_box_average"
2124                    } else {
2125                        "nearest_neighbor"
2126                    }
2127                    .into(),
2128                ),
2129            ),
2130            ("output_dimensions", dimensions_value(dimensions)?),
2131        ])?,
2132    )
2133}
2134
2135fn manifest_region(
2136    region: RegionDefinition,
2137    dimensions: PixelDimensions,
2138) -> Result<Option<FrameRegion>> {
2139    let RegionDefinition::FixedSourceImage { rect } = region else {
2140        return Ok(None);
2141    };
2142    if rect.x() < 0 || rect.y() < 0 {
2143        return Ok(None);
2144    }
2145    let pixel_rect = PixelRect::new(
2146        u32::try_from(rect.x()).map_err(|_| invalid_region_error())?,
2147        u32::try_from(rect.y()).map_err(|_| invalid_region_error())?,
2148        rect.width(),
2149        rect.height(),
2150    )?;
2151    if !pixel_rect.fits_within(dimensions) {
2152        return Ok(None);
2153    }
2154    Ok(Some(FrameRegion::new(pixel_rect, dimensions)?))
2155}
2156
2157fn filmstrip_parameters<F: Display>(
2158    plan: &RegionFilmstripPlan<F>,
2159    artifact_source_indices: &[usize],
2160    source_frame_count: usize,
2161    request: &RegionFilmstripParameters,
2162    layout: FilmstripLayout,
2163    tile_dimensions: PixelDimensions,
2164) -> Result<Parameters> {
2165    let selected = plan
2166        .tiles()
2167        .iter()
2168        .map(|tile| {
2169            object([
2170                ("frame_index", unsigned_usize(tile.frame_index())?),
2171                (
2172                    "frame_label",
2173                    ParameterValue::Text(tile.frame_id().to_string().into()),
2174                ),
2175                (
2176                    "timestamp_nanos",
2177                    ParameterValue::Unsigned(tile.timestamp().as_nanos()),
2178                ),
2179                (
2180                    "anchor_offset",
2181                    signed_offset_value(tile.anchor_offset_nanos())?,
2182                ),
2183                (
2184                    "selection_reason",
2185                    ParameterValue::Text(
2186                        if plan.omitted_frame_count() == 0 {
2187                            "all_source_frames"
2188                        } else {
2189                            "uniform_source_order_coverage"
2190                        }
2191                        .into(),
2192                    ),
2193                ),
2194                ("source_rect", optional_rect_value(tile.source_rect())?),
2195                ("padding", padding_value(tile.padding())?),
2196                ("gap_after", ParameterValue::Bool(tile.gap_after())),
2197            ])
2198        })
2199        .collect::<Result<Vec<_>>>()?;
2200    let gap_warning_count = plan.tiles().iter().filter(|tile| tile.gap_after()).count();
2201    let mapping = match (request.mask.as_ref(), request.region) {
2202        (None, RegionDefinition::FixedViewport { mapping, .. }) => object([
2203            (
2204                "viewport_dimensions",
2205                dimensions_value(mapping.viewport_dimensions())?,
2206            ),
2207            ("scale_x", rational_value(mapping.scale_x())?),
2208            ("scale_y", rational_value(mapping.scale_y())?),
2209        ])?,
2210        _ => ParameterValue::Text("not_applicable".into()),
2211    };
2212    let effective_region = if request.mask.is_some() {
2213        RegionDefinition::FixedSourceImage {
2214            rect: plan.resolved_source_region(),
2215        }
2216    } else {
2217        request.region
2218    };
2219    let mask = request.mask.as_ref().map_or_else(
2220        || Ok(ParameterValue::Text("none".into())),
2221        |mask| {
2222            object([
2223                ("dimensions", dimensions_value(mask.dimensions())?),
2224                ("bounds", signed_rect_value(plan.resolved_source_region())?),
2225                ("sha256", ParameterValue::Text(mask_sha256(mask).into())),
2226                (
2227                    "encoding",
2228                    ParameterValue::Text("row_major_msb_first_one_bit".into()),
2229                ),
2230            ])
2231        },
2232    )?;
2233    Parameters::new(
2234        [
2235            (
2236                "algorithm_version".into(),
2237                ParameterValue::Text(
2238                    generator_descriptor(ArtifactKind::RegionFilmstrip)
2239                        .version
2240                        .into(),
2241                ),
2242            ),
2243            ("region_definition".into(), region_value(effective_region)?),
2244            ("mask".into(), mask),
2245            (
2246                "coordinate_space".into(),
2247                ParameterValue::Text(plan.coordinate_space().as_str().into()),
2248            ),
2249            ("viewport_mapping".into(), mapping),
2250            (
2251                "resolved_source_region".into(),
2252                signed_rect_value(plan.resolved_source_region())?,
2253            ),
2254            ("selected".into(), ParameterValue::List(selected)),
2255            (
2256                "artifact_source_indices".into(),
2257                ParameterValue::List(
2258                    artifact_source_indices
2259                        .iter()
2260                        .map(|index| unsigned_usize(*index))
2261                        .collect::<Result<Vec<_>>>()?,
2262                ),
2263            ),
2264            (
2265                "omitted_frame_count".into(),
2266                unsigned_usize(
2267                    source_frame_count
2268                        .checked_sub(artifact_source_indices.len())
2269                        .ok_or_else(render_limit_error)?,
2270                )?,
2271            ),
2272            (
2273                "strip_omitted_frame_count".into(),
2274                ParameterValue::Unsigned(plan.omitted_frame_count()),
2275            ),
2276            (
2277                "locator_frame_index".into(),
2278                unsigned_usize(plan.locator_frame_index())?,
2279            ),
2280            ("background_rgb8".into(), rgb_value(request.background)),
2281            ("padding_rgb8".into(), rgb_value(request.padding_color)),
2282            (
2283                "display_scale".into(),
2284                object([
2285                    (
2286                        "direction",
2287                        ParameterValue::Text(request.display_scale.direction_name().into()),
2288                    ),
2289                    (
2290                        "factor",
2291                        ParameterValue::Unsigned(u64::from(request.display_scale.factor())),
2292                    ),
2293                ])?,
2294            ),
2295            (
2296                "tile_source_dimensions".into(),
2297                dimensions_value(plan.tile_source_dimensions())?,
2298            ),
2299            (
2300                "tile_output_dimensions".into(),
2301                dimensions_value(tile_dimensions)?,
2302            ),
2303            (
2304                "gap_warning_count".into(),
2305                unsigned_usize(gap_warning_count)?,
2306            ),
2307            (
2308                "title".into(),
2309                ParameterValue::Text(request.labels.title().into()),
2310            ),
2311            (
2312                "source_context".into(),
2313                ParameterValue::Text(request.labels.source().into()),
2314            ),
2315            (
2316                "tracking_method".into(),
2317                ParameterValue::Text("none".into()),
2318            ),
2319            (
2320                "fixed_region_semantics".into(),
2321                ParameterValue::Text("no_logical_element_following".into()),
2322            ),
2323            (
2324                "label_truncation".into(),
2325                ParameterValue::Text("embedded_ascii_ellipsis_exact_text_in_manifest".into()),
2326            ),
2327            (
2328                "output_layout".into(),
2329                object([
2330                    (
2331                        "name",
2332                        ParameterValue::Text("locator_and_wrapped_strip_v1".into()),
2333                    ),
2334                    ("columns", unsigned_usize(layout.columns)?),
2335                    ("rows", unsigned_usize(layout.rows)?),
2336                    (
2337                        "tile_slot_width",
2338                        ParameterValue::Unsigned(u64::from(layout.tile_slot_width)),
2339                    ),
2340                    (
2341                        "time_direction",
2342                        ParameterValue::Text("left_to_right_then_next_row".into()),
2343                    ),
2344                ])?,
2345            ),
2346            (
2347                "png".into(),
2348                ParameterValue::Text("png-0.17.16-rgb8-best-no_filter-no_chunks".into()),
2349            ),
2350            (
2351                "max_output_width".into(),
2352                ParameterValue::Unsigned(u64::from(request.limits.max_width())),
2353            ),
2354            (
2355                "max_output_height".into(),
2356                ParameterValue::Unsigned(u64::from(request.limits.max_height())),
2357            ),
2358            (
2359                "max_canvas_bytes".into(),
2360                unsigned_usize(request.limits.max_canvas_bytes())?,
2361            ),
2362            (
2363                "max_encoded_bytes".into(),
2364                unsigned_usize(request.limits.max_encoded_bytes())?,
2365            ),
2366            (
2367                "max_source_frames".into(),
2368                unsigned_usize(request.limits.max_source_frames())?,
2369            ),
2370        ]
2371        .into_iter()
2372        .collect::<BTreeMap<_, _>>(),
2373    )
2374}
2375
2376fn region_value(region: RegionDefinition) -> Result<ParameterValue> {
2377    match region {
2378        RegionDefinition::FixedSourceImage { rect } => object([
2379            ("kind", ParameterValue::Text("fixed_source_image".into())),
2380            ("rect", signed_rect_value(rect)?),
2381        ]),
2382        RegionDefinition::FixedViewport { rect, mapping } => object([
2383            ("kind", ParameterValue::Text("fixed_viewport".into())),
2384            ("rect", signed_rect_value(rect)?),
2385            (
2386                "mapping",
2387                object([
2388                    (
2389                        "viewport_dimensions",
2390                        dimensions_value(mapping.viewport_dimensions())?,
2391                    ),
2392                    ("scale_x", rational_value(mapping.scale_x())?),
2393                    ("scale_y", rational_value(mapping.scale_y())?),
2394                ])?,
2395            ),
2396        ]),
2397    }
2398}
2399
2400fn signed_rect_value(rect: SignedPixelRect) -> Result<ParameterValue> {
2401    object([
2402        ("x", ParameterValue::Signed(rect.x())),
2403        ("y", ParameterValue::Signed(rect.y())),
2404        ("width", ParameterValue::Unsigned(u64::from(rect.width()))),
2405        ("height", ParameterValue::Unsigned(u64::from(rect.height()))),
2406    ])
2407}
2408
2409fn optional_rect_value(rect: Option<PixelRect>) -> Result<ParameterValue> {
2410    rect.map_or_else(
2411        || Ok(ParameterValue::Text("none".into())),
2412        |rect| {
2413            object([
2414                ("x", ParameterValue::Unsigned(u64::from(rect.x()))),
2415                ("y", ParameterValue::Unsigned(u64::from(rect.y()))),
2416                ("width", ParameterValue::Unsigned(u64::from(rect.width()))),
2417                ("height", ParameterValue::Unsigned(u64::from(rect.height()))),
2418            ])
2419        },
2420    )
2421}
2422
2423fn padding_value(padding: PaddingInsets) -> Result<ParameterValue> {
2424    object([
2425        ("left", ParameterValue::Unsigned(u64::from(padding.left()))),
2426        ("top", ParameterValue::Unsigned(u64::from(padding.top()))),
2427        (
2428            "right",
2429            ParameterValue::Unsigned(u64::from(padding.right())),
2430        ),
2431        (
2432            "bottom",
2433            ParameterValue::Unsigned(u64::from(padding.bottom())),
2434        ),
2435    ])
2436}
2437
2438fn rational_value(scale: RationalScale) -> Result<ParameterValue> {
2439    object([
2440        (
2441            "numerator",
2442            ParameterValue::Unsigned(u64::from(scale.numerator())),
2443        ),
2444        (
2445            "denominator",
2446            ParameterValue::Unsigned(u64::from(scale.denominator())),
2447        ),
2448    ])
2449}
2450
2451fn dimensions_value(dimensions: PixelDimensions) -> Result<ParameterValue> {
2452    object([
2453        (
2454            "width",
2455            ParameterValue::Unsigned(u64::from(dimensions.width())),
2456        ),
2457        (
2458            "height",
2459            ParameterValue::Unsigned(u64::from(dimensions.height())),
2460        ),
2461    ])
2462}
2463
2464fn mask_sha256(mask: &BinaryMask) -> String {
2465    let mut digest = Sha256::new();
2466    digest.update(mask.dimensions().width().to_be_bytes());
2467    digest.update(mask.dimensions().height().to_be_bytes());
2468    digest.update(mask.bits());
2469    digest
2470        .finalize()
2471        .iter()
2472        .map(|byte| format!("{byte:02x}"))
2473        .collect()
2474}
2475
2476fn rgb_value(color: Rgb8) -> ParameterValue {
2477    ParameterValue::List(
2478        color
2479            .channels()
2480            .into_iter()
2481            .map(|channel| ParameterValue::Unsigned(u64::from(channel)))
2482            .collect(),
2483    )
2484}
2485
2486fn signed_offset_value(value: i128) -> Result<ParameterValue> {
2487    let sign = if value < 0 { "negative" } else { "nonnegative" };
2488    let magnitude = u64::try_from(value.unsigned_abs()).map_err(|_| render_limit_error())?;
2489    object([
2490        ("sign", ParameterValue::Text(sign.into())),
2491        ("magnitude_nanos", ParameterValue::Unsigned(magnitude)),
2492    ])
2493}
2494
2495fn unsigned_usize(value: usize) -> Result<ParameterValue> {
2496    u64::try_from(value)
2497        .map(ParameterValue::Unsigned)
2498        .map_err(|_| render_limit_error())
2499}
2500
2501fn object<const N: usize>(entries: [(&'static str, ParameterValue); N]) -> Result<ParameterValue> {
2502    let values = entries
2503        .into_iter()
2504        .map(|(key, value)| (Box::<str>::from(key), value))
2505        .collect::<BTreeMap<_, _>>();
2506    Parameters::new(values.clone())?;
2507    Ok(ParameterValue::Object(values))
2508}
2509
2510fn render_limit_error() -> VisionError {
2511    VisionError::new(
2512        ErrorCode::ResourceLimitExceeded,
2513        "region filmstrip exceeds configured processing or rendering limits",
2514    )
2515}
2516
2517#[cfg(test)]
2518mod tests {
2519    use super::*;
2520    use crate::{DeclaredGap, Frame, Marker, PixelFormat};
2521
2522    fn source(frame_count: u8) -> FrameSequence<u8, u8, u8, Box<[u8]>> {
2523        let dimensions = PixelDimensions::new(8, 6).unwrap();
2524        FrameSequence::new(
2525            (0..frame_count)
2526                .map(|id| {
2527                    Frame::new(
2528                        id,
2529                        Timestamp::from_nanos(u64::from(id) * 10),
2530                        dimensions,
2531                        PixelFormat::Rgba8SrgbStraight,
2532                        vec![0; dimensions.rgba8_byte_len().unwrap()].into_boxed_slice(),
2533                    )
2534                    .unwrap()
2535                })
2536                .collect(),
2537            Vec::<Marker<u8>>::new(),
2538            Vec::<DeclaredGap<u8>>::new(),
2539            None,
2540            None,
2541        )
2542        .unwrap()
2543    }
2544
2545    #[test]
2546    fn resolves_outward_viewport_mapping_and_rejects_contradictions() {
2547        let mapping = ViewportMapping::new(
2548            PixelDimensions::new(4, 3).unwrap(),
2549            RationalScale::new(NonZeroU32::new(2).unwrap(), NonZeroU32::new(1).unwrap()),
2550            RationalScale::new(NonZeroU32::new(2).unwrap(), NonZeroU32::new(1).unwrap()),
2551        );
2552        let rect = SignedPixelRect::new(
2553            -1,
2554            1,
2555            NonZeroU32::new(3).unwrap(),
2556            NonZeroU32::new(2).unwrap(),
2557        )
2558        .unwrap();
2559        let plan = plan_region_filmstrip(
2560            &source(2),
2561            RegionDefinition::FixedViewport { rect, mapping },
2562            Timestamp::ZERO,
2563            FilmstripTileLimit::DEFAULT,
2564            None,
2565        )
2566        .unwrap();
2567        assert_eq!(plan.resolved_source_region().x(), -2);
2568        assert_eq!(plan.resolved_source_region().width(), 6);
2569        assert_eq!(plan.tiles()[0].padding().left(), 2);
2570        assert_eq!(plan.tiles()[0].source_rect().unwrap().width(), 4);
2571
2572        let wrong = ViewportMapping::new(
2573            PixelDimensions::new(5, 3).unwrap(),
2574            mapping.scale_x(),
2575            mapping.scale_y(),
2576        );
2577        assert_eq!(
2578            plan_region_filmstrip(
2579                &source(2),
2580                RegionDefinition::FixedViewport {
2581                    rect,
2582                    mapping: wrong,
2583                },
2584                Timestamp::ZERO,
2585                FilmstripTileLimit::DEFAULT,
2586                None,
2587            )
2588            .unwrap_err()
2589            .code,
2590            ErrorCode::InvalidScale
2591        );
2592    }
2593
2594    #[test]
2595    fn exact_padding_and_selection_cover_partial_and_fully_outside_regions() {
2596        let partial = SignedPixelRect::new(
2597            -2,
2598            -1,
2599            NonZeroU32::new(12).unwrap(),
2600            NonZeroU32::new(9).unwrap(),
2601        )
2602        .unwrap();
2603        let plan = plan_region_filmstrip(
2604            &source(10),
2605            RegionDefinition::FixedSourceImage { rect: partial },
2606            Timestamp::from_nanos(50),
2607            FilmstripTileLimit::new(4).unwrap(),
2608            None,
2609        )
2610        .unwrap();
2611        assert_eq!(
2612            plan.tiles()
2613                .iter()
2614                .map(FilmstripTilePlan::frame_index)
2615                .collect::<Vec<_>>(),
2616            [0, 3, 6, 9]
2617        );
2618        assert_eq!(plan.locator_frame_index(), 6);
2619        assert_eq!(plan.omitted_frame_count(), 6);
2620        let tile = &plan.tiles()[0];
2621        assert_eq!(
2622            tile.source_rect(),
2623            Some(PixelRect::new(0, 0, 8, 6).unwrap())
2624        );
2625        assert_eq!(
2626            tile.padding(),
2627            PaddingInsets {
2628                left: 2,
2629                top: 1,
2630                right: 2,
2631                bottom: 2
2632            }
2633        );
2634
2635        let outside = SignedPixelRect::new(
2636            20,
2637            20,
2638            NonZeroU32::new(3).unwrap(),
2639            NonZeroU32::new(2).unwrap(),
2640        )
2641        .unwrap();
2642        let plan = plan_region_filmstrip(
2643            &source(1),
2644            RegionDefinition::FixedSourceImage { rect: outside },
2645            Timestamp::ZERO,
2646            FilmstripTileLimit::DEFAULT,
2647            None,
2648        )
2649        .unwrap();
2650        assert_eq!(plan.tiles()[0].source_rect(), None);
2651        assert_eq!(
2652            plan.tiles()[0].padding(),
2653            PaddingInsets {
2654                left: 0,
2655                top: 0,
2656                right: 3,
2657                bottom: 2
2658            }
2659        );
2660    }
2661
2662    #[test]
2663    fn selected_tile_subsequence_matches_full_normalization() {
2664        let source = source(10);
2665        let region = SignedPixelRect::new(
2666            0,
2667            0,
2668            NonZeroU32::new(8).unwrap(),
2669            NonZeroU32::new(6).unwrap(),
2670        )
2671        .unwrap();
2672        let plan = plan_region_filmstrip(
2673            &source,
2674            RegionDefinition::FixedSourceImage { rect: region },
2675            Timestamp::from_nanos(50),
2676            FilmstripTileLimit::new(4).unwrap(),
2677            None,
2678        )
2679        .unwrap();
2680        let tile_source = FrameSequence::new(
2681            plan.tiles()
2682                .iter()
2683                .map(|tile| source.frames()[tile.frame_index()].clone())
2684                .collect(),
2685            Vec::<Marker<u8>>::new(),
2686            Vec::<DeclaredGap<u8>>::new(),
2687            None,
2688            None,
2689        )
2690        .unwrap();
2691        let limits = ProcessingLimits::default();
2692        let parameters = |sequence: &FrameSequence<u8, u8, u8, Box<[u8]>>| {
2693            normalize_sequence(
2694                sequence,
2695                NormalizationParameters::new(
2696                    Rgb8::new(0, 0, 0),
2697                    Some(PixelRect::new(0, 0, 8, 6).unwrap()),
2698                    IntegerScale::IDENTITY,
2699                    limits,
2700                ),
2701            )
2702            .unwrap()
2703        };
2704        let full = parameters(&source);
2705        let selected = parameters(&tile_source);
2706        for (position, tile) in plan.tiles().iter().enumerate() {
2707            assert_eq!(
2708                selected.frames()[position],
2709                full.frames()[tile.frame_index()]
2710            );
2711        }
2712    }
2713
2714    #[test]
2715    fn filmstrip_120_frames_fit_when_only_selected_tiles_are_retained() {
2716        let dimensions = PixelDimensions::new(128, 128).unwrap();
2717        let source = sized_source(120, dimensions);
2718        let region = SignedPixelRect::new(
2719            0,
2720            0,
2721            NonZeroU32::new(128).unwrap(),
2722            NonZeroU32::new(128).unwrap(),
2723        )
2724        .unwrap();
2725        let limits = RegionFilmstripRenderLimits::new(
2726            NonZeroU32::new(4_096).unwrap(),
2727            NonZeroU32::new(4_096).unwrap(),
2728            NonZeroUsize::new(1_000_000).unwrap(),
2729            NonZeroUsize::new(1_000_000).unwrap(),
2730        )
2731        .with_max_source_frames(NonZeroUsize::new(120).unwrap());
2732        let artifact = generate_region_filmstrip(
2733            1_u32,
2734            &source,
2735            RegionFilmstripParameters::new(
2736                RegionDefinition::FixedSourceImage { rect: region },
2737                Timestamp::from_nanos(400),
2738                FilmstripTileLimit::new(3).unwrap(),
2739                Rgb8::new(0, 0, 0),
2740                Rgb8::new(255, 0, 255),
2741                IntegerScale::IDENTITY,
2742                RegionFilmstripLabels::new("FILMSTRIP", "SOURCE").unwrap(),
2743                limits,
2744            ),
2745        )
2746        .unwrap();
2747        assert_eq!(artifact.plan().tiles().len(), 3);
2748        assert!(!artifact.image().bytes().is_empty());
2749    }
2750
2751    fn sized_source(
2752        frame_count: usize,
2753        dimensions: PixelDimensions,
2754    ) -> FrameSequence<u32, u32, u32, Box<[u8]>> {
2755        FrameSequence::new(
2756            (0..frame_count)
2757                .map(|id| {
2758                    Frame::new(
2759                        u32::try_from(id).unwrap(),
2760                        Timestamp::from_nanos(u64::try_from(id).unwrap() * 10),
2761                        dimensions,
2762                        PixelFormat::Rgba8SrgbStraight,
2763                        vec![0; dimensions.rgba8_byte_len().unwrap()].into_boxed_slice(),
2764                    )
2765                    .unwrap()
2766                })
2767                .collect(),
2768            Vec::<Marker<u32>>::new(),
2769            Vec::<DeclaredGap<u32>>::new(),
2770            None,
2771            None,
2772        )
2773        .unwrap()
2774    }
2775
2776    fn tracked_params(regions: Vec<TrackedRegion>, tile_limit: u8) -> TrackedFilmstripParameters {
2777        TrackedFilmstripParameters::new(
2778            regions,
2779            Timestamp::ZERO,
2780            FilmstripTileLimit::new(tile_limit).unwrap(),
2781            Rgb8::new(0, 0, 0),
2782            Rgb8::new(32, 32, 32),
2783            IntegerScale::IDENTITY,
2784            RegionFilmstripLabels::new("TRACKED".to_owned(), "TEST".to_owned()).unwrap(),
2785            RegionFilmstripRenderLimits::default(),
2786        )
2787    }
2788
2789    fn rect(x: i64, y: i64, w: u32, h: u32) -> SignedPixelRect {
2790        SignedPixelRect::new(
2791            x,
2792            y,
2793            NonZeroU32::new(w).unwrap(),
2794            NonZeroU32::new(h).unwrap(),
2795        )
2796        .unwrap()
2797    }
2798
2799    #[test]
2800    fn tracked_filmstrip_crops_each_tile_from_its_own_region() {
2801        // 4 frames at 8x6; two 4x3 regions at opposite corners. Evenly-spaced
2802        // selection over 4 frames with limit 4 selects all frames, but only
2803        // frames 1 and 3 have regions.
2804        let seq = sized_source(4, PixelDimensions::new(8, 6).unwrap());
2805        let artifact = generate_tracked_region_filmstrip(
2806            "tracked",
2807            &seq,
2808            tracked_params(
2809                vec![
2810                    TrackedRegion {
2811                        frame_index: 1,
2812                        rect: rect(0, 0, 4, 3),
2813                    },
2814                    TrackedRegion {
2815                        frame_index: 3,
2816                        rect: rect(4, 3, 4, 3),
2817                    },
2818                ],
2819                4,
2820            ),
2821        )
2822        .unwrap();
2823        let tiles = artifact.plan().tiles();
2824        assert_eq!(tiles.len(), 4);
2825        // Frame 1: top-left region, fully inside the source.
2826        let tile1 = &tiles[1];
2827        assert_eq!(tile1.source_rect().unwrap().x(), 0);
2828        assert_eq!(tile1.source_rect().unwrap().y(), 0);
2829        assert!(tile1.padding().is_empty());
2830        // Frame 3: bottom-right region, fully inside the source.
2831        let tile3 = &tiles[3];
2832        assert_eq!(tile3.source_rect().unwrap().x(), 4);
2833        assert_eq!(tile3.source_rect().unwrap().y(), 3);
2834        assert!(tile3.padding().is_empty());
2835        assert!(!artifact.image().bytes().is_empty());
2836    }
2837
2838    #[test]
2839    fn tracked_filmstrip_missing_selected_frame_renders_padded_tile() {
2840        // Regions only cover frames 0 and 3; the selected middle frames get
2841        // fully-padded tiles instead of an error.
2842        let seq = sized_source(4, PixelDimensions::new(8, 6).unwrap());
2843        let artifact = generate_tracked_region_filmstrip(
2844            "tracked",
2845            &seq,
2846            tracked_params(
2847                vec![
2848                    TrackedRegion {
2849                        frame_index: 0,
2850                        rect: rect(0, 0, 4, 3),
2851                    },
2852                    TrackedRegion {
2853                        frame_index: 3,
2854                        rect: rect(0, 0, 4, 3),
2855                    },
2856                ],
2857                4,
2858            ),
2859        )
2860        .unwrap();
2861        let tiles = artifact.plan().tiles();
2862        assert_eq!(tiles.len(), 4);
2863        for index in [1usize, 2] {
2864            let tile = &tiles[index];
2865            assert!(
2866                tile.source_rect().is_none(),
2867                "frame {index} without a region must be fully padded"
2868            );
2869            assert_eq!(tile.padding().left(), 4);
2870            assert_eq!(tile.padding().top(), 3);
2871        }
2872        assert!(!artifact.image().bytes().is_empty());
2873    }
2874
2875    #[test]
2876    fn tracked_filmstrip_is_deterministic() {
2877        let seq = sized_source(3, PixelDimensions::new(8, 6).unwrap());
2878        let make = || {
2879            generate_tracked_region_filmstrip(
2880                "tracked",
2881                &seq,
2882                tracked_params(
2883                    vec![
2884                        TrackedRegion {
2885                            frame_index: 0,
2886                            rect: rect(0, 0, 4, 3),
2887                        },
2888                        TrackedRegion {
2889                            frame_index: 2,
2890                            rect: rect(2, 1, 4, 3),
2891                        },
2892                    ],
2893                    3,
2894                ),
2895            )
2896            .unwrap()
2897        };
2898        assert_eq!(make().image().bytes(), make().image().bytes());
2899    }
2900
2901    #[test]
2902    fn tracked_filmstrip_rejects_inconsistent_crop_dimensions() {
2903        let seq = sized_source(3, PixelDimensions::new(8, 6).unwrap());
2904        let result = generate_tracked_region_filmstrip(
2905            "tracked",
2906            &seq,
2907            tracked_params(
2908                vec![
2909                    TrackedRegion {
2910                        frame_index: 0,
2911                        rect: rect(0, 0, 4, 3),
2912                    },
2913                    TrackedRegion {
2914                        frame_index: 1,
2915                        rect: rect(0, 0, 2, 3),
2916                    },
2917                ],
2918                3,
2919            ),
2920        );
2921        assert!(result.is_err());
2922    }
2923}