Skip to main content

temporal_vision/
select.rs

1use std::cmp::Ordering;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use crate::{
6    ComparisonOutcome, ErrorCode, FrameSequence, MeasurementParameters, MeasurementVector,
7    NormalizedSequence, Result, Timestamp, VisionError, measure_adjacent, measure_pair,
8};
9
10const MIN_TILES: u8 = 3;
11const MAX_TILES: u8 = 12;
12
13stable_registry! {
14    /// Stable descriptive reason why a source frame appears in a storyboard.
15    pub enum SelectionReason {
16        PreAnchor => "pre_anchor",
17        PostAnchor => "post_anchor",
18        FirstChange => "first_change",
19        PeakBaselineChange => "peak_baseline_change",
20        FinalFrame => "final_frame",
21        MarkerBoundary => "marker_boundary",
22        GapBoundary => "gap_boundary",
23        LocalChangePeak => "local_change_peak",
24        ChangeTrend => "change_trend",
25        ChangedRegionTransition => "changed_region_transition",
26        InformationGain => "information_gain",
27        TemporalCoverage => "temporal_coverage",
28    }
29}
30
31/// Hard maximum number of storyboard source panels.
32#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
33#[serde(transparent)]
34pub struct StoryboardTileLimit(u8);
35
36impl StoryboardTileLimit {
37    pub const DEFAULT: Self = Self(8);
38
39    pub fn new(value: u8) -> Result<Self> {
40        if !(MIN_TILES..=MAX_TILES).contains(&value) {
41            return Err(VisionError::new(
42                ErrorCode::InvalidParameter,
43                "storyboard tile limit must be between three and twelve",
44            ));
45        }
46        Ok(Self(value))
47    }
48
49    pub const fn get(self) -> u8 {
50        self.0
51    }
52}
53
54impl Default for StoryboardTileLimit {
55    fn default() -> Self {
56        Self::DEFAULT
57    }
58}
59
60/// One selected source frame and every unique reason assigned to it.
61#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct SelectedFrame<FrameId> {
64    frame_id: FrameId,
65    frame_index: usize,
66    timestamp: Timestamp,
67    reasons: Box<[SelectionReason]>,
68}
69
70impl<F> SelectedFrame<F> {
71    pub fn frame_id(&self) -> &F {
72        &self.frame_id
73    }
74
75    pub const fn frame_index(&self) -> usize {
76        self.frame_index
77    }
78
79    pub const fn timestamp(&self) -> Timestamp {
80        self.timestamp
81    }
82
83    pub fn reasons(&self) -> &[SelectionReason] {
84        &self.reasons
85    }
86}
87
88/// An available required or boundary anchor displaced by the hard tile budget.
89#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
90#[serde(deny_unknown_fields)]
91pub struct OmittedAnchor {
92    frame_index: usize,
93    reason: SelectionReason,
94}
95
96impl OmittedAnchor {
97    pub const fn frame_index(&self) -> usize {
98        self.frame_index
99    }
100
101    pub const fn reason(&self) -> SelectionReason {
102        self.reason
103    }
104}
105
106/// One authoritative visual-change decision retained from selector measurements.
107#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
108#[serde(deny_unknown_fields)]
109pub struct VisualChangeMoment<FrameId> {
110    frame_id: FrameId,
111    frame_index: usize,
112    timestamp: Timestamp,
113    comparison: crate::FrameComparison,
114}
115
116impl<F> VisualChangeMoment<F> {
117    pub fn frame_id(&self) -> &F {
118        &self.frame_id
119    }
120
121    pub const fn frame_index(&self) -> usize {
122        self.frame_index
123    }
124
125    pub const fn timestamp(&self) -> Timestamp {
126        self.timestamp
127    }
128
129    pub const fn comparison(&self) -> &crate::FrameComparison {
130        &self.comparison
131    }
132
133    fn validate_local(&self) -> Result<()> {
134        let changed = matches!(
135            self.comparison.outcome(),
136            ComparisonOutcome::Measured(vector)
137                if vector.changed_pixel_proportion().changed() > 0
138        );
139        if self.frame_index != self.comparison.later_frame_index() || !changed {
140            return Err(VisionError::new(
141                ErrorCode::InvalidManifest,
142                "storyboard visual moments must name the changed later comparison frame",
143            ));
144        }
145        Ok(())
146    }
147}
148
149impl<'de, F: Deserialize<'de>> Deserialize<'de> for VisualChangeMoment<F> {
150    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
151        #[derive(Deserialize)]
152        #[serde(bound(deserialize = "F: Deserialize<'de>"), deny_unknown_fields)]
153        struct Wire<F> {
154            frame_id: F,
155            frame_index: usize,
156            timestamp: Timestamp,
157            comparison: crate::FrameComparison,
158        }
159        let wire = Wire::deserialize(deserializer)?;
160        let moment = Self {
161            frame_id: wire.frame_id,
162            frame_index: wire.frame_index,
163            timestamp: wire.timestamp,
164            comparison: wire.comparison,
165        };
166        moment.validate_local().map_err(serde::de::Error::custom)?;
167        Ok(moment)
168    }
169}
170
171/// Direct moments already measured while constructing one storyboard selection.
172#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
173#[serde(deny_unknown_fields)]
174pub struct StoryboardVisualSummary<FrameId> {
175    first_change: Option<VisualChangeMoment<FrameId>>,
176    peak_baseline_change: Option<VisualChangeMoment<FrameId>>,
177    peak_adjacent_changed_area: Option<VisualChangeMoment<FrameId>>,
178}
179
180impl<F> StoryboardVisualSummary<F> {
181    pub const fn first_change(&self) -> Option<&VisualChangeMoment<F>> {
182        self.first_change.as_ref()
183    }
184
185    pub const fn peak_baseline_change(&self) -> Option<&VisualChangeMoment<F>> {
186        self.peak_baseline_change.as_ref()
187    }
188
189    pub const fn peak_adjacent_changed_area(&self) -> Option<&VisualChangeMoment<F>> {
190        self.peak_adjacent_changed_area.as_ref()
191    }
192
193    fn validate_local(&self) -> Result<()> {
194        for moment in [
195            self.first_change.as_ref(),
196            self.peak_baseline_change.as_ref(),
197            self.peak_adjacent_changed_area.as_ref(),
198        ]
199        .into_iter()
200        .flatten()
201        {
202            moment.validate_local()?;
203        }
204        Ok(())
205    }
206}
207
208impl<'de, F: Deserialize<'de>> Deserialize<'de> for StoryboardVisualSummary<F> {
209    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
210        #[derive(Deserialize)]
211        #[serde(bound(deserialize = "F: Deserialize<'de>"), deny_unknown_fields)]
212        struct Wire<F> {
213            first_change: Option<VisualChangeMoment<F>>,
214            peak_baseline_change: Option<VisualChangeMoment<F>>,
215            peak_adjacent_changed_area: Option<VisualChangeMoment<F>>,
216        }
217        let wire = Wire::deserialize(deserializer)?;
218        let summary = Self {
219            first_change: wire.first_change,
220            peak_baseline_change: wire.peak_baseline_change,
221            peak_adjacent_changed_area: wire.peak_adjacent_changed_area,
222        };
223        summary.validate_local().map_err(serde::de::Error::custom)?;
224        Ok(summary)
225    }
226}
227
228/// Reusable deterministic source-frame plan shared by storyboard renderers.
229#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
230pub struct StoryboardSelection<FrameId> {
231    selected_frames: Box<[SelectedFrame<FrameId>]>,
232    omitted_anchors: Box<[OmittedAnchor]>,
233    before_index: usize,
234    during_index: usize,
235    after_index: usize,
236    continuity_segment_count: usize,
237    visual_summary: StoryboardVisualSummary<FrameId>,
238}
239
240impl<F> StoryboardSelection<F> {
241    pub fn selected_frames(&self) -> &[SelectedFrame<F>] {
242        &self.selected_frames
243    }
244
245    pub fn omitted_anchors(&self) -> &[OmittedAnchor] {
246        &self.omitted_anchors
247    }
248
249    /// Source-sequence index used by the orientation composite's BEFORE panel.
250    pub const fn before_index(&self) -> usize {
251        self.before_index
252    }
253
254    /// Source-sequence index used by the orientation composite's DURING panel.
255    pub const fn during_index(&self) -> usize {
256        self.during_index
257    }
258
259    /// Source-sequence index used by the orientation composite's AFTER panel.
260    pub const fn after_index(&self) -> usize {
261        self.after_index
262    }
263
264    pub const fn continuity_segment_count(&self) -> usize {
265        self.continuity_segment_count
266    }
267
268    pub const fn visual_summary(&self) -> &StoryboardVisualSummary<F> {
269        &self.visual_summary
270    }
271
272    pub(crate) fn remap_source_indices(mut self, indices: &[usize]) -> Result<Self> {
273        let remap = |index: usize| {
274            indices.get(index).copied().ok_or_else(|| {
275                VisionError::new(
276                    ErrorCode::InvalidManifest,
277                    "bounded storyboard index has no source provenance",
278                )
279            })
280        };
281        for selected in &mut self.selected_frames {
282            selected.frame_index = remap(selected.frame_index)?;
283        }
284        for anchor in &mut self.omitted_anchors {
285            anchor.frame_index = remap(anchor.frame_index)?;
286        }
287        self.before_index = remap(self.before_index)?;
288        self.during_index = remap(self.during_index)?;
289        self.after_index = remap(self.after_index)?;
290        for moment in [
291            self.visual_summary.first_change.as_mut(),
292            self.visual_summary.peak_baseline_change.as_mut(),
293            self.visual_summary.peak_adjacent_changed_area.as_mut(),
294        ]
295        .into_iter()
296        .flatten()
297        {
298            moment.frame_index = remap(moment.frame_index)?;
299            moment.comparison = moment.comparison.clone().remap_indices(
300                remap(moment.comparison.earlier_frame_index())?,
301                remap(moment.comparison.later_frame_index())?,
302            );
303        }
304        Ok(self)
305    }
306}
307
308impl<F: Eq> StoryboardSelection<F> {
309    pub(crate) fn validate_local(&self) -> Result<()> {
310        if self.selected_frames.is_empty()
311            || self.continuity_segment_count == 0
312            || self.before_index > self.during_index
313            || self.during_index > self.after_index
314        {
315            return Err(VisionError::new(
316                ErrorCode::InvalidManifest,
317                "storyboard selection roles and counts are invalid",
318            ));
319        }
320        for (position, frame) in self.selected_frames.iter().enumerate() {
321            if frame.reasons.is_empty()
322                || frame
323                    .reasons
324                    .iter()
325                    .enumerate()
326                    .any(|(index, reason)| frame.reasons[..index].contains(reason))
327                || self.selected_frames[..position]
328                    .iter()
329                    .any(|prior| prior.frame_id == frame.frame_id)
330                || position > 0
331                    && (self.selected_frames[position - 1].frame_index >= frame.frame_index
332                        || self.selected_frames[position - 1].timestamp > frame.timestamp)
333            {
334                return Err(VisionError::new(
335                    ErrorCode::InvalidManifest,
336                    "storyboard selected frames must be unique, ordered, and reasoned",
337                ));
338            }
339        }
340        self.visual_summary.validate_local()?;
341        if let Some(moment) = self.visual_summary.peak_baseline_change() {
342            if moment.comparison().earlier_frame_index() != self.before_index
343                || moment.frame_index() != self.during_index
344            {
345                return Err(VisionError::new(
346                    ErrorCode::InvalidManifest,
347                    "storyboard peak baseline moment must agree with orientation roles",
348                ));
349            }
350        }
351        Ok(())
352    }
353}
354
355impl<'de, F> Deserialize<'de> for StoryboardSelection<F>
356where
357    F: Deserialize<'de> + Eq,
358{
359    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
360        #[derive(Deserialize)]
361        #[serde(bound(deserialize = "F: Deserialize<'de>"), deny_unknown_fields)]
362        struct Wire<F> {
363            selected_frames: Box<[SelectedFrame<F>]>,
364            omitted_anchors: Box<[OmittedAnchor]>,
365            before_index: usize,
366            during_index: usize,
367            after_index: usize,
368            continuity_segment_count: usize,
369            visual_summary: StoryboardVisualSummary<F>,
370        }
371        let wire = Wire::deserialize(deserializer)?;
372        let selection = Self {
373            selected_frames: wire.selected_frames,
374            omitted_anchors: wire.omitted_anchors,
375            before_index: wire.before_index,
376            during_index: wire.during_index,
377            after_index: wire.after_index,
378            continuity_segment_count: wire.continuity_segment_count,
379            visual_summary: wire.visual_summary,
380        };
381        selection
382            .validate_local()
383            .map_err(serde::de::Error::custom)?;
384        Ok(selection)
385    }
386}
387
388/// Select representative source frames using the temporal-storyboard 1.1.0 rules.
389pub fn select_storyboard_frames<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
390    source: &FrameSequence<F, M, G, P>,
391    normalized: &NormalizedSequence<F>,
392    anchor: Timestamp,
393    tile_limit: StoryboardTileLimit,
394    measurement: MeasurementParameters,
395) -> Result<StoryboardSelection<F>> {
396    select_storyboard_frames_with_analysis(
397        source,
398        normalized,
399        anchor,
400        tile_limit,
401        measurement,
402        None,
403    )
404}
405
406pub fn select_storyboard_frames_with_analysis<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
407    source: &FrameSequence<F, M, G, P>,
408    normalized: &NormalizedSequence<F>,
409    anchor: Timestamp,
410    tile_limit: StoryboardTileLimit,
411    measurement: MeasurementParameters,
412    shared: Option<&crate::SharedAdjacentAnalysis<F>>,
413) -> Result<StoryboardSelection<F>> {
414    validate_alignment(source, normalized)?;
415    if !source.range().contains(anchor) {
416        return Err(VisionError::new(
417            ErrorCode::InvalidParameter,
418            "storyboard anchor must lie inside the source frame range",
419        ));
420    }
421
422    // A shared result is an optimization only. Never let a stale or differently sampled
423    // analysis authorize indexes into this consumer's plan.
424    let shared = shared.filter(|analysis| analysis.is_compatible_with(normalized, measurement));
425    let frame_count = source.frames().len();
426    let adjacent_owned;
427    let adjacent = if let Some(shared) = shared {
428        shared.comparisons()
429    } else {
430        adjacent_owned = measure_adjacent(normalized, measurement)?;
431        &adjacent_owned
432    };
433    let analysis = SelectionAnalysis::new(adjacent, source, frame_count)?;
434    let baseline = source
435        .frames()
436        .iter()
437        .rposition(|frame| frame.timestamp() < anchor)
438        .unwrap_or(0);
439    let post_anchor = source
440        .frames()
441        .iter()
442        .position(|frame| frame.timestamp() > anchor);
443    let first_change_comparison = first_change_comparison(adjacent, normalized, anchor);
444    let first_change = first_change_comparison.map(crate::FrameComparison::later_frame_index);
445    let peak_baseline_comparison =
446        peak_baseline_comparison(normalized, baseline, &analysis, measurement)?;
447    let peak = peak_baseline_comparison
448        .as_ref()
449        .map(crate::FrameComparison::later_frame_index);
450    let peak_adjacent_comparison = peak_adjacent_changed_area_comparison(adjacent);
451    let visual_summary = StoryboardVisualSummary {
452        first_change: first_change_comparison
453            .map(|comparison| visual_moment(source, comparison.clone())),
454        peak_baseline_change: peak_baseline_comparison
455            .clone()
456            .map(|comparison| visual_moment(source, comparison)),
457        peak_adjacent_changed_area: peak_adjacent_comparison
458            .map(|comparison| visual_moment(source, comparison.clone())),
459    };
460    let final_frame = frame_count - 1;
461
462    let mut selected = vec![false; frame_count];
463    let mut reasons = vec![Vec::<SelectionReason>::new(); frame_count];
464    let mut omitted = Vec::new();
465    let limit = usize::from(tile_limit.get());
466
467    // The priority makes a three-tile request preserve the orientation spine.
468    admit_anchor(
469        baseline,
470        SelectionReason::PreAnchor,
471        limit,
472        &mut selected,
473        &mut reasons,
474        &mut omitted,
475    );
476    if let Some(index) = peak {
477        admit_anchor(
478            index,
479            SelectionReason::PeakBaselineChange,
480            limit,
481            &mut selected,
482            &mut reasons,
483            &mut omitted,
484        );
485    }
486    admit_anchor(
487        final_frame,
488        SelectionReason::FinalFrame,
489        limit,
490        &mut selected,
491        &mut reasons,
492        &mut omitted,
493    );
494    if let Some(index) = first_change {
495        admit_anchor(
496            index,
497            SelectionReason::FirstChange,
498            limit,
499            &mut selected,
500            &mut reasons,
501            &mut omitted,
502        );
503    }
504    if let Some(index) = post_anchor {
505        admit_anchor(
506            index,
507            SelectionReason::PostAnchor,
508            limit,
509            &mut selected,
510            &mut reasons,
511            &mut omitted,
512        );
513    }
514
515    let mut boundary_roles = vec![Vec::<SelectionReason>::new(); frame_count];
516    for marker in source.markers() {
517        let index = source
518            .frames()
519            .iter()
520            .position(|frame| frame.timestamp() >= marker.timestamp())
521            .unwrap_or(final_frame);
522        boundary_roles[index].push(SelectionReason::MarkerBoundary);
523    }
524    for gap in source.gaps() {
525        if let Some(index) = source
526            .frames()
527            .iter()
528            .rposition(|frame| frame.timestamp() < gap.range().start())
529        {
530            boundary_roles[index].push(SelectionReason::GapBoundary);
531        }
532        if let Some(index) = source
533            .frames()
534            .iter()
535            .position(|frame| frame.timestamp() > gap.range().end())
536        {
537            boundary_roles[index].push(SelectionReason::GapBoundary);
538        }
539    }
540
541    // Supplementary anchors are admitted in source declaration order. Repeated
542    // boundaries on one source frame merge into one panel and one visible reason.
543    for (index, boundary_reasons) in boundary_roles.iter().enumerate() {
544        for reason in boundary_reasons.iter().copied() {
545            admit_anchor(
546                index,
547                reason,
548                limit,
549                &mut selected,
550                &mut reasons,
551                &mut omitted,
552            );
553        }
554    }
555
556    while selected.iter().filter(|value| **value).count() < limit
557        && selected.iter().any(|value| !*value)
558    {
559        let index = best_fill_candidate(source, &analysis, &selected, &boundary_roles)?;
560        selected[index] = true;
561        let candidate_reasons = fill_reasons(index, &analysis, &selected, &boundary_roles);
562        for reason in candidate_reasons {
563            push_unique(&mut reasons[index], reason);
564        }
565    }
566
567    let selected_frames = source
568        .frames()
569        .iter()
570        .enumerate()
571        .filter(|(index, _)| selected[*index])
572        .map(|(index, frame)| SelectedFrame {
573            frame_id: frame.id().clone(),
574            frame_index: index,
575            timestamp: frame.timestamp(),
576            reasons: std::mem::take(&mut reasons[index]).into_boxed_slice(),
577        })
578        .collect::<Vec<_>>()
579        .into_boxed_slice();
580
581    Ok(StoryboardSelection {
582        selected_frames,
583        omitted_anchors: omitted.into_boxed_slice(),
584        before_index: baseline,
585        during_index: peak.or(post_anchor).unwrap_or(baseline),
586        after_index: final_frame,
587        continuity_segment_count: analysis.segment_count,
588        visual_summary,
589    })
590}
591
592fn validate_alignment<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
593    source: &FrameSequence<F, M, G, P>,
594    normalized: &NormalizedSequence<F>,
595) -> Result<()> {
596    if source.frames().len() != normalized.frames().len()
597        || source
598            .frames()
599            .iter()
600            .zip(normalized.frames())
601            .any(|(left, right)| {
602                left.id() != right.id()
603                    || left.timestamp() != right.timestamp()
604                    || right.dimensions() != normalized.dimensions()
605            })
606    {
607        return Err(VisionError::new(
608            ErrorCode::InvalidParameter,
609            "source and normalized sequences must have aligned frame identity, time, and geometry",
610        ));
611    }
612    Ok(())
613}
614
615fn first_change_comparison<'a, F>(
616    adjacent: &'a [crate::FrameComparison],
617    normalized: &NormalizedSequence<F>,
618    anchor: Timestamp,
619) -> Option<&'a crate::FrameComparison> {
620    let changed = |comparison: &&crate::FrameComparison| {
621        matches!(
622            comparison.outcome(),
623            ComparisonOutcome::Measured(vector)
624                if vector.changed_pixel_proportion().changed() > 0
625        )
626    };
627    adjacent
628        .iter()
629        .filter(changed)
630        .find(|comparison| {
631            normalized.frames()[comparison.later_frame_index()].timestamp() >= anchor
632        })
633        .or_else(|| adjacent.iter().find(changed))
634}
635
636fn peak_baseline_comparison<F>(
637    normalized: &NormalizedSequence<F>,
638    baseline: usize,
639    analysis: &SelectionAnalysis,
640    measurement: MeasurementParameters,
641) -> Result<Option<crate::FrameComparison>> {
642    let segment = analysis.segments[baseline];
643    let mut best = None;
644    let mut best_metrics = None::<PeakMetrics>;
645    for index in (baseline + 1)..normalized.frames().len() {
646        if analysis.segments[index] != segment {
647            break;
648        }
649        let comparison = measure_pair(normalized, baseline, index, measurement)?;
650        let ComparisonOutcome::Measured(vector) = comparison.outcome() else {
651            break;
652        };
653        let metrics = PeakMetrics::from_vector(vector, index);
654        if metrics.distance == 0 && metrics.changed == 0 {
655            continue;
656        }
657        if best_metrics
658            .as_ref()
659            .is_none_or(|current| metrics > *current)
660        {
661            best = Some(comparison);
662            best_metrics = Some(metrics);
663        }
664    }
665    Ok(best)
666}
667
668fn peak_adjacent_changed_area_comparison(
669    adjacent: &[crate::FrameComparison],
670) -> Option<&crate::FrameComparison> {
671    let mut best: Option<&crate::FrameComparison> = None;
672    for comparison in adjacent {
673        let ComparisonOutcome::Measured(candidate) = comparison.outcome() else {
674            continue;
675        };
676        let candidate_area = candidate.changed_pixel_proportion();
677        if candidate_area.changed() == 0 {
678            continue;
679        }
680        let replace = best.is_none_or(|current| {
681            let ComparisonOutcome::Measured(current) = current.outcome() else {
682                unreachable!("only measured comparisons become changed-area candidates")
683            };
684            let current_area = current.changed_pixel_proportion();
685            u128::from(candidate_area.changed()) * u128::from(current_area.compared())
686                > u128::from(current_area.changed()) * u128::from(candidate_area.compared())
687        });
688        // Equality deliberately keeps the earliest source comparison.
689        if replace {
690            best = Some(comparison);
691        }
692    }
693    best
694}
695
696fn visual_moment<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
697    source: &FrameSequence<F, M, G, P>,
698    comparison: crate::FrameComparison,
699) -> VisualChangeMoment<F> {
700    let frame_index = comparison.later_frame_index();
701    let frame = &source.frames()[frame_index];
702    VisualChangeMoment {
703        frame_id: frame.id().clone(),
704        frame_index,
705        timestamp: frame.timestamp(),
706        comparison,
707    }
708}
709
710#[derive(Clone, Copy, Debug, Eq, PartialEq)]
711struct PeakMetrics {
712    distance: u16,
713    changed: u64,
714    compared: u64,
715    absolute: u64,
716    reverse_index: usize,
717}
718
719impl PeakMetrics {
720    fn from_vector(vector: &MeasurementVector, index: usize) -> Self {
721        let proportion = vector.changed_pixel_proportion();
722        Self {
723            distance: vector.perceptual_frame_distance(),
724            changed: proportion.changed(),
725            compared: proportion.compared(),
726            absolute: vector.absolute_pixel_difference(),
727            reverse_index: usize::MAX - index,
728        }
729    }
730}
731
732impl Ord for PeakMetrics {
733    fn cmp(&self, other: &Self) -> Ordering {
734        self.distance
735            .cmp(&other.distance)
736            .then(self.changed.cmp(&other.changed))
737            .then_with(|| {
738                (u128::from(self.changed) * u128::from(other.compared))
739                    .cmp(&(u128::from(other.changed) * u128::from(self.compared)))
740            })
741            .then(self.absolute.cmp(&other.absolute))
742            .then(self.reverse_index.cmp(&other.reverse_index))
743    }
744}
745
746impl PartialOrd for PeakMetrics {
747    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
748        Some(self.cmp(other))
749    }
750}
751
752fn admit_anchor(
753    index: usize,
754    reason: SelectionReason,
755    limit: usize,
756    selected: &mut [bool],
757    reasons: &mut [Vec<SelectionReason>],
758    omitted: &mut Vec<OmittedAnchor>,
759) {
760    if selected[index] {
761        push_unique(&mut reasons[index], reason);
762    } else if selected.iter().filter(|value| **value).count() < limit {
763        selected[index] = true;
764        reasons[index].push(reason);
765    } else {
766        omitted.push(OmittedAnchor {
767            frame_index: index,
768            reason,
769        });
770    }
771}
772
773fn push_unique(reasons: &mut Vec<SelectionReason>, reason: SelectionReason) {
774    if !reasons.contains(&reason) {
775        reasons.push(reason);
776    }
777}
778
779#[derive(Debug)]
780struct SelectionAnalysis {
781    segments: Vec<usize>,
782    cumulative_change: Vec<u64>,
783    incoming_change: Vec<u16>,
784    local_peak: Vec<u16>,
785    trend_delta: Vec<u16>,
786    region_transition: Vec<bool>,
787    segment_count: usize,
788}
789
790impl SelectionAnalysis {
791    fn new<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
792        adjacent: &[crate::FrameComparison],
793        _source: &FrameSequence<F, M, G, P>,
794        frame_count: usize,
795    ) -> Result<Self> {
796        let mut segments = vec![0; frame_count];
797        let mut cumulative_change = vec![0_u64; frame_count];
798        let mut incoming_change = vec![0_u16; frame_count];
799        let mut changed_region = vec![false; frame_count];
800        let mut segment = 0_usize;
801        for comparison in adjacent {
802            let later = comparison.later_frame_index();
803            match comparison.outcome() {
804                ComparisonOutcome::GapBoundary { .. } => {
805                    segment = segment.checked_add(1).ok_or_else(score_overflow)?;
806                    segments[later] = segment;
807                    cumulative_change[later] = 0;
808                }
809                ComparisonOutcome::Measured(vector) => {
810                    segments[later] = segment;
811                    incoming_change[later] = vector.perceptual_frame_distance();
812                    changed_region[later] = vector.changed_region_bounds().is_some();
813                    cumulative_change[later] = cumulative_change[later - 1]
814                        .checked_add(u64::from(vector.perceptual_frame_distance()))
815                        .ok_or_else(score_overflow)?;
816                }
817            }
818        }
819        let mut local_peak = vec![0; frame_count];
820        let mut trend_delta = vec![0; frame_count];
821        let mut region_transition = vec![false; frame_count];
822        for index in 1..frame_count {
823            if segments[index] != segments[index - 1] {
824                continue;
825            }
826            let current = incoming_change[index];
827            let previous = if index > 1 && segments[index - 1] == segments[index - 2] {
828                incoming_change[index - 1]
829            } else {
830                0
831            };
832            let next = if index + 1 < frame_count && segments[index + 1] == segments[index] {
833                incoming_change[index + 1]
834            } else {
835                0
836            };
837            if current >= previous && current > next {
838                local_peak[index] = current;
839            }
840            trend_delta[index] = current.abs_diff(previous).max(current.abs_diff(next));
841            region_transition[index] = changed_region[index] != changed_region[index - 1];
842        }
843        Ok(Self {
844            segments,
845            cumulative_change,
846            incoming_change,
847            local_peak,
848            trend_delta,
849            region_transition,
850            segment_count: segment + 1,
851        })
852    }
853}
854
855#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
856struct FillScore {
857    unrepresented_segment: bool,
858    supplementary_roles: usize,
859    information_gain: u64,
860    local_peak: u16,
861    trend_delta: u16,
862    region_transition: bool,
863    temporal_coverage: u64,
864    reverse_index: usize,
865}
866
867fn best_fill_candidate<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
868    source: &FrameSequence<F, M, G, P>,
869    analysis: &SelectionAnalysis,
870    selected: &[bool],
871    boundary_roles: &[Vec<SelectionReason>],
872) -> Result<usize> {
873    let represented = selected
874        .iter()
875        .enumerate()
876        .filter(|(_, value)| **value)
877        .map(|(index, _)| analysis.segments[index])
878        .collect::<Vec<_>>();
879    (0..selected.len())
880        .filter(|index| !selected[*index])
881        .map(|index| {
882            score_candidate(
883                source,
884                analysis,
885                selected,
886                boundary_roles,
887                &represented,
888                index,
889            )
890            .map(|score| (score, index))
891        })
892        .collect::<Result<Vec<_>>>()?
893        .into_iter()
894        .max_by_key(|(score, _)| *score)
895        .map(|(_, index)| index)
896        .ok_or_else(score_overflow)
897}
898
899fn score_candidate<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
900    source: &FrameSequence<F, M, G, P>,
901    analysis: &SelectionAnalysis,
902    selected: &[bool],
903    boundary_roles: &[Vec<SelectionReason>],
904    represented: &[usize],
905    index: usize,
906) -> Result<FillScore> {
907    Ok(FillScore {
908        unrepresented_segment: !represented.contains(&analysis.segments[index]),
909        supplementary_roles: boundary_roles[index].len(),
910        information_gain: nearest_selected_distance(index, selected, |left, right| {
911            if analysis.segments[left] != analysis.segments[right] {
912                None
913            } else {
914                Some(analysis.cumulative_change[left].abs_diff(analysis.cumulative_change[right]))
915            }
916        }),
917        local_peak: analysis.local_peak[index],
918        trend_delta: analysis.trend_delta[index],
919        region_transition: analysis.region_transition[index],
920        temporal_coverage: nearest_selected_distance(index, selected, |left, right| {
921            Some(
922                source.frames()[left]
923                    .timestamp()
924                    .as_nanos()
925                    .abs_diff(source.frames()[right].timestamp().as_nanos()),
926            )
927        }),
928        reverse_index: usize::MAX - index,
929    })
930}
931
932fn nearest_selected_distance(
933    index: usize,
934    selected: &[bool],
935    distance: impl Fn(usize, usize) -> Option<u64>,
936) -> u64 {
937    let predecessor = (0..index)
938        .rev()
939        .find(|candidate| selected[*candidate] && distance(index, *candidate).is_some());
940    let successor = ((index + 1)..selected.len())
941        .find(|candidate| selected[*candidate] && distance(index, *candidate).is_some());
942    match (predecessor, successor) {
943        (Some(left), Some(right)) => distance(index, left)
944            .expect("filtered")
945            .min(distance(index, right).expect("filtered")),
946        (Some(left), None) => distance(index, left).expect("filtered"),
947        (None, Some(right)) => distance(index, right).expect("filtered"),
948        (None, None) => 0,
949    }
950}
951
952fn fill_reasons(
953    index: usize,
954    analysis: &SelectionAnalysis,
955    selected_after: &[bool],
956    boundary_roles: &[Vec<SelectionReason>],
957) -> Vec<SelectionReason> {
958    let mut reasons = boundary_roles[index].clone();
959    reasons.sort_by_key(|reason| {
960        SelectionReason::ALL
961            .iter()
962            .position(|value| value == reason)
963    });
964    reasons.dedup();
965    if analysis.local_peak[index] > 0 {
966        reasons.push(SelectionReason::LocalChangePeak);
967    }
968    if analysis.trend_delta[index] > 0 {
969        reasons.push(SelectionReason::ChangeTrend);
970    }
971    if analysis.region_transition[index] {
972        reasons.push(SelectionReason::ChangedRegionTransition);
973    }
974    if analysis.incoming_change[index] > 0 {
975        reasons.push(SelectionReason::InformationGain);
976    }
977    if reasons.is_empty() || selected_after.iter().filter(|value| **value).count() > 1 {
978        reasons.push(SelectionReason::TemporalCoverage);
979    }
980    reasons
981}
982
983fn score_overflow() -> VisionError {
984    VisionError::new(
985        ErrorCode::ResourceLimitExceeded,
986        "storyboard selection score exceeds the supported integer representation",
987    )
988}
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use crate::{
994        DeclaredGap, Frame, IntegerScale, Marker, NormalizationParameters, PixelDimensions,
995        PixelFormat, ProcessingLimits, Rgb8, normalize_sequence,
996    };
997
998    type TestSequence = FrameSequence<u8, u8, u8, Box<[u8]>>;
999
1000    fn sequence() -> (TestSequence, NormalizedSequence<u8>) {
1001        let dimensions = PixelDimensions::new(1, 1).unwrap();
1002        let frames = [0_u8, 0, 255, 64, 255, 0]
1003            .into_iter()
1004            .enumerate()
1005            .map(|(index, value)| {
1006                Frame::new(
1007                    index as u8,
1008                    Timestamp::from_nanos(index as u64),
1009                    dimensions,
1010                    PixelFormat::Rgba8SrgbStraight,
1011                    vec![value, value, value, 255].into_boxed_slice(),
1012                )
1013                .unwrap()
1014            })
1015            .collect();
1016        let source = FrameSequence::new(
1017            frames,
1018            vec![Marker::new(1, Timestamp::from_nanos(3), "action", "marker").unwrap()],
1019            Vec::<DeclaredGap<u8>>::new(),
1020            None,
1021            None,
1022        )
1023        .unwrap();
1024        let normalized = normalize_sequence(
1025            &source,
1026            NormalizationParameters::new(
1027                Rgb8::new(0, 0, 0),
1028                None,
1029                IntegerScale::IDENTITY,
1030                ProcessingLimits::default(),
1031            ),
1032        )
1033        .unwrap();
1034        (source, normalized)
1035    }
1036
1037    #[test]
1038    fn limits_and_anchor_priority_are_deterministic() {
1039        assert_eq!(StoryboardTileLimit::default().get(), 8);
1040        assert!(StoryboardTileLimit::new(2).is_err());
1041        assert!(StoryboardTileLimit::new(13).is_err());
1042        let (source, normalized) = sequence();
1043        let selection = select_storyboard_frames(
1044            &source,
1045            &normalized,
1046            Timestamp::from_nanos(2),
1047            StoryboardTileLimit::new(3).unwrap(),
1048            MeasurementParameters::new(0),
1049        )
1050        .unwrap();
1051        assert_eq!(selection.selected_frames().len(), 3);
1052        assert_eq!(selection.before_index(), 1);
1053        assert_eq!(selection.after_index(), 5);
1054        assert!(!selection.omitted_anchors().is_empty());
1055        assert_eq!(
1056            serde_json::to_vec(&selection).unwrap(),
1057            serde_json::to_vec(&selection).unwrap()
1058        );
1059    }
1060
1061    #[test]
1062    fn reason_registry_has_stable_names() {
1063        for reason in SelectionReason::ALL {
1064            let json = serde_json::to_string(reason).unwrap();
1065            assert_eq!(
1066                serde_json::from_str::<SelectionReason>(&json).unwrap(),
1067                *reason
1068            );
1069            assert_eq!(reason.to_string(), reason.as_str());
1070        }
1071    }
1072}