Skip to main content

temporal_vision/
motion_history.rs

1use std::{collections::BTreeMap, fmt::Display, num::NonZeroU8};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{
6    AlgorithmDescriptor, ArtifactKind, ArtifactManifest, BinaryMask, ComparisonOutcome,
7    EncodedImage, ErrorCode, EvidenceClass, FrameSequence, GeneratedArtifact,
8    MeasurementParameters, NormalizationKind, NormalizationStep, NormalizedSequence,
9    ParameterValue, Parameters, PixelDimensions, Result, Rgb8, SharedAdjacentAnalysis, TimeRange,
10    Timestamp, VisionError, generator_descriptor,
11    measure::{PixelClassifier, linear_luminance, pair_pixels},
12    measure_adjacent,
13    provenance::analysis_sampling_parameters,
14    render::{
15        ArtifactLabels, RenderLimits,
16        canvas::{BLACK, Canvas, MUTED, PANEL, WARNING, WHITE, canvas_limit_error},
17        font::{CELL_WIDTH, draw_text, untruncated},
18    },
19};
20
21/// One deterministic integer exponential-decay curve over pair recency rank.
22#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
23pub struct MotionDecay {
24    peak_intensity: u16,
25    half_life_ranks: NonZeroU8,
26}
27
28impl MotionDecay {
29    pub const DEFAULT_PEAK_INTENSITY: u16 = u16::MAX;
30    pub const DEFAULT_HALF_LIFE_RANKS: u8 = 1;
31    pub const DEFAULT: Self = Self {
32        peak_intensity: Self::DEFAULT_PEAK_INTENSITY,
33        half_life_ranks: NonZeroU8::MIN,
34    };
35
36    pub const fn new(peak_intensity: u16, half_life_ranks: NonZeroU8) -> Self {
37        Self {
38            peak_intensity,
39            half_life_ranks,
40        }
41    }
42
43    pub const fn peak_intensity(self) -> u16 {
44        self.peak_intensity
45    }
46
47    pub const fn half_life_ranks(self) -> NonZeroU8 {
48        self.half_life_ranks
49    }
50
51    /// Weight for a pair where rank zero is the newest pair in its continuity segment.
52    pub const fn weight_at(self, rank_from_newest: u32) -> u16 {
53        let shift = rank_from_newest / self.half_life_ranks.get() as u32;
54        if shift >= u16::BITS {
55            0
56        } else {
57            self.peak_intensity >> shift
58        }
59    }
60
61    /// Number of recency ranks that can contribute a nonzero weight.
62    pub const fn live_window(self) -> u32 {
63        u16::BITS * self.half_life_ranks.get() as u32
64    }
65}
66
67impl Default for MotionDecay {
68    fn default() -> Self {
69        Self::DEFAULT
70    }
71}
72
73/// Fixed source-derived choices for one motion-history artifact.
74#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct MotionHistoryParameters {
76    reference_frame_index: usize,
77    measurement: MeasurementParameters,
78    decay: MotionDecay,
79    reference_strength: u8,
80    accent_color: Rgb8,
81    outline_color: Rgb8,
82    labels: ArtifactLabels,
83    limits: RenderLimits,
84}
85
86impl MotionHistoryParameters {
87    #[allow(clippy::too_many_arguments)]
88    pub fn new(
89        reference_frame_index: usize,
90        measurement: MeasurementParameters,
91        decay: MotionDecay,
92        reference_strength: u8,
93        accent_color: Rgb8,
94        outline_color: Rgb8,
95        labels: ArtifactLabels,
96        limits: RenderLimits,
97    ) -> Self {
98        Self {
99            reference_frame_index,
100            measurement,
101            decay,
102            reference_strength,
103            accent_color,
104            outline_color,
105            labels,
106            limits,
107        }
108    }
109
110    pub const fn reference_frame_index(&self) -> usize {
111        self.reference_frame_index
112    }
113
114    pub const fn measurement(&self) -> MeasurementParameters {
115        self.measurement
116    }
117
118    pub const fn decay(&self) -> MotionDecay {
119        self.decay
120    }
121
122    pub const fn reference_strength(&self) -> u8 {
123        self.reference_strength
124    }
125
126    pub const fn accent_color(&self) -> Rgb8 {
127        self.accent_color
128    }
129
130    pub const fn outline_color(&self) -> Rgb8 {
131        self.outline_color
132    }
133
134    pub const fn labels(&self) -> &ArtifactLabels {
135        &self.labels
136    }
137
138    pub const fn limits(&self) -> RenderLimits {
139        self.limits
140    }
141}
142
143/// Render-independent result of deterministic gap-aware motion accumulation.
144#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
145pub struct MotionHistoryPlan<FrameId> {
146    accumulation: Box<[u16]>,
147    ever_changed: BinaryMask,
148    outline: BinaryMask,
149    dimensions: PixelDimensions,
150    reference_frame_index: usize,
151    reference_frame_id: FrameId,
152    continuity_segment_count: usize,
153    live_window: u32,
154    measured_pair_count: usize,
155    gap_pair_count: usize,
156    changed_pixel_count: u64,
157    max_segment_rank: u32,
158    range: TimeRange,
159}
160
161impl<F> MotionHistoryPlan<F> {
162    pub fn accumulation(&self) -> &[u16] {
163        &self.accumulation
164    }
165
166    pub const fn ever_changed(&self) -> &BinaryMask {
167        &self.ever_changed
168    }
169
170    pub const fn outline(&self) -> &BinaryMask {
171        &self.outline
172    }
173
174    pub const fn dimensions(&self) -> PixelDimensions {
175        self.dimensions
176    }
177
178    pub const fn reference_frame_index(&self) -> usize {
179        self.reference_frame_index
180    }
181
182    pub const fn reference_frame_id(&self) -> &F {
183        &self.reference_frame_id
184    }
185
186    pub const fn continuity_segment_count(&self) -> usize {
187        self.continuity_segment_count
188    }
189
190    pub const fn live_window(&self) -> u32 {
191        self.live_window
192    }
193
194    pub const fn measured_pair_count(&self) -> usize {
195        self.measured_pair_count
196    }
197
198    pub const fn gap_pair_count(&self) -> usize {
199        self.gap_pair_count
200    }
201
202    pub const fn changed_pixel_count(&self) -> u64 {
203        self.changed_pixel_count
204    }
205
206    pub const fn max_segment_rank(&self) -> u32 {
207        self.max_segment_rank
208    }
209
210    pub const fn range(&self) -> TimeRange {
211        self.range
212    }
213}
214
215/// Build a bounded motion-history plan without rendering or encoding an image.
216pub fn build_motion_history_plan<F, M, G, P>(
217    source: &FrameSequence<F, M, G, P>,
218    normalized: &NormalizedSequence<F>,
219    parameters: &MotionHistoryParameters,
220) -> Result<MotionHistoryPlan<F>>
221where
222    F: Clone + Eq,
223    M: Eq,
224    G: Eq,
225    P: AsRef<[u8]>,
226{
227    build_motion_history_plan_with_analysis(source, normalized, parameters, None)
228}
229
230pub fn build_motion_history_plan_with_analysis<F, M, G, P>(
231    source: &FrameSequence<F, M, G, P>,
232    normalized: &NormalizedSequence<F>,
233    parameters: &MotionHistoryParameters,
234    shared: Option<&SharedAdjacentAnalysis<F>>,
235) -> Result<MotionHistoryPlan<F>>
236where
237    F: Clone + Eq,
238    M: Eq,
239    G: Eq,
240    P: AsRef<[u8]>,
241{
242    validate_source_alignment(source, normalized, parameters.reference_frame_index)?;
243    let dimensions = normalized.dimensions();
244    let pixel_count = dimensions.pixel_count()?;
245    ensure_plan_memory_fits(pixel_count, parameters.limits)?;
246
247    // A shared result is an optimization only. A mismatched sampled plan or threshold
248    // must use the local measurement path so it cannot shorten or misaddress this plan.
249    let shared =
250        shared.filter(|analysis| analysis.is_compatible_with(normalized, parameters.measurement));
251    let comparisons_owned;
252    let comparisons = if let Some(shared) = shared {
253        shared.comparisons()
254    } else {
255        comparisons_owned = measure_adjacent(normalized, parameters.measurement)?;
256        &comparisons_owned
257    };
258    let measured_pair_count = comparisons
259        .iter()
260        .filter(|comparison| matches!(comparison.outcome(), ComparisonOutcome::Measured(_)))
261        .count();
262    let gap_pair_count = comparisons.len() - measured_pair_count;
263    let mut accumulation = vec![0_u16; pixel_count];
264    let mut segment_accumulation = vec![0_u16; pixel_count];
265    let mask_byte_len = pixel_count.checked_add(7).ok_or_else(motion_limit_error)? / 8;
266    let mut ever_changed_bits = vec![0_u8; mask_byte_len];
267    let mut continuity_segment_count = 0_usize;
268    let mut max_segment_rank = 0_u32;
269    let mut segment_start = None;
270    for (comparison_index, comparison) in comparisons.iter().enumerate() {
271        match comparison.outcome() {
272            ComparisonOutcome::Measured(_) => {
273                segment_start.get_or_insert(comparison_index);
274            }
275            ComparisonOutcome::GapBoundary { .. } => {
276                if let Some(start) = segment_start.take() {
277                    accumulate_segment(
278                        &comparisons[start..comparison_index],
279                        start,
280                        normalized,
281                        parameters,
282                        shared,
283                        &mut segment_accumulation,
284                        &mut accumulation,
285                        &mut ever_changed_bits,
286                    )?;
287                    continuity_segment_count = continuity_segment_count
288                        .checked_add(1)
289                        .ok_or_else(motion_limit_error)?;
290                    max_segment_rank =
291                        max_segment_rank.max(segment_rank(comparison_index - start)?);
292                }
293            }
294        }
295    }
296    if let Some(start) = segment_start {
297        accumulate_segment(
298            &comparisons[start..],
299            start,
300            normalized,
301            parameters,
302            shared,
303            &mut segment_accumulation,
304            &mut accumulation,
305            &mut ever_changed_bits,
306        )?;
307        continuity_segment_count = continuity_segment_count
308            .checked_add(1)
309            .ok_or_else(motion_limit_error)?;
310        max_segment_rank = max_segment_rank.max(segment_rank(comparisons.len() - start)?);
311    }
312
313    let changed_pixel_count = ever_changed_bits
314        .iter()
315        .map(|byte| u64::from(byte.count_ones()))
316        .sum();
317    let outline_bits = build_outline(&ever_changed_bits, dimensions)?;
318    let ever_changed = BinaryMask::new(dimensions, ever_changed_bits)?;
319    let outline = BinaryMask::new(dimensions, outline_bits)?;
320
321    Ok(MotionHistoryPlan {
322        accumulation: accumulation.into_boxed_slice(),
323        ever_changed,
324        outline,
325        dimensions,
326        reference_frame_index: parameters.reference_frame_index,
327        reference_frame_id: normalized.frames()[parameters.reference_frame_index]
328            .id()
329            .clone(),
330        continuity_segment_count,
331        live_window: parameters.decay.live_window(),
332        measured_pair_count,
333        gap_pair_count,
334        changed_pixel_count,
335        max_segment_rank,
336        range: source.range(),
337    })
338}
339
340fn validate_source_alignment<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
341    source: &FrameSequence<F, M, G, P>,
342    normalized: &NormalizedSequence<F>,
343    reference_frame_index: usize,
344) -> Result<()> {
345    let aligned_frames = source.frames().len() == normalized.frames().len()
346        && source.dimensions() == normalized.source_dimensions()
347        && source.frames().iter().zip(normalized.frames()).all(
348            |(source_frame, normalized_frame)| {
349                source_frame.id() == normalized_frame.id()
350                    && source_frame.timestamp() == normalized_frame.timestamp()
351                    && normalized_frame.dimensions() == normalized.dimensions()
352            },
353        );
354    let aligned_gaps = source.gaps().len() == normalized.gap_ranges().len()
355        && source
356            .gaps()
357            .iter()
358            .map(|gap| gap.range())
359            .eq(normalized.gap_ranges().iter().copied());
360    if !aligned_frames || !aligned_gaps || reference_frame_index >= normalized.frames().len() {
361        return Err(VisionError::new(
362            ErrorCode::InvalidParameter,
363            "normalized frames, gaps, or reference index do not match the source sequence",
364        ));
365    }
366    Ok(())
367}
368
369fn ensure_plan_memory_fits(pixel_count: usize, limits: RenderLimits) -> Result<()> {
370    if plan_working_bytes(pixel_count)? > limits.max_canvas_bytes() {
371        return Err(motion_limit_error());
372    }
373    Ok(())
374}
375
376fn plan_working_bytes(pixel_count: usize) -> Result<usize> {
377    let mask_bytes = pixel_count
378        .checked_add(7)
379        .and_then(|value| value.checked_div(8))
380        .ok_or_else(motion_limit_error)?;
381    pixel_count
382        .checked_mul(std::mem::size_of::<u16>())
383        .and_then(|value| value.checked_mul(2))
384        .and_then(|value| value.checked_add(mask_bytes.checked_mul(2)?))
385        .ok_or_else(motion_limit_error)
386}
387
388#[allow(clippy::too_many_arguments)]
389fn accumulate_segment<F>(
390    comparisons: &[crate::FrameComparison],
391    comparison_start: usize,
392    normalized: &NormalizedSequence<F>,
393    parameters: &MotionHistoryParameters,
394    shared: Option<&SharedAdjacentAnalysis<F>>,
395    segment_accumulation: &mut [u16],
396    accumulation: &mut [u16],
397    ever_changed_bits: &mut [u8],
398) -> Result<()> {
399    segment_accumulation.fill(0);
400    let pairs = comparisons
401        .iter()
402        .map(|comparison| {
403            debug_assert!(matches!(
404                comparison.outcome(),
405                ComparisonOutcome::Measured(_)
406            ));
407            pair_pixels(
408                normalized,
409                comparison.earlier_frame_index(),
410                comparison.later_frame_index(),
411            )
412        })
413        .collect::<Result<Vec<_>>>()?;
414    let dimensions = normalized.dimensions();
415    let width = usize::try_from(dimensions.width()).map_err(|_| motion_limit_error())?;
416    let pixel_count = dimensions.pixel_count()?;
417    let mask = normalized.analysis_mask();
418    let classifier =
419        PixelClassifier::new(parameters.measurement).map_err(|_| motion_limit_error())?;
420    let shared_change_masks = shared.map(|analysis| {
421        comparisons
422            .iter()
423            .enumerate()
424            .map(|(offset, _)| analysis.change_mask_for_pair(comparison_start + offset))
425            .collect::<Vec<_>>()
426    });
427    let (local_accumulation, local_ever_changed) = crate::parallel::map_reduce(
428        pairs.len(),
429        || {
430            (
431                vec![0_u16; pixel_count],
432                vec![0_u8; ever_changed_bits.len()],
433            )
434        },
435        |(local_accumulation, local_ever_changed), offset| {
436            let rank = match u32::try_from(pairs.len() - 1 - offset) {
437                Ok(rank) => rank,
438                Err(_) => return,
439            };
440            let weight = parameters.decay.weight_at(rank);
441            let pair = &pairs[offset];
442            for y in 0..dimensions.height() {
443                let row = match usize::try_from(y)
444                    .ok()
445                    .and_then(|row| row.checked_mul(width))
446                {
447                    Some(row) => row,
448                    None => return,
449                };
450                let byte_row = match row.checked_mul(3) {
451                    Some(row) => row,
452                    None => return,
453                };
454                let end = match byte_row.checked_add(width * 3) {
455                    Some(end) => end,
456                    None => return,
457                };
458                let mut mask_cursor = mask.map(|mask| {
459                    let (bits, bit_offset) = mask
460                        .row_bits(y)
461                        .expect("mask dimensions match normalized frames");
462                    (bits, 0_usize, 0x80_u8 >> bit_offset)
463                });
464                let change_start = usize::try_from(y)
465                    .ok()
466                    .and_then(|row| row.checked_mul(width))
467                    .expect("normalized dimensions fit the change-mask index space");
468                let mut change_cursor = shared_change_masks
469                    .as_ref()
470                    .and_then(|masks| masks[offset])
471                    .map(|bits| (bits, change_start / 8, 0x80_u8 >> (change_start % 8)));
472                for (x, (before, after)) in pair.earlier[byte_row..end]
473                    .chunks_exact(3)
474                    .zip(pair.later[byte_row..end].chunks_exact(3))
475                    .enumerate()
476                {
477                    let changed_by_mask = if let Some((bits, byte, bit)) = change_cursor.as_mut() {
478                        let changed = bits[*byte] & *bit != 0;
479                        *bit >>= 1;
480                        if *bit == 0 {
481                            *bit = 0x80;
482                            *byte += 1;
483                        }
484                        Some(changed)
485                    } else {
486                        None
487                    };
488                    let included = if let Some((bits, byte, bit)) = mask_cursor.as_mut() {
489                        let included = bits[*byte] & *bit != 0;
490                        *bit >>= 1;
491                        if *bit == 0 {
492                            *bit = 0x80;
493                            *byte += 1;
494                        }
495                        included
496                    } else {
497                        true
498                    };
499                    if !included {
500                        continue;
501                    }
502                    let before: &[u16; 3] = before
503                        .try_into()
504                        .expect("chunks_exact yields three-channel pixels");
505                    let after: &[u16; 3] = after
506                        .try_into()
507                        .expect("chunks_exact yields three-channel pixels");
508                    match changed_by_mask {
509                        Some(false) => continue,
510                        Some(true) => {}
511                        None if !classifier.classify(before, after).changed => continue,
512                        None => {}
513                    }
514                    let pixel = row + x;
515                    set_bit(local_ever_changed, pixel);
516                    if weight != 0 {
517                        local_accumulation[pixel] =
518                            local_accumulation[pixel].saturating_add(weight);
519                    }
520                }
521            }
522        },
523        |(mut left_accumulation, mut left_changed), (right_accumulation, right_changed)| {
524            for (left, right) in left_accumulation.iter_mut().zip(right_accumulation) {
525                *left = left.saturating_add(right);
526            }
527            for (left, right) in left_changed.iter_mut().zip(right_changed) {
528                *left |= right;
529            }
530            (left_accumulation, left_changed)
531        },
532    );
533    segment_accumulation.copy_from_slice(&local_accumulation);
534    for (target, local) in ever_changed_bits.iter_mut().zip(local_ever_changed) {
535        *target |= local;
536    }
537    for (composite, segment) in accumulation.iter_mut().zip(segment_accumulation.iter()) {
538        *composite = (*composite).max(*segment);
539    }
540    Ok(())
541}
542
543fn segment_rank(pair_count: usize) -> Result<u32> {
544    u32::try_from(pair_count.saturating_sub(1)).map_err(|_| motion_limit_error())
545}
546
547fn build_outline(ever_changed: &[u8], dimensions: PixelDimensions) -> Result<Vec<u8>> {
548    let pixel_count = dimensions.pixel_count()?;
549    let mut outline = vec![0_u8; ever_changed.len()];
550    let width = usize::try_from(dimensions.width()).map_err(|_| motion_limit_error())?;
551    let height = usize::try_from(dimensions.height()).map_err(|_| motion_limit_error())?;
552    for pixel in 0..pixel_count {
553        if !bit_is_set(ever_changed, pixel) {
554            continue;
555        }
556        let x = pixel % width;
557        let y = pixel / width;
558        let boundary = x == 0
559            || y == 0
560            || x + 1 == width
561            || y + 1 == height
562            || !bit_is_set(ever_changed, pixel - 1)
563            || !bit_is_set(ever_changed, pixel + 1)
564            || !bit_is_set(ever_changed, pixel - width)
565            || !bit_is_set(ever_changed, pixel + width);
566        if boundary {
567            set_bit(&mut outline, pixel);
568        }
569    }
570    Ok(outline)
571}
572
573fn bit_is_set(bits: &[u8], index: usize) -> bool {
574    bits[index / 8] & (0x80 >> (index % 8)) != 0
575}
576
577fn set_bit(bits: &mut [u8], index: usize) {
578    bits[index / 8] |= 0x80 >> (index % 8);
579}
580
581const HEADER_HEIGHT: u32 = 38;
582const FOOTER_HEIGHT: u32 = 94;
583const LEGEND_X: u32 = 4;
584const LEGEND_Y_OFFSET: u32 = 30;
585const LEGEND_HEIGHT: u32 = 8;
586const PNG_PROFILE: &str = "png-0.17.16-rgb8-best-no_filter-no_chunks";
587
588/// Encoded motion-history evidence and its machine-readable provenance.
589pub type MotionHistoryArtifact<ArtifactId, FrameId, MarkerId, GapId> =
590    GeneratedArtifact<ArtifactId, FrameId, MarkerId, GapId>;
591
592#[derive(Clone, Copy, Debug, Eq, PartialEq)]
593struct MotionHistoryLayout {
594    dimensions: PixelDimensions,
595    main_y: u32,
596    footer_y: u32,
597}
598
599impl MotionHistoryLayout {
600    fn new(source: PixelDimensions, limits: RenderLimits) -> Result<Self> {
601        let height = HEADER_HEIGHT
602            .checked_add(source.height())
603            .and_then(|value| value.checked_add(FOOTER_HEIGHT))
604            .ok_or_else(canvas_limit_error)?;
605        if source.width() > limits.max_width() || height > limits.max_height() {
606            return Err(canvas_limit_error());
607        }
608        let dimensions =
609            PixelDimensions::new(source.width(), height).map_err(|_| canvas_limit_error())?;
610        let canvas_bytes = dimensions
611            .pixel_count()?
612            .checked_mul(3)
613            .ok_or_else(canvas_limit_error)?;
614        let total_working_bytes = plan_working_bytes(source.pixel_count()?)?
615            .checked_add(canvas_bytes)
616            .ok_or_else(canvas_limit_error)?;
617        if total_working_bytes > limits.max_canvas_bytes() {
618            return Err(canvas_limit_error());
619        }
620        Ok(Self {
621            dimensions,
622            main_y: HEADER_HEIGHT,
623            footer_y: HEADER_HEIGHT + source.height(),
624        })
625    }
626}
627
628/// Render and encode one deterministic, bounded, source-derived motion-history image.
629pub fn generate_motion_history<A, F, M, G, P>(
630    artifact_id: A,
631    source: &FrameSequence<F, M, G, P>,
632    normalized: &NormalizedSequence<F>,
633    parameters: MotionHistoryParameters,
634) -> Result<MotionHistoryArtifact<A, F, M, G>>
635where
636    F: Clone + Eq + Display,
637    M: Clone + Eq,
638    G: Clone + Eq,
639    P: AsRef<[u8]>,
640{
641    generate_motion_history_with_analysis(artifact_id, source, normalized, parameters, None)
642}
643
644pub fn generate_motion_history_with_analysis<A, F, M, G, P>(
645    artifact_id: A,
646    source: &FrameSequence<F, M, G, P>,
647    normalized: &NormalizedSequence<F>,
648    parameters: MotionHistoryParameters,
649    shared: Option<&SharedAdjacentAnalysis<F>>,
650) -> Result<MotionHistoryArtifact<A, F, M, G>>
651where
652    F: Clone + Eq + Display,
653    M: Clone + Eq,
654    G: Clone + Eq,
655    P: AsRef<[u8]>,
656{
657    validate_source_alignment(source, normalized, parameters.reference_frame_index)?;
658    let layout = MotionHistoryLayout::new(normalized.dimensions(), parameters.limits)?;
659    let plan = build_motion_history_plan_with_analysis(source, normalized, &parameters, shared)?;
660    let mut canvas = Canvas::new(
661        layout.dimensions,
662        BLACK,
663        parameters.limits.max_canvas_bytes(),
664    )?;
665    draw_motion_history(&mut canvas, layout, source, normalized, &plan, &parameters)?;
666    let (bytes, hash) = crate::encode::encode_png(
667        layout.dimensions,
668        canvas.pixels(),
669        parameters.limits.max_encoded_bytes(),
670    )?;
671
672    let mut normalization = normalized.normalization_steps().to_vec();
673    normalization.push(parameters.measurement.provenance_step()?);
674    normalization.push(display_step()?);
675    let manifest = ArtifactManifest::from_sequence(
676        artifact_id,
677        ArtifactKind::MotionHistory,
678        EvidenceClass::SourceDerived,
679        {
680            let descriptor = generator_descriptor(ArtifactKind::MotionHistory);
681            AlgorithmDescriptor::new(descriptor.name, descriptor.version)?
682        },
683        source,
684        vec![plan.reference_frame_id().clone()],
685        normalization,
686        manifest_parameters(source, &plan, &parameters)?,
687        layout.dimensions,
688        hash,
689    )?;
690    Ok(GeneratedArtifact::new(
691        EncodedImage::new(layout.dimensions, bytes),
692        manifest,
693    ))
694}
695
696fn draw_motion_history<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
697    canvas: &mut Canvas,
698    layout: MotionHistoryLayout,
699    source: &FrameSequence<F, M, G, P>,
700    normalized: &NormalizedSequence<F>,
701    plan: &MotionHistoryPlan<F>,
702    parameters: &MotionHistoryParameters,
703) -> Result<()> {
704    canvas.fill_rect(0, 0, layout.dimensions.width(), HEADER_HEIGHT, BLACK)?;
705    draw_clipped_text(
706        canvas,
707        0,
708        1,
709        layout.dimensions.width(),
710        parameters.labels.title(),
711        WHITE,
712    )?;
713    draw_clipped_text(
714        canvas,
715        0,
716        13,
717        layout.dimensions.width(),
718        parameters.labels.source(),
719        MUTED,
720    )?;
721    draw_clipped_text(
722        canvas,
723        0,
724        25,
725        layout.dimensions.width(),
726        &format!(
727            "MOTION HISTORY | RANGE {} - {}",
728            format_time(source.range().start()),
729            format_time(source.range().end())
730        ),
731        MUTED,
732    )?;
733
734    let reference = &normalized.frames()[plan.reference_frame_index()];
735    let width = usize::try_from(plan.dimensions().width()).map_err(|_| canvas_limit_error())?;
736    for (pixel, rgb) in reference.linear_rgb16().chunks_exact(3).enumerate() {
737        let luminance = linear_luminance(rgb)?;
738        let gray =
739            u8::try_from((luminance * u128::from(parameters.reference_strength) + 32_767) / 65_535)
740                .map_err(|_| canvas_limit_error())?;
741        let alpha = u32::from(plan.accumulation[pixel]);
742        let accent = parameters.accent_color.channels();
743        let color = accent.map(|channel| {
744            let value = u32::from(gray) * (65_535 - alpha) + u32::from(channel) * alpha + 32_767;
745            (value / 65_535) as u8
746        });
747        let x = u32::try_from(pixel % width).map_err(|_| canvas_limit_error())?;
748        let y = u32::try_from(pixel / width).map_err(|_| canvas_limit_error())?;
749        canvas.set_pixel(x, layout.main_y + y, color)?;
750    }
751    for pixel in 0..plan.dimensions().pixel_count()? {
752        let x = u32::try_from(pixel % width).map_err(|_| canvas_limit_error())?;
753        let y = u32::try_from(pixel / width).map_err(|_| canvas_limit_error())?;
754        if plan.outline.includes(x, y) == Some(true) {
755            canvas.set_pixel(x, layout.main_y + y, parameters.outline_color.channels())?;
756        }
757    }
758    draw_footer(canvas, layout, source, plan, parameters)
759}
760
761fn draw_footer<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
762    canvas: &mut Canvas,
763    layout: MotionHistoryLayout,
764    source: &FrameSequence<F, M, G, P>,
765    plan: &MotionHistoryPlan<F>,
766    parameters: &MotionHistoryParameters,
767) -> Result<()> {
768    canvas.fill_rect(
769        0,
770        layout.footer_y,
771        layout.dimensions.width(),
772        FOOTER_HEIGHT,
773        PANEL,
774    )?;
775    let lines = annotation_lines(source, plan);
776    draw_clipped_text(
777        canvas,
778        4,
779        layout.footer_y + 3,
780        layout.dimensions.width().saturating_sub(8),
781        &lines.range,
782        WHITE,
783    )?;
784    draw_clipped_text(
785        canvas,
786        4,
787        layout.footer_y + 15,
788        layout.dimensions.width().saturating_sub(8),
789        &lines.decay,
790        MUTED,
791    )?;
792    draw_decay_ramp(canvas, layout, plan, parameters)?;
793    draw_clipped_text(
794        canvas,
795        4,
796        layout.footer_y + 42,
797        layout.dimensions.width().saturating_sub(8),
798        lines.disclaimer,
799        MUTED,
800    )?;
801    draw_clipped_text(
802        canvas,
803        4,
804        layout.footer_y + 54,
805        layout.dimensions.width().saturating_sub(8),
806        lines.direction,
807        WHITE,
808    )?;
809    draw_clipped_text(
810        canvas,
811        4,
812        layout.footer_y + 66,
813        layout.dimensions.width().saturating_sub(8),
814        lines.disambiguation,
815        MUTED,
816    )?;
817    if let Some(gap) = lines.gap {
818        canvas.fill_rect(
819            0,
820            layout.footer_y + 78,
821            layout.dimensions.width(),
822            16,
823            WARNING,
824        )?;
825        draw_clipped_text(
826            canvas,
827            4,
828            layout.footer_y + 80,
829            layout.dimensions.width().saturating_sub(8),
830            &gap,
831            BLACK,
832        )?;
833    }
834    Ok(())
835}
836
837fn draw_decay_ramp<F>(
838    canvas: &mut Canvas,
839    layout: MotionHistoryLayout,
840    plan: &MotionHistoryPlan<F>,
841    parameters: &MotionHistoryParameters,
842) -> Result<()> {
843    let width = layout.dimensions.width().saturating_sub(LEGEND_X * 2);
844    if width == 0 {
845        return Ok(());
846    }
847    let oldest_rank = plan
848        .live_window()
849        .saturating_sub(1)
850        .min(plan.max_segment_rank());
851    for x in 0..width {
852        let rank = if width == 1 {
853            oldest_rank
854        } else {
855            u32::try_from(u64::from(oldest_rank) * u64::from(width - 1 - x) / u64::from(width - 1))
856                .map_err(|_| canvas_limit_error())?
857        };
858        let alpha = u32::from(parameters.decay.weight_at(rank));
859        let color = parameters
860            .accent_color
861            .channels()
862            .map(|channel| (u32::from(channel) * alpha / 65_535) as u8);
863        for y in 0..LEGEND_HEIGHT {
864            canvas.set_pixel(LEGEND_X + x, layout.footer_y + LEGEND_Y_OFFSET + y, color)?;
865        }
866    }
867    Ok(())
868}
869
870#[derive(Debug, Eq, PartialEq)]
871struct AnnotationLines {
872    range: String,
873    decay: String,
874    disclaimer: &'static str,
875    direction: &'static str,
876    disambiguation: &'static str,
877    gap: Option<String>,
878}
879
880fn annotation_lines<F, M, G, P>(
881    source: &FrameSequence<F, M, G, P>,
882    plan: &MotionHistoryPlan<F>,
883) -> AnnotationLines
884where
885    F: Eq,
886    M: Eq,
887    G: Eq,
888    P: AsRef<[u8]>,
889{
890    let span = source
891        .range()
892        .end()
893        .as_nanos()
894        .saturating_sub(source.range().start().as_nanos());
895    let oldest_rank = plan
896        .live_window()
897        .saturating_sub(1)
898        .min(plan.max_segment_rank());
899    AnnotationLines {
900        range: format!(
901            "START {} | END {} | SPAN {} NS",
902            format_time(source.range().start()),
903            format_time(source.range().end()),
904            span
905        ),
906        decay: format!(
907            "DECAY: OLDEST RETAINED RANK {} -> NEWEST RANK 0",
908            oldest_rank
909        ),
910        disclaimer: "MOTION HISTORY - SOURCE-DERIVED; NO DIRECTION INFERRED",
911        direction: "TIME -> START TO END; INTENSITY IS PER-SEGMENT RECENCY",
912        disambiguation: "OVERLAP MAY SMEAR DETAIL; INSPECT STORYBOARD OR REGION FILMSTRIP",
913        gap: (!source.gaps().is_empty()).then(|| {
914            format!(
915                "GAP - {} DECLARED; UNSEEN BEHAVIOR MAY HAVE OCCURRED",
916                source.gaps().len()
917            )
918        }),
919    }
920}
921
922fn draw_clipped_text(
923    canvas: &mut Canvas,
924    x: u32,
925    y: u32,
926    width: u32,
927    text: &str,
928    color: [u8; 3],
929) -> Result<()> {
930    let cells = usize::try_from(width / CELL_WIDTH).unwrap_or(0);
931    if cells == 0 {
932        return Ok(());
933    }
934    if let Some(text) = untruncated(text, cells) {
935        draw_text(canvas, x, y, &text, color)?;
936    }
937    Ok(())
938}
939
940fn format_time(timestamp: Timestamp) -> String {
941    let milliseconds = timestamp.as_nanos() / 1_000_000;
942    let micros = timestamp.as_nanos() % 1_000_000 / 1_000;
943    format!("{milliseconds}.{micros:03} MS")
944}
945
946fn display_step() -> Result<NormalizationStep> {
947    NormalizationStep::new(
948        NormalizationKind::ColorSpaceConversion,
949        "motion-history-display-rgb8-v1",
950        parameter_map([
951            (
952                "reference",
953                ParameterValue::Text("linear16_luminance_subdued_rgb8".into()),
954            ),
955            (
956                "motion",
957                ParameterValue::Text("u16_straight_alpha_accent_rgb8".into()),
958            ),
959            (
960                "outline",
961                ParameterValue::Text("four_connectivity_ever_changed".into()),
962            ),
963        ])?,
964    )
965}
966
967fn manifest_parameters<F, M, G, P>(
968    source: &FrameSequence<F, M, G, P>,
969    plan: &MotionHistoryPlan<F>,
970    request: &MotionHistoryParameters,
971) -> Result<Parameters>
972where
973    F: Display + Eq,
974    M: Eq,
975    G: Eq,
976    P: AsRef<[u8]>,
977{
978    let mut values = parameter_map([
979        ("title", ParameterValue::Text(request.labels.title().into())),
980        (
981            "source",
982            ParameterValue::Text(request.labels.source().into()),
983        ),
984        (
985            "reference_frame_index",
986            unsigned_usize(request.reference_frame_index)?,
987        ),
988        (
989            "reference_frame_id",
990            ParameterValue::Text(plan.reference_frame_id().to_string().into()),
991        ),
992        (
993            "peak_intensity",
994            ParameterValue::Unsigned(u64::from(request.decay.peak_intensity())),
995        ),
996        (
997            "half_life_ranks",
998            ParameterValue::Unsigned(u64::from(request.decay.half_life_ranks().get())),
999        ),
1000        (
1001            "live_window",
1002            ParameterValue::Unsigned(u64::from(plan.live_window())),
1003        ),
1004        (
1005            "reference_strength",
1006            ParameterValue::Unsigned(u64::from(request.reference_strength)),
1007        ),
1008        ("accent_rgb8", rgb_parameter(request.accent_color)),
1009        ("outline_rgb8", rgb_parameter(request.outline_color)),
1010        (
1011            "continuity_segment_count",
1012            unsigned_usize(plan.continuity_segment_count())?,
1013        ),
1014        (
1015            "measured_pair_count",
1016            unsigned_usize(plan.measured_pair_count())?,
1017        ),
1018        ("gap_pair_count", unsigned_usize(plan.gap_pair_count())?),
1019        ("declared_gap_count", unsigned_usize(source.gaps().len())?),
1020        (
1021            "changed_pixel_count",
1022            ParameterValue::Unsigned(plan.changed_pixel_count()),
1023        ),
1024        (
1025            "max_segment_rank",
1026            ParameterValue::Unsigned(u64::from(plan.max_segment_rank())),
1027        ),
1028        (
1029            "accumulation",
1030            ParameterValue::Text("saturating_u16_per_segment_then_pixelwise_max".into()),
1031        ),
1032        (
1033            "cross_gap_policy",
1034            ParameterValue::Text("never_accumulate_across_declared_gap".into()),
1035        ),
1036        (
1037            "outline",
1038            ParameterValue::Text("ever_changed_four_connectivity_boundary".into()),
1039        ),
1040        ("direction_inference", ParameterValue::Text("none".into())),
1041        (
1042            "disambiguation",
1043            ParameterValue::Text("storyboard_or_region_filmstrip".into()),
1044        ),
1045        (
1046            "layout",
1047            ParameterValue::Text("fixed_header_combined_image_footer_v1".into()),
1048        ),
1049        (
1050            "header_height",
1051            ParameterValue::Unsigned(u64::from(HEADER_HEIGHT)),
1052        ),
1053        (
1054            "footer_height",
1055            ParameterValue::Unsigned(u64::from(FOOTER_HEIGHT)),
1056        ),
1057        ("encoding", ParameterValue::Text(PNG_PROFILE.into())),
1058        (
1059            "max_canvas_bytes",
1060            unsigned_usize(request.limits.max_canvas_bytes())?,
1061        ),
1062        (
1063            "max_encoded_bytes",
1064            unsigned_usize(request.limits.max_encoded_bytes())?,
1065        ),
1066    ])?;
1067    if let Some(sampling) = analysis_sampling_parameters(source)? {
1068        values.insert("analysis_sampling", sampling)?;
1069    }
1070    Ok(values)
1071}
1072
1073fn rgb_parameter(color: Rgb8) -> ParameterValue {
1074    ParameterValue::List(
1075        color
1076            .channels()
1077            .into_iter()
1078            .map(|channel| ParameterValue::Unsigned(u64::from(channel)))
1079            .collect(),
1080    )
1081}
1082
1083fn parameter_map<const N: usize>(
1084    entries: [(&'static str, ParameterValue); N],
1085) -> Result<Parameters> {
1086    Parameters::new(
1087        entries
1088            .into_iter()
1089            .map(|(key, value)| (key.into(), value))
1090            .collect::<BTreeMap<_, _>>(),
1091    )
1092}
1093
1094fn unsigned_usize(value: usize) -> Result<ParameterValue> {
1095    Ok(ParameterValue::Unsigned(
1096        u64::try_from(value).map_err(|_| motion_limit_error())?,
1097    ))
1098}
1099
1100fn motion_limit_error() -> VisionError {
1101    VisionError::new(
1102        ErrorCode::ResourceLimitExceeded,
1103        "motion-history processing exceeds configured integer or memory limits",
1104    )
1105}
1106
1107#[cfg(test)]
1108mod tests {
1109    use super::*;
1110    use std::io::Cursor;
1111    use std::num::{NonZeroU32, NonZeroUsize};
1112
1113    use crate::{
1114        DeclaredGap, Frame, IntegerScale, Marker, NormalizationParameters, PixelFormat,
1115        ProcessingLimits, Timestamp, normalize_sequence,
1116    };
1117
1118    fn parameters(limits: RenderLimits) -> MotionHistoryParameters {
1119        MotionHistoryParameters::new(
1120            0,
1121            MeasurementParameters::new(0),
1122            MotionDecay::default(),
1123            64,
1124            Rgb8::new(255, 176, 0),
1125            Rgb8::new(255, 255, 255),
1126            ArtifactLabels::new("motion", "fixture").unwrap(),
1127            limits,
1128        )
1129    }
1130
1131    #[test]
1132    fn decay_curve_is_exact_at_boundaries() {
1133        let decay = MotionDecay::new(60_000, NonZeroU8::new(2).unwrap());
1134        assert_eq!(decay.weight_at(0), 60_000);
1135        assert_eq!(decay.weight_at(1), 60_000);
1136        assert_eq!(decay.weight_at(2), 30_000);
1137        assert_eq!(decay.weight_at(31), 1);
1138        assert_eq!(decay.weight_at(32), 0);
1139        assert_eq!(decay.live_window(), 32);
1140    }
1141
1142    #[test]
1143    fn outline_uses_four_connectivity_and_image_edges() {
1144        let dimensions = PixelDimensions::new(3, 3).unwrap();
1145        let full = [0xff, 0x80];
1146        assert_eq!(build_outline(&full, dimensions).unwrap(), [0xf7, 0x80]);
1147        let isolated = [0x10, 0x00];
1148        assert_eq!(build_outline(&isolated, dimensions).unwrap(), isolated);
1149    }
1150
1151    #[test]
1152    fn narrow_motion_history_omits_unreadable_label_bands() {
1153        let dimensions = PixelDimensions::new(239, 1).unwrap();
1154        let source = FrameSequence::new(
1155            vec![
1156                Frame::new(
1157                    0_u8,
1158                    Timestamp::ZERO,
1159                    dimensions,
1160                    PixelFormat::Rgba8SrgbStraight,
1161                    (0..dimensions.width())
1162                        .flat_map(|_| [0, 0, 0, 255])
1163                        .collect::<Vec<_>>()
1164                        .into_boxed_slice(),
1165                )
1166                .unwrap(),
1167            ],
1168            Vec::<Marker<u8>>::new(),
1169            Vec::<DeclaredGap<u8>>::new(),
1170            None,
1171            None,
1172        )
1173        .unwrap();
1174        let normalized = normalize_sequence(
1175            &source,
1176            NormalizationParameters::new(
1177                Rgb8::new(0, 0, 0),
1178                None,
1179                IntegerScale::IDENTITY,
1180                ProcessingLimits::default(),
1181            ),
1182        )
1183        .unwrap();
1184        let labels = ArtifactLabels::new(
1185            "a deliberately long title that cannot fit",
1186            "a deliberately long source context that cannot fit",
1187        )
1188        .unwrap();
1189        let rendered = generate_motion_history(
1190            1_u8,
1191            &source,
1192            &normalized,
1193            MotionHistoryParameters::new(
1194                0,
1195                MeasurementParameters::new(0),
1196                MotionDecay::default(),
1197                64,
1198                Rgb8::new(255, 176, 0),
1199                Rgb8::new(255, 255, 255),
1200                labels,
1201                RenderLimits::default(),
1202            ),
1203        )
1204        .unwrap();
1205        let decoder = png::Decoder::new(Cursor::new(rendered.image().bytes()));
1206        let mut reader = decoder.read_info().unwrap();
1207        let mut pixels = vec![0_u8; reader.output_buffer_size()];
1208        let info = reader.next_frame(&mut pixels).unwrap();
1209        assert_eq!(info.color_type, png::ColorType::Rgb);
1210        assert_eq!(info.width, dimensions.width());
1211        assert_eq!(
1212            info.height,
1213            HEADER_HEIGHT + dimensions.height() + FOOTER_HEIGHT
1214        );
1215        let image = &pixels[..info.buffer_size()];
1216        for y in 0..HEADER_HEIGHT {
1217            for x in 0..dimensions.width() {
1218                let offset = (y * dimensions.width() + x) as usize * 3;
1219                assert_eq!(&image[offset..offset + 3], BLACK);
1220            }
1221        }
1222        let footer_y = HEADER_HEIGHT + dimensions.height();
1223        for y in footer_y..footer_y + FOOTER_HEIGHT {
1224            if (footer_y + LEGEND_Y_OFFSET..footer_y + LEGEND_Y_OFFSET + LEGEND_HEIGHT).contains(&y)
1225            {
1226                continue;
1227            }
1228            for x in 0..dimensions.width() {
1229                let offset = (y * dimensions.width() + x) as usize * 3;
1230                assert_eq!(&image[offset..offset + 3], PANEL);
1231            }
1232        }
1233    }
1234
1235    #[test]
1236    fn accumulation_saturates_resets_at_gaps_and_respects_the_mask() {
1237        let dimensions = PixelDimensions::new(2, 1).unwrap();
1238        let frame = |id, time, value| {
1239            Frame::new(
1240                id,
1241                Timestamp::from_nanos(time),
1242                dimensions,
1243                PixelFormat::Rgba8SrgbStraight,
1244                vec![value, value, value, 255, value, value, value, 255].into_boxed_slice(),
1245            )
1246            .unwrap()
1247        };
1248        let gap = DeclaredGap::new(
1249            1_u8,
1250            TimeRange::new(Timestamp::from_nanos(15), Timestamp::from_nanos(15)).unwrap(),
1251            "loss",
1252            None,
1253        )
1254        .unwrap();
1255        let source = FrameSequence::new(
1256            vec![
1257                frame(0_u8, 0, 0),
1258                frame(1, 10, 255),
1259                frame(2, 20, 0),
1260                frame(3, 30, 255),
1261                frame(4, 40, 0),
1262            ],
1263            Vec::<Marker<u8>>::new(),
1264            vec![gap],
1265            None,
1266            Some(BinaryMask::new(dimensions, [0x80]).unwrap()),
1267        )
1268        .unwrap();
1269        let normalized = normalize_sequence(
1270            &source,
1271            NormalizationParameters::new(
1272                Rgb8::new(0, 0, 0),
1273                None,
1274                IntegerScale::IDENTITY,
1275                ProcessingLimits::default(),
1276            ),
1277        )
1278        .unwrap();
1279        let plan =
1280            build_motion_history_plan(&source, &normalized, &parameters(RenderLimits::default()))
1281                .unwrap();
1282
1283        assert_eq!(plan.accumulation(), &[u16::MAX, 0]);
1284        assert_eq!(plan.continuity_segment_count(), 2);
1285        assert_eq!(plan.measured_pair_count(), 3);
1286        assert_eq!(plan.gap_pair_count(), 1);
1287        assert_eq!(plan.changed_pixel_count(), 1);
1288        assert_eq!(plan.ever_changed().bits(), &[0x80]);
1289        assert_eq!(plan.outline().bits(), &[0x80]);
1290
1291        let lines = annotation_lines(&source, &plan);
1292        assert_eq!(lines.range, "START 0.000 MS | END 0.000 MS | SPAN 40 NS");
1293        assert_eq!(
1294            lines.decay,
1295            "DECAY: OLDEST RETAINED RANK 1 -> NEWEST RANK 0"
1296        );
1297        assert_eq!(
1298            lines.disclaimer,
1299            "MOTION HISTORY - SOURCE-DERIVED; NO DIRECTION INFERRED"
1300        );
1301        assert_eq!(
1302            lines.direction,
1303            "TIME -> START TO END; INTENSITY IS PER-SEGMENT RECENCY"
1304        );
1305        assert_eq!(
1306            lines.gap.as_deref(),
1307            Some("GAP - 1 DECLARED; UNSEEN BEHAVIOR MAY HAVE OCCURRED")
1308        );
1309    }
1310
1311    #[test]
1312    fn plan_memory_is_bounded_before_accumulator_allocation() {
1313        let limits = RenderLimits::new(
1314            NonZeroU32::new(10).unwrap(),
1315            NonZeroU32::new(10).unwrap(),
1316            NonZeroUsize::new(4).unwrap(),
1317            NonZeroUsize::new(10).unwrap(),
1318        );
1319        assert_eq!(
1320            ensure_plan_memory_fits(1, limits).unwrap_err().code,
1321            ErrorCode::ResourceLimitExceeded
1322        );
1323    }
1324}