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            && (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        Ok(())
351    }
352}
353
354impl<'de, F> Deserialize<'de> for StoryboardSelection<F>
355where
356    F: Deserialize<'de> + Eq,
357{
358    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
359        #[derive(Deserialize)]
360        #[serde(bound(deserialize = "F: Deserialize<'de>"), deny_unknown_fields)]
361        struct Wire<F> {
362            selected_frames: Box<[SelectedFrame<F>]>,
363            omitted_anchors: Box<[OmittedAnchor]>,
364            before_index: usize,
365            during_index: usize,
366            after_index: usize,
367            continuity_segment_count: usize,
368            visual_summary: StoryboardVisualSummary<F>,
369        }
370        let wire = Wire::deserialize(deserializer)?;
371        let selection = Self {
372            selected_frames: wire.selected_frames,
373            omitted_anchors: wire.omitted_anchors,
374            before_index: wire.before_index,
375            during_index: wire.during_index,
376            after_index: wire.after_index,
377            continuity_segment_count: wire.continuity_segment_count,
378            visual_summary: wire.visual_summary,
379        };
380        selection
381            .validate_local()
382            .map_err(serde::de::Error::custom)?;
383        Ok(selection)
384    }
385}
386
387/// Select representative source frames using the temporal-storyboard 1.1.0 rules.
388pub fn select_storyboard_frames<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
389    source: &FrameSequence<F, M, G, P>,
390    normalized: &NormalizedSequence<F>,
391    anchor: Timestamp,
392    tile_limit: StoryboardTileLimit,
393    measurement: MeasurementParameters,
394) -> Result<StoryboardSelection<F>> {
395    select_storyboard_frames_with_analysis(
396        source,
397        normalized,
398        anchor,
399        tile_limit,
400        measurement,
401        None,
402    )
403}
404
405pub fn select_storyboard_frames_with_analysis<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
406    source: &FrameSequence<F, M, G, P>,
407    normalized: &NormalizedSequence<F>,
408    anchor: Timestamp,
409    tile_limit: StoryboardTileLimit,
410    measurement: MeasurementParameters,
411    shared: Option<&crate::SharedAdjacentAnalysis<F>>,
412) -> Result<StoryboardSelection<F>> {
413    validate_alignment(source, normalized)?;
414    if !source.range().contains(anchor) {
415        return Err(VisionError::new(
416            ErrorCode::InvalidParameter,
417            "storyboard anchor must lie inside the source frame range",
418        ));
419    }
420
421    // A shared result is an optimization only. Never let a stale or differently sampled
422    // analysis authorize indexes into this consumer's plan.
423    let shared = shared.filter(|analysis| analysis.is_compatible_with(normalized, measurement));
424    let frame_count = source.frames().len();
425    let adjacent_owned;
426    let adjacent = if let Some(shared) = shared {
427        shared.comparisons()
428    } else {
429        adjacent_owned = measure_adjacent(normalized, measurement)?;
430        &adjacent_owned
431    };
432    let analysis = SelectionAnalysis::new(adjacent, source, frame_count)?;
433    let baseline = source
434        .frames()
435        .iter()
436        .rposition(|frame| frame.timestamp() < anchor)
437        .unwrap_or(0);
438    let post_anchor = source
439        .frames()
440        .iter()
441        .position(|frame| frame.timestamp() > anchor);
442    let first_change_comparison = first_change_comparison(adjacent, normalized, anchor);
443    let first_change = first_change_comparison.map(crate::FrameComparison::later_frame_index);
444    let peak_baseline_comparison =
445        peak_baseline_comparison(normalized, baseline, &analysis, measurement)?;
446    let peak = peak_baseline_comparison
447        .as_ref()
448        .map(crate::FrameComparison::later_frame_index);
449    let peak_adjacent_comparison = peak_adjacent_changed_area_comparison(adjacent);
450    let visual_summary = StoryboardVisualSummary {
451        first_change: first_change_comparison
452            .map(|comparison| visual_moment(source, comparison.clone())),
453        peak_baseline_change: peak_baseline_comparison
454            .clone()
455            .map(|comparison| visual_moment(source, comparison)),
456        peak_adjacent_changed_area: peak_adjacent_comparison
457            .map(|comparison| visual_moment(source, comparison.clone())),
458    };
459    let final_frame = frame_count - 1;
460
461    let mut selected = vec![false; frame_count];
462    let mut reasons = vec![Vec::<SelectionReason>::new(); frame_count];
463    let mut omitted = Vec::new();
464    let limit = usize::from(tile_limit.get());
465
466    // The priority makes a three-tile request preserve the orientation spine.
467    admit_anchor(
468        baseline,
469        SelectionReason::PreAnchor,
470        limit,
471        &mut selected,
472        &mut reasons,
473        &mut omitted,
474    );
475    if let Some(index) = peak {
476        admit_anchor(
477            index,
478            SelectionReason::PeakBaselineChange,
479            limit,
480            &mut selected,
481            &mut reasons,
482            &mut omitted,
483        );
484    }
485    admit_anchor(
486        final_frame,
487        SelectionReason::FinalFrame,
488        limit,
489        &mut selected,
490        &mut reasons,
491        &mut omitted,
492    );
493    if let Some(index) = first_change {
494        admit_anchor(
495            index,
496            SelectionReason::FirstChange,
497            limit,
498            &mut selected,
499            &mut reasons,
500            &mut omitted,
501        );
502    }
503    if let Some(index) = post_anchor {
504        admit_anchor(
505            index,
506            SelectionReason::PostAnchor,
507            limit,
508            &mut selected,
509            &mut reasons,
510            &mut omitted,
511        );
512    }
513
514    let mut boundary_roles = vec![Vec::<SelectionReason>::new(); frame_count];
515    for marker in source.markers() {
516        let index = source
517            .frames()
518            .iter()
519            .position(|frame| frame.timestamp() >= marker.timestamp())
520            .unwrap_or(final_frame);
521        boundary_roles[index].push(SelectionReason::MarkerBoundary);
522    }
523    for gap in source.gaps() {
524        if let Some(index) = source
525            .frames()
526            .iter()
527            .rposition(|frame| frame.timestamp() < gap.range().start())
528        {
529            boundary_roles[index].push(SelectionReason::GapBoundary);
530        }
531        if let Some(index) = source
532            .frames()
533            .iter()
534            .position(|frame| frame.timestamp() > gap.range().end())
535        {
536            boundary_roles[index].push(SelectionReason::GapBoundary);
537        }
538    }
539
540    // Supplementary anchors are admitted in source declaration order. Repeated
541    // boundaries on one source frame merge into one panel and one visible reason.
542    for (index, boundary_reasons) in boundary_roles.iter().enumerate() {
543        for reason in boundary_reasons.iter().copied() {
544            admit_anchor(
545                index,
546                reason,
547                limit,
548                &mut selected,
549                &mut reasons,
550                &mut omitted,
551            );
552        }
553    }
554
555    while selected.iter().filter(|value| **value).count() < limit
556        && selected.iter().any(|value| !*value)
557    {
558        let index = best_fill_candidate(source, &analysis, &selected, &boundary_roles)?;
559        selected[index] = true;
560        let candidate_reasons = fill_reasons(index, &analysis, &selected, &boundary_roles);
561        for reason in candidate_reasons {
562            push_unique(&mut reasons[index], reason);
563        }
564    }
565
566    let selected_frames = source
567        .frames()
568        .iter()
569        .enumerate()
570        .filter(|(index, _)| selected[*index])
571        .map(|(index, frame)| SelectedFrame {
572            frame_id: frame.id().clone(),
573            frame_index: index,
574            timestamp: frame.timestamp(),
575            reasons: std::mem::take(&mut reasons[index]).into_boxed_slice(),
576        })
577        .collect::<Vec<_>>()
578        .into_boxed_slice();
579
580    Ok(StoryboardSelection {
581        selected_frames,
582        omitted_anchors: omitted.into_boxed_slice(),
583        before_index: baseline,
584        during_index: peak.or(post_anchor).unwrap_or(baseline),
585        after_index: final_frame,
586        continuity_segment_count: analysis.segment_count,
587        visual_summary,
588    })
589}
590
591fn validate_alignment<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
592    source: &FrameSequence<F, M, G, P>,
593    normalized: &NormalizedSequence<F>,
594) -> Result<()> {
595    if source.frames().len() != normalized.frames().len()
596        || source
597            .frames()
598            .iter()
599            .zip(normalized.frames())
600            .any(|(left, right)| {
601                left.id() != right.id()
602                    || left.timestamp() != right.timestamp()
603                    || right.dimensions() != normalized.dimensions()
604            })
605    {
606        return Err(VisionError::new(
607            ErrorCode::InvalidParameter,
608            "source and normalized sequences must have aligned frame identity, time, and geometry",
609        ));
610    }
611    Ok(())
612}
613
614fn first_change_comparison<'a, F>(
615    adjacent: &'a [crate::FrameComparison],
616    normalized: &NormalizedSequence<F>,
617    anchor: Timestamp,
618) -> Option<&'a crate::FrameComparison> {
619    let changed = |comparison: &&crate::FrameComparison| {
620        matches!(
621            comparison.outcome(),
622            ComparisonOutcome::Measured(vector)
623                if vector.changed_pixel_proportion().changed() > 0
624        )
625    };
626    adjacent
627        .iter()
628        .filter(changed)
629        .find(|comparison| {
630            normalized.frames()[comparison.later_frame_index()].timestamp() >= anchor
631        })
632        .or_else(|| adjacent.iter().find(changed))
633}
634
635fn peak_baseline_comparison<F>(
636    normalized: &NormalizedSequence<F>,
637    baseline: usize,
638    analysis: &SelectionAnalysis,
639    measurement: MeasurementParameters,
640) -> Result<Option<crate::FrameComparison>> {
641    let segment = analysis.segments[baseline];
642    let mut best = None;
643    let mut best_metrics = None::<PeakMetrics>;
644    for index in (baseline + 1)..normalized.frames().len() {
645        if analysis.segments[index] != segment {
646            break;
647        }
648        let comparison = measure_pair(normalized, baseline, index, measurement)?;
649        let ComparisonOutcome::Measured(vector) = comparison.outcome() else {
650            break;
651        };
652        let metrics = PeakMetrics::from_vector(vector, index);
653        if metrics.distance == 0 && metrics.changed == 0 {
654            continue;
655        }
656        if best_metrics
657            .as_ref()
658            .is_none_or(|current| metrics > *current)
659        {
660            best = Some(comparison);
661            best_metrics = Some(metrics);
662        }
663    }
664    Ok(best)
665}
666
667fn peak_adjacent_changed_area_comparison(
668    adjacent: &[crate::FrameComparison],
669) -> Option<&crate::FrameComparison> {
670    let mut best: Option<&crate::FrameComparison> = None;
671    for comparison in adjacent {
672        let ComparisonOutcome::Measured(candidate) = comparison.outcome() else {
673            continue;
674        };
675        let candidate_area = candidate.changed_pixel_proportion();
676        if candidate_area.changed() == 0 {
677            continue;
678        }
679        let replace = best.is_none_or(|current| {
680            let ComparisonOutcome::Measured(current) = current.outcome() else {
681                unreachable!("only measured comparisons become changed-area candidates")
682            };
683            let current_area = current.changed_pixel_proportion();
684            u128::from(candidate_area.changed()) * u128::from(current_area.compared())
685                > u128::from(current_area.changed()) * u128::from(candidate_area.compared())
686        });
687        // Equality deliberately keeps the earliest source comparison.
688        if replace {
689            best = Some(comparison);
690        }
691    }
692    best
693}
694
695fn visual_moment<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
696    source: &FrameSequence<F, M, G, P>,
697    comparison: crate::FrameComparison,
698) -> VisualChangeMoment<F> {
699    let frame_index = comparison.later_frame_index();
700    let frame = &source.frames()[frame_index];
701    VisualChangeMoment {
702        frame_id: frame.id().clone(),
703        frame_index,
704        timestamp: frame.timestamp(),
705        comparison,
706    }
707}
708
709#[derive(Clone, Copy, Debug, Eq, PartialEq)]
710struct PeakMetrics {
711    distance: u16,
712    changed: u64,
713    compared: u64,
714    absolute: u64,
715    reverse_index: usize,
716}
717
718impl PeakMetrics {
719    fn from_vector(vector: &MeasurementVector, index: usize) -> Self {
720        let proportion = vector.changed_pixel_proportion();
721        Self {
722            distance: vector.perceptual_frame_distance(),
723            changed: proportion.changed(),
724            compared: proportion.compared(),
725            absolute: vector.absolute_pixel_difference(),
726            reverse_index: usize::MAX - index,
727        }
728    }
729}
730
731impl Ord for PeakMetrics {
732    fn cmp(&self, other: &Self) -> Ordering {
733        self.distance
734            .cmp(&other.distance)
735            .then(self.changed.cmp(&other.changed))
736            .then_with(|| {
737                (u128::from(self.changed) * u128::from(other.compared))
738                    .cmp(&(u128::from(other.changed) * u128::from(self.compared)))
739            })
740            .then(self.absolute.cmp(&other.absolute))
741            .then(self.reverse_index.cmp(&other.reverse_index))
742    }
743}
744
745impl PartialOrd for PeakMetrics {
746    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
747        Some(self.cmp(other))
748    }
749}
750
751fn admit_anchor(
752    index: usize,
753    reason: SelectionReason,
754    limit: usize,
755    selected: &mut [bool],
756    reasons: &mut [Vec<SelectionReason>],
757    omitted: &mut Vec<OmittedAnchor>,
758) {
759    if selected[index] {
760        push_unique(&mut reasons[index], reason);
761    } else if selected.iter().filter(|value| **value).count() < limit {
762        selected[index] = true;
763        reasons[index].push(reason);
764    } else {
765        omitted.push(OmittedAnchor {
766            frame_index: index,
767            reason,
768        });
769    }
770}
771
772fn push_unique(reasons: &mut Vec<SelectionReason>, reason: SelectionReason) {
773    if !reasons.contains(&reason) {
774        reasons.push(reason);
775    }
776}
777
778#[derive(Debug)]
779struct SelectionAnalysis {
780    segments: Vec<usize>,
781    cumulative_change: Vec<u64>,
782    incoming_change: Vec<u16>,
783    local_peak: Vec<u16>,
784    trend_delta: Vec<u16>,
785    region_transition: Vec<bool>,
786    segment_count: usize,
787}
788
789impl SelectionAnalysis {
790    fn new<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
791        adjacent: &[crate::FrameComparison],
792        _source: &FrameSequence<F, M, G, P>,
793        frame_count: usize,
794    ) -> Result<Self> {
795        let mut segments = vec![0; frame_count];
796        let mut cumulative_change = vec![0_u64; frame_count];
797        let mut incoming_change = vec![0_u16; frame_count];
798        let mut changed_region = vec![false; frame_count];
799        let mut segment = 0_usize;
800        for comparison in adjacent {
801            let later = comparison.later_frame_index();
802            match comparison.outcome() {
803                ComparisonOutcome::GapBoundary { .. } => {
804                    segment = segment.checked_add(1).ok_or_else(score_overflow)?;
805                    segments[later] = segment;
806                    cumulative_change[later] = 0;
807                }
808                ComparisonOutcome::Measured(vector) => {
809                    segments[later] = segment;
810                    incoming_change[later] = vector.perceptual_frame_distance();
811                    changed_region[later] = vector.changed_region_bounds().is_some();
812                    cumulative_change[later] = cumulative_change[later - 1]
813                        .checked_add(u64::from(vector.perceptual_frame_distance()))
814                        .ok_or_else(score_overflow)?;
815                }
816            }
817        }
818        let mut local_peak = vec![0; frame_count];
819        let mut trend_delta = vec![0; frame_count];
820        let mut region_transition = vec![false; frame_count];
821        for index in 1..frame_count {
822            if segments[index] != segments[index - 1] {
823                continue;
824            }
825            let current = incoming_change[index];
826            let previous = if index > 1 && segments[index - 1] == segments[index - 2] {
827                incoming_change[index - 1]
828            } else {
829                0
830            };
831            let next = if index + 1 < frame_count && segments[index + 1] == segments[index] {
832                incoming_change[index + 1]
833            } else {
834                0
835            };
836            if current >= previous && current > next {
837                local_peak[index] = current;
838            }
839            trend_delta[index] = current.abs_diff(previous).max(current.abs_diff(next));
840            region_transition[index] = changed_region[index] != changed_region[index - 1];
841        }
842        Ok(Self {
843            segments,
844            cumulative_change,
845            incoming_change,
846            local_peak,
847            trend_delta,
848            region_transition,
849            segment_count: segment + 1,
850        })
851    }
852}
853
854#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
855struct FillScore {
856    unrepresented_segment: bool,
857    supplementary_roles: usize,
858    information_gain: u64,
859    local_peak: u16,
860    trend_delta: u16,
861    region_transition: bool,
862    temporal_coverage: u64,
863    reverse_index: usize,
864}
865
866fn best_fill_candidate<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
867    source: &FrameSequence<F, M, G, P>,
868    analysis: &SelectionAnalysis,
869    selected: &[bool],
870    boundary_roles: &[Vec<SelectionReason>],
871) -> Result<usize> {
872    let represented = selected
873        .iter()
874        .enumerate()
875        .filter(|(_, value)| **value)
876        .map(|(index, _)| analysis.segments[index])
877        .collect::<Vec<_>>();
878    (0..selected.len())
879        .filter(|index| !selected[*index])
880        .map(|index| {
881            score_candidate(
882                source,
883                analysis,
884                selected,
885                boundary_roles,
886                &represented,
887                index,
888            )
889            .map(|score| (score, index))
890        })
891        .collect::<Result<Vec<_>>>()?
892        .into_iter()
893        .max_by_key(|(score, _)| *score)
894        .map(|(_, index)| index)
895        .ok_or_else(score_overflow)
896}
897
898fn score_candidate<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
899    source: &FrameSequence<F, M, G, P>,
900    analysis: &SelectionAnalysis,
901    selected: &[bool],
902    boundary_roles: &[Vec<SelectionReason>],
903    represented: &[usize],
904    index: usize,
905) -> Result<FillScore> {
906    Ok(FillScore {
907        unrepresented_segment: !represented.contains(&analysis.segments[index]),
908        supplementary_roles: boundary_roles[index].len(),
909        information_gain: nearest_selected_distance(index, selected, |left, right| {
910            if analysis.segments[left] != analysis.segments[right] {
911                None
912            } else {
913                Some(analysis.cumulative_change[left].abs_diff(analysis.cumulative_change[right]))
914            }
915        }),
916        local_peak: analysis.local_peak[index],
917        trend_delta: analysis.trend_delta[index],
918        region_transition: analysis.region_transition[index],
919        temporal_coverage: nearest_selected_distance(index, selected, |left, right| {
920            Some(
921                source.frames()[left]
922                    .timestamp()
923                    .as_nanos()
924                    .abs_diff(source.frames()[right].timestamp().as_nanos()),
925            )
926        }),
927        reverse_index: usize::MAX - index,
928    })
929}
930
931fn nearest_selected_distance(
932    index: usize,
933    selected: &[bool],
934    distance: impl Fn(usize, usize) -> Option<u64>,
935) -> u64 {
936    let predecessor = (0..index)
937        .rev()
938        .find(|candidate| selected[*candidate] && distance(index, *candidate).is_some());
939    let successor = ((index + 1)..selected.len())
940        .find(|candidate| selected[*candidate] && distance(index, *candidate).is_some());
941    match (predecessor, successor) {
942        (Some(left), Some(right)) => distance(index, left)
943            .expect("filtered")
944            .min(distance(index, right).expect("filtered")),
945        (Some(left), None) => distance(index, left).expect("filtered"),
946        (None, Some(right)) => distance(index, right).expect("filtered"),
947        (None, None) => 0,
948    }
949}
950
951fn fill_reasons(
952    index: usize,
953    analysis: &SelectionAnalysis,
954    selected_after: &[bool],
955    boundary_roles: &[Vec<SelectionReason>],
956) -> Vec<SelectionReason> {
957    let mut reasons = boundary_roles[index].clone();
958    reasons.sort_by_key(|reason| {
959        SelectionReason::ALL
960            .iter()
961            .position(|value| value == reason)
962    });
963    reasons.dedup();
964    if analysis.local_peak[index] > 0 {
965        reasons.push(SelectionReason::LocalChangePeak);
966    }
967    if analysis.trend_delta[index] > 0 {
968        reasons.push(SelectionReason::ChangeTrend);
969    }
970    if analysis.region_transition[index] {
971        reasons.push(SelectionReason::ChangedRegionTransition);
972    }
973    if analysis.incoming_change[index] > 0 {
974        reasons.push(SelectionReason::InformationGain);
975    }
976    if reasons.is_empty() || selected_after.iter().filter(|value| **value).count() > 1 {
977        reasons.push(SelectionReason::TemporalCoverage);
978    }
979    reasons
980}
981
982fn score_overflow() -> VisionError {
983    VisionError::new(
984        ErrorCode::ResourceLimitExceeded,
985        "storyboard selection score exceeds the supported integer representation",
986    )
987}
988
989#[cfg(test)]
990mod tests {
991    use super::*;
992    use crate::{
993        DeclaredGap, Frame, IntegerScale, Marker, NormalizationParameters, PixelDimensions,
994        PixelFormat, ProcessingLimits, Rgb8, normalize_sequence,
995    };
996
997    type TestSequence = FrameSequence<u8, u8, u8, Box<[u8]>>;
998
999    fn sequence() -> (TestSequence, NormalizedSequence<u8>) {
1000        let dimensions = PixelDimensions::new(1, 1).unwrap();
1001        let frames = [0_u8, 0, 255, 64, 255, 0]
1002            .into_iter()
1003            .enumerate()
1004            .map(|(index, value)| {
1005                Frame::new(
1006                    index as u8,
1007                    Timestamp::from_nanos(index as u64),
1008                    dimensions,
1009                    PixelFormat::Rgba8SrgbStraight,
1010                    vec![value, value, value, 255].into_boxed_slice(),
1011                )
1012                .unwrap()
1013            })
1014            .collect();
1015        let source = FrameSequence::new(
1016            frames,
1017            vec![Marker::new(1, Timestamp::from_nanos(3), "action", "marker").unwrap()],
1018            Vec::<DeclaredGap<u8>>::new(),
1019            None,
1020            None,
1021        )
1022        .unwrap();
1023        let normalized = normalize_sequence(
1024            &source,
1025            NormalizationParameters::new(
1026                Rgb8::new(0, 0, 0),
1027                None,
1028                IntegerScale::IDENTITY,
1029                ProcessingLimits::default(),
1030            ),
1031        )
1032        .unwrap();
1033        (source, normalized)
1034    }
1035
1036    #[test]
1037    fn limits_and_anchor_priority_are_deterministic() {
1038        assert_eq!(StoryboardTileLimit::default().get(), 8);
1039        assert!(StoryboardTileLimit::new(2).is_err());
1040        assert!(StoryboardTileLimit::new(13).is_err());
1041        let (source, normalized) = sequence();
1042        let selection = select_storyboard_frames(
1043            &source,
1044            &normalized,
1045            Timestamp::from_nanos(2),
1046            StoryboardTileLimit::new(3).unwrap(),
1047            MeasurementParameters::new(0),
1048        )
1049        .unwrap();
1050        assert_eq!(selection.selected_frames().len(), 3);
1051        assert_eq!(selection.before_index(), 1);
1052        assert_eq!(selection.after_index(), 5);
1053        assert!(!selection.omitted_anchors().is_empty());
1054        assert_eq!(
1055            serde_json::to_vec(&selection).unwrap(),
1056            serde_json::to_vec(&selection).unwrap()
1057        );
1058    }
1059
1060    #[test]
1061    fn reason_registry_has_stable_names() {
1062        for reason in SelectionReason::ALL {
1063            let json = serde_json::to_string(reason).unwrap();
1064            assert_eq!(
1065                serde_json::from_str::<SelectionReason>(&json).unwrap(),
1066                *reason
1067            );
1068            assert_eq!(reason.to_string(), reason.as_str());
1069        }
1070    }
1071}