1pub(crate) mod canvas;
2pub(crate) mod font;
3
4use std::{
5 collections::BTreeMap,
6 fmt::Display,
7 num::{NonZeroU32, NonZeroUsize},
8};
9
10use crate::{
11 AlgorithmDescriptor, ArtifactKind, ArtifactManifest, DeclaredGap, EncodedImage, ErrorCode,
12 EvidenceClass, FrameSequence, GeneratedArtifact, Marker, MeasurementParameters,
13 NormalizationKind, NormalizationStep, NormalizedSequence, ParameterValue, Parameters,
14 PixelDimensions, Result, SelectionReason, StoryboardSelection, StoryboardTileLimit, Timestamp,
15 VisionError, generator_descriptor, normalize::make_parameters,
16 select_storyboard_frames_with_analysis,
17};
18use canvas::{
19 BLACK, Canvas, MUTED, PANEL, WARNING, WHITE, canvas_limit_error, canvas_output_limit_error,
20};
21use font::{CELL_WIDTH, draw_text, ellipsize, untruncated};
22
23const PREFERRED_TILE_WIDTH: u32 = 240;
24const MINIMUM_TILE_WIDTH: u32 = 160;
25const HEADER_HEIGHT: u32 = 52;
26const STORY_ANNOTATION_HEIGHT: u32 = 70;
27const ORIENTATION_ANNOTATION_HEIGHT: u32 = 48;
28const TIMELINE_HEIGHT: u32 = 24;
29const DEFAULT_MAX_DIMENSION: u32 = 4_096;
30const DEFAULT_MAX_BYTES: usize = 64 * 1024 * 1024;
31
32#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct ArtifactLabels {
35 title: String,
36 source: String,
37}
38
39impl ArtifactLabels {
40 pub fn new(title: impl Into<String>, source: impl Into<String>) -> Result<Self> {
41 let title = title.into();
42 let source = source.into();
43 if title.trim().is_empty() || source.trim().is_empty() {
44 return Err(VisionError::new(
45 ErrorCode::InvalidParameter,
46 "artifact title and source context must not be empty",
47 ));
48 }
49 Ok(Self { title, source })
50 }
51
52 pub fn title(&self) -> &str {
53 &self.title
54 }
55
56 pub fn source(&self) -> &str {
57 &self.source
58 }
59}
60
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63pub struct RenderLimits {
64 max_width: NonZeroU32,
65 max_height: NonZeroU32,
66 max_canvas_bytes: NonZeroUsize,
67 max_encoded_bytes: NonZeroUsize,
68}
69
70impl RenderLimits {
71 pub const fn new(
72 max_width: NonZeroU32,
73 max_height: NonZeroU32,
74 max_canvas_bytes: NonZeroUsize,
75 max_encoded_bytes: NonZeroUsize,
76 ) -> Self {
77 Self {
78 max_width,
79 max_height,
80 max_canvas_bytes,
81 max_encoded_bytes,
82 }
83 }
84
85 pub const fn max_width(self) -> u32 {
86 self.max_width.get()
87 }
88
89 pub const fn max_height(self) -> u32 {
90 self.max_height.get()
91 }
92
93 pub const fn max_canvas_bytes(self) -> usize {
94 self.max_canvas_bytes.get()
95 }
96
97 pub const fn max_encoded_bytes(self) -> usize {
98 self.max_encoded_bytes.get()
99 }
100}
101
102impl Default for RenderLimits {
103 fn default() -> Self {
104 Self::new(
105 NonZeroU32::new(DEFAULT_MAX_DIMENSION).expect("default is nonzero"),
106 NonZeroU32::new(DEFAULT_MAX_DIMENSION).expect("default is nonzero"),
107 NonZeroUsize::new(DEFAULT_MAX_BYTES).expect("default is nonzero"),
108 NonZeroUsize::new(DEFAULT_MAX_BYTES).expect("default is nonzero"),
109 )
110 }
111}
112
113#[derive(Clone, Debug, Eq, PartialEq)]
115pub struct StoryboardParameters {
116 anchor: Timestamp,
117 tile_limit: StoryboardTileLimit,
118 measurement: MeasurementParameters,
119 labels: ArtifactLabels,
120 limits: RenderLimits,
121 analysis_source_indices: Option<Vec<usize>>,
122}
123
124impl StoryboardParameters {
125 pub fn new(
126 anchor: Timestamp,
127 tile_limit: StoryboardTileLimit,
128 measurement: MeasurementParameters,
129 labels: ArtifactLabels,
130 limits: RenderLimits,
131 ) -> Self {
132 Self {
133 anchor,
134 tile_limit,
135 measurement,
136 labels,
137 limits,
138 analysis_source_indices: None,
139 }
140 }
141
142 pub fn with_analysis_source_indices(mut self, indices: Vec<usize>) -> Self {
143 self.analysis_source_indices = Some(indices);
144 self
145 }
146
147 pub const fn anchor(&self) -> Timestamp {
148 self.anchor
149 }
150 pub const fn tile_limit(&self) -> StoryboardTileLimit {
151 self.tile_limit
152 }
153 pub const fn measurement(&self) -> MeasurementParameters {
154 self.measurement
155 }
156 pub const fn labels(&self) -> &ArtifactLabels {
157 &self.labels
158 }
159 pub const fn limits(&self) -> RenderLimits {
160 self.limits
161 }
162
163 pub fn analysis_source_indices(&self) -> Option<&[usize]> {
164 self.analysis_source_indices.as_deref()
165 }
166 pub const fn preferred_tile_width(&self) -> u32 {
167 PREFERRED_TILE_WIDTH
168 }
169 pub const fn minimum_tile_width(&self) -> u32 {
170 MINIMUM_TILE_WIDTH
171 }
172}
173
174#[derive(Clone, Debug, PartialEq)]
176pub struct StoryboardArtifacts<ArtifactId, FrameId, MarkerId, GapId> {
177 storyboard: GeneratedArtifact<ArtifactId, FrameId, MarkerId, GapId>,
178 orientation: Option<GeneratedArtifact<ArtifactId, FrameId, MarkerId, GapId>>,
179 selection: StoryboardSelection<FrameId>,
180}
181
182impl<A, F, M, G> StoryboardArtifacts<A, F, M, G> {
183 pub const fn storyboard(&self) -> &GeneratedArtifact<A, F, M, G> {
184 &self.storyboard
185 }
186 pub fn orientation(&self) -> Option<&GeneratedArtifact<A, F, M, G>> {
187 self.orientation.as_ref()
188 }
189 pub const fn selection(&self) -> &StoryboardSelection<F> {
190 &self.selection
191 }
192}
193
194pub fn generate_storyboard<A, F, M, G, P>(
196 storyboard_artifact_id: A,
197 orientation_artifact_id: Option<A>,
198 source: &FrameSequence<F, M, G, P>,
199 normalized: &NormalizedSequence<F>,
200 parameters: StoryboardParameters,
201) -> Result<StoryboardArtifacts<A, F, M, G>>
202where
203 F: Clone + Eq + Display,
204 M: Clone + Eq,
205 G: Clone + Eq,
206 P: AsRef<[u8]>,
207{
208 generate_storyboard_with_analysis(
209 storyboard_artifact_id,
210 orientation_artifact_id,
211 source,
212 normalized,
213 parameters,
214 None,
215 )
216}
217
218pub fn generate_storyboard_with_analysis<A, F, M, G, P>(
219 storyboard_artifact_id: A,
220 orientation_artifact_id: Option<A>,
221 source: &FrameSequence<F, M, G, P>,
222 normalized: &NormalizedSequence<F>,
223 parameters: StoryboardParameters,
224 shared: Option<&crate::SharedAdjacentAnalysis<F>>,
225) -> Result<StoryboardArtifacts<A, F, M, G>>
226where
227 F: Clone + Eq + Display,
228 M: Clone + Eq,
229 G: Clone + Eq,
230 P: AsRef<[u8]>,
231{
232 let selection = select_storyboard_frames_with_analysis(
233 source,
234 normalized,
235 parameters.anchor,
236 parameters.tile_limit,
237 parameters.measurement,
238 shared,
239 )?;
240 let marker_assignments = assign_markers(source.markers(), &selection);
241 let storyboard_raster = render_storyboard(
242 source,
243 normalized,
244 &selection,
245 &marker_assignments,
246 ¶meters,
247 )?;
248 let storyboard = finish_artifact(
249 storyboard_artifact_id,
250 ArtifactKind::Storyboard,
251 source,
252 normalized,
253 selection
254 .selected_frames()
255 .iter()
256 .map(|frame| frame.frame_id().clone())
257 .collect(),
258 &selection,
259 &marker_assignments,
260 ¶meters,
261 storyboard_raster,
262 "chronological_strip",
263 )?;
264
265 let orientation = if let Some(artifact_id) = orientation_artifact_id {
266 let role_indices = [
267 selection.before_index(),
268 selection.during_index(),
269 selection.after_index(),
270 ];
271 let mut selected_indices = role_indices.to_vec();
272 selected_indices.sort_unstable();
273 selected_indices.dedup();
274 let selected_ids = selected_indices
275 .iter()
276 .map(|index| source.frames()[*index].id().clone())
277 .collect();
278 let raster = render_orientation(source, normalized, &selection, ¶meters)?;
279 Some(finish_artifact(
280 artifact_id,
281 ArtifactKind::BeforeDuringAfter,
282 source,
283 normalized,
284 selected_ids,
285 &selection,
286 &marker_assignments,
287 ¶meters,
288 raster,
289 "before_during_after",
290 )?)
291 } else {
292 None
293 };
294
295 Ok(StoryboardArtifacts {
296 storyboard,
297 orientation,
298 selection,
299 })
300}
301
302struct Raster {
303 canvas: Canvas,
304 tile_width: u32,
305 image_height: u32,
306}
307
308fn render_storyboard<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
309 source: &FrameSequence<F, M, G, P>,
310 normalized: &NormalizedSequence<F>,
311 selection: &StoryboardSelection<F>,
312 marker_assignments: &[Vec<usize>],
313 parameters: &StoryboardParameters,
314) -> Result<Raster> {
315 let layout = checked_layout(
316 selection.selected_frames().len(),
317 normalized.dimensions(),
318 story_annotation_height(
319 selection,
320 source,
321 marker_assignments,
322 parameters.anchor,
323 parameters.limits,
324 ),
325 parameters.limits,
326 )?;
327 let mut canvas = Canvas::new(
328 layout.dimensions,
329 BLACK,
330 parameters.limits.max_canvas_bytes(),
331 )?;
332 draw_header(
333 &mut canvas,
334 source,
335 parameters,
336 !source.gaps().is_empty(),
337 selection.omitted_anchors().len(),
338 )?;
339 let image_y = HEADER_HEIGHT;
340 let annotation_y = image_y + layout.image_height;
341 if layout.annotation_height > 0 {
342 canvas.fill_rect(
343 0,
344 annotation_y,
345 layout.dimensions.width(),
346 layout.annotation_height,
347 PANEL,
348 )?;
349 }
350 canvas.fill_rect(
351 0,
352 annotation_y + layout.annotation_height,
353 layout.dimensions.width(),
354 TIMELINE_HEIGHT,
355 BLACK,
356 )?;
357
358 for (tile, selected) in selection.selected_frames().iter().enumerate() {
359 let tile_x = u32::try_from(tile)
360 .map_err(|_| canvas_limit_error())?
361 .checked_mul(layout.tile_width)
362 .ok_or_else(canvas_limit_error)?;
363 let frame = &normalized.frames()[selected.frame_index()];
364 canvas.draw_linear_frame(
365 frame.dimensions(),
366 frame.linear_rgb16(),
367 tile_x,
368 image_y,
369 layout.tile_width,
370 layout.image_height,
371 )?;
372 draw_story_annotation(
373 &mut canvas,
374 (tile_x, annotation_y, layout.tile_width),
375 selected,
376 source,
377 &marker_assignments[tile],
378 parameters.anchor,
379 )?;
380 }
381
382 for pair in selection.selected_frames().windows(2) {
383 if gap_intersects(source.gaps(), pair[0].timestamp(), pair[1].timestamp()) {
384 let right_tile = selection
385 .selected_frames()
386 .iter()
387 .position(|frame| frame.frame_index() == pair[1].frame_index())
388 .expect("selected frame is present");
389 let boundary_x = u32::try_from(right_tile)
390 .map_err(|_| canvas_limit_error())?
391 .checked_mul(layout.tile_width)
392 .ok_or_else(canvas_limit_error)?;
393 let hatch_x = boundary_x.saturating_sub(4);
394 canvas.draw_hatch(
395 hatch_x,
396 annotation_y,
397 8,
398 layout.annotation_height + TIMELINE_HEIGHT,
399 WARNING,
400 )?;
401 if layout.annotation_height > 0 {
402 let label_x = boundary_x.saturating_sub(18);
403 draw_text(&mut canvas, label_x, annotation_y + 50, "GAP", WARNING)?;
404 }
405 }
406 }
407 draw_timeline(
408 &mut canvas,
409 annotation_y + layout.annotation_height,
410 source,
411 layout.dimensions.width(),
412 )?;
413 Ok(Raster {
414 canvas,
415 tile_width: layout.tile_width,
416 image_height: layout.image_height,
417 })
418}
419
420fn render_orientation<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
421 source: &FrameSequence<F, M, G, P>,
422 normalized: &NormalizedSequence<F>,
423 selection: &StoryboardSelection<F>,
424 parameters: &StoryboardParameters,
425) -> Result<Raster> {
426 let layout = checked_layout(
427 3,
428 normalized.dimensions(),
429 ORIENTATION_ANNOTATION_HEIGHT,
430 parameters.limits,
431 )?;
432 let mut canvas = Canvas::new(
433 layout.dimensions,
434 BLACK,
435 parameters.limits.max_canvas_bytes(),
436 )?;
437 draw_header(
438 &mut canvas,
439 source,
440 parameters,
441 !source.gaps().is_empty(),
442 selection.omitted_anchors().len(),
443 )?;
444 let image_y = HEADER_HEIGHT;
445 let annotation_y = image_y + layout.image_height;
446 canvas.fill_rect(
447 0,
448 annotation_y,
449 layout.dimensions.width(),
450 ORIENTATION_ANNOTATION_HEIGHT,
451 PANEL,
452 )?;
453 canvas.fill_rect(
454 0,
455 annotation_y + ORIENTATION_ANNOTATION_HEIGHT,
456 layout.dimensions.width(),
457 TIMELINE_HEIGHT,
458 BLACK,
459 )?;
460
461 let roles = [
462 ("BEFORE", selection.before_index()),
463 (during_label(selection), selection.during_index()),
464 ("AFTER", selection.after_index()),
465 ];
466 for (panel, (label, frame_index)) in roles.into_iter().enumerate() {
467 let panel_x = u32::try_from(panel)
468 .map_err(|_| canvas_limit_error())?
469 .checked_mul(layout.tile_width)
470 .ok_or_else(canvas_limit_error)?;
471 let frame = &normalized.frames()[frame_index];
472 canvas.draw_linear_frame(
473 frame.dimensions(),
474 frame.linear_rgb16(),
475 panel_x,
476 image_y,
477 layout.tile_width,
478 layout.image_height,
479 )?;
480 let max_cells = usize::try_from(layout.tile_width / CELL_WIDTH)
481 .unwrap_or(0)
482 .saturating_sub(1);
483 draw_untruncated(
484 &mut canvas,
485 panel_x + 3,
486 annotation_y + 2,
487 label,
488 max_cells,
489 WHITE,
490 )?;
491 let source_label = format!("FRAME {}", source.frames()[frame_index].id());
492 draw_ellipsized(
493 &mut canvas,
494 panel_x + 3,
495 annotation_y + 14,
496 &source_label,
497 max_cells,
498 MUTED,
499 )?;
500 let time = time_and_offset(source.frames()[frame_index].timestamp(), parameters.anchor);
501 draw_untruncated(
502 &mut canvas,
503 panel_x + 3,
504 annotation_y + 26,
505 &time,
506 max_cells,
507 MUTED,
508 )?;
509 }
510 draw_timeline(
511 &mut canvas,
512 annotation_y + ORIENTATION_ANNOTATION_HEIGHT,
513 source,
514 layout.dimensions.width(),
515 )?;
516 Ok(Raster {
517 canvas,
518 tile_width: layout.tile_width,
519 image_height: layout.image_height,
520 })
521}
522
523fn during_label<F>(selection: &StoryboardSelection<F>) -> &'static str {
524 let selected = selection
525 .selected_frames()
526 .iter()
527 .find(|frame| frame.frame_index() == selection.during_index());
528 if selected.is_some_and(|frame| {
529 frame
530 .reasons()
531 .contains(&SelectionReason::PeakBaselineChange)
532 }) {
533 "DURING - PEAK BASELINE CHANGE"
534 } else if selection.during_index() != selection.before_index() {
535 "DURING - FIRST POST ANCHOR"
536 } else {
537 "DURING - BASELINE FALLBACK"
538 }
539}
540
541struct Layout {
542 dimensions: PixelDimensions,
543 tile_width: u32,
544 image_height: u32,
545 annotation_height: u32,
546}
547
548fn checked_layout(
549 tile_count: usize,
550 source_dimensions: PixelDimensions,
551 annotation_height: u32,
552 limits: RenderLimits,
553) -> Result<Layout> {
554 let count = u32::try_from(tile_count).map_err(|_| canvas_limit_error())?;
555 if count == 0 {
556 return Err(canvas_limit_error());
557 }
558 let tile_width = PREFERRED_TILE_WIDTH.min(limits.max_width() / count);
559 if tile_width < MINIMUM_TILE_WIDTH {
560 return Err(canvas_limit_error());
561 }
562 let image_height_u64 = u64::from(tile_width)
563 .checked_mul(u64::from(source_dimensions.height()))
564 .ok_or_else(canvas_limit_error)?
565 .checked_add(u64::from(source_dimensions.width()) / 2)
566 .ok_or_else(canvas_limit_error)?
567 / u64::from(source_dimensions.width());
568 let image_height = u32::try_from(image_height_u64.max(1)).map_err(|_| canvas_limit_error())?;
569 let width = tile_width
570 .checked_mul(count)
571 .ok_or_else(canvas_limit_error)?;
572 let height = HEADER_HEIGHT
573 .checked_add(image_height)
574 .and_then(|value| value.checked_add(annotation_height))
575 .and_then(|value| value.checked_add(TIMELINE_HEIGHT))
576 .ok_or_else(canvas_limit_error)?;
577 if width > limits.max_width() || height > limits.max_height() {
578 return Err(canvas_output_limit_error(
579 width,
580 height,
581 limits.max_width(),
582 limits.max_height(),
583 ));
584 }
585 let dimensions = PixelDimensions::new(width, height).map_err(|_| canvas_limit_error())?;
586 let bytes = dimensions
587 .pixel_count()?
588 .checked_mul(3)
589 .ok_or_else(canvas_limit_error)?;
590 if bytes > limits.max_canvas_bytes() {
591 return Err(canvas_limit_error());
592 }
593 Ok(Layout {
594 dimensions,
595 tile_width,
596 image_height,
597 annotation_height,
598 })
599}
600
601fn draw_header<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
602 canvas: &mut Canvas,
603 source: &FrameSequence<F, M, G, P>,
604 parameters: &StoryboardParameters,
605 has_gaps: bool,
606 omitted_anchors: usize,
607) -> Result<()> {
608 let max_cells = usize::try_from(canvas.dimensions().width() / CELL_WIDTH)
609 .unwrap_or(0)
610 .saturating_sub(1);
611 draw_untruncated(canvas, 4, 2, parameters.labels.title(), max_cells, WHITE)?;
612 draw_untruncated(canvas, 4, 14, parameters.labels.source(), max_cells, MUTED)?;
613 let range = format!(
614 "RANGE {} - {} | ANCHOR {}",
615 format_time(source.range().start()),
616 format_time(source.range().end()),
617 format_time(parameters.anchor)
618 );
619 draw_untruncated(canvas, 4, 26, &range, max_cells, MUTED)?;
620 let warning = match (has_gaps, omitted_anchors) {
621 (true, 0) => "GAP - UNSEEN BEHAVIOR MAY HAVE OCCURRED".to_owned(),
622 (false, count) if count > 0 => format!("ANCHORS OMITTED: {count}; SEE MANIFEST"),
623 (true, count) => format!(
624 "GAP - UNSEEN BEHAVIOR MAY HAVE OCCURRED | ANCHORS OMITTED: {count}; SEE MANIFEST"
625 ),
626 (false, 0) => "SOURCE-DERIVED | SELECTED FRAMES; SEE MANIFEST".to_owned(),
627 _ => unreachable!(),
628 };
629 draw_untruncated(
630 canvas,
631 4,
632 38,
633 &warning,
634 max_cells,
635 if has_gaps { WARNING } else { MUTED },
636 )?;
637 Ok(())
638}
639
640fn draw_story_annotation<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
641 canvas: &mut Canvas,
642 tile: (u32, u32, u32),
643 selected: &crate::SelectedFrame<F>,
644 source: &FrameSequence<F, M, G, P>,
645 marker_indices: &[usize],
646 anchor: Timestamp,
647) -> Result<()> {
648 let (tile_x, annotation_y, tile_width) = tile;
649 let max_cells = usize::try_from(tile_width / CELL_WIDTH)
650 .unwrap_or(0)
651 .saturating_sub(1);
652 let lines = story_annotation_lines(selected, source, marker_indices, anchor);
653 for (line, text) in lines.iter().enumerate() {
654 let x = tile_x + 3;
655 let y = annotation_y + 2 + line as u32 * 12;
656 let color = if line == 0 { WHITE } else { MUTED };
657 if matches!(line, 1 | 3) {
658 draw_ellipsized(canvas, x, y, text, max_cells, color)?;
659 } else {
660 draw_untruncated(canvas, x, y, text, max_cells, color)?;
661 }
662 }
663 Ok(())
664}
665
666fn draw_timeline<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
667 canvas: &mut Canvas,
668 y: u32,
669 source: &FrameSequence<F, M, G, P>,
670 width: u32,
671) -> Result<()> {
672 let cells = usize::try_from(width / CELL_WIDTH).unwrap_or(0);
673 draw_untruncated(canvas, 4, y + 6, "TIME ->", cells, WHITE)?;
674 let end = format!(
675 "{} -> {}",
676 format_time(source.range().start()),
677 format_time(source.range().end())
678 );
679 let text_width = u32::try_from(end.chars().count())
680 .unwrap_or(u32::MAX)
681 .saturating_mul(CELL_WIDTH);
682 let x = width.saturating_sub(text_width + 4);
683 draw_untruncated(canvas, x, y + 6, &end, cells, MUTED)?;
684 Ok(())
685}
686
687fn draw_untruncated(
688 canvas: &mut Canvas,
689 x: u32,
690 y: u32,
691 text: &str,
692 max_cells: usize,
693 color: [u8; 3],
694) -> Result<bool> {
695 let Some(text) = untruncated(text, max_cells) else {
696 return Ok(false);
697 };
698 draw_text(canvas, x, y, &text, color)?;
699 Ok(true)
700}
701
702fn draw_ellipsized(
703 canvas: &mut Canvas,
704 x: u32,
705 y: u32,
706 text: &str,
707 max_cells: usize,
708 color: [u8; 3],
709) -> Result<()> {
710 draw_text(canvas, x, y, &ellipsize(text, max_cells), color)
711}
712
713fn story_annotation_lines<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
714 selected: &crate::SelectedFrame<F>,
715 source: &FrameSequence<F, M, G, P>,
716 marker_indices: &[usize],
717 anchor: Timestamp,
718) -> [String; 5] {
719 let marker_text = if marker_indices.is_empty() {
720 "MARKERS NONE".to_owned()
721 } else {
722 format!(
723 "MARKERS {}",
724 marker_indices
725 .iter()
726 .map(|index| {
727 let marker = &source.markers()[*index];
728 format!("{}: {}", marker.kind(), marker.label())
729 })
730 .collect::<Vec<_>>()
731 .join(" | ")
732 )
733 };
734 [
735 time_and_offset(selected.timestamp(), anchor),
736 format!("FRAME {}", selected.frame_id()),
737 format!(
738 "REASON {}",
739 selected
740 .reasons()
741 .iter()
742 .map(|reason| reason.as_str())
743 .collect::<Vec<_>>()
744 .join(" + ")
745 ),
746 marker_text,
747 "SOURCE FRAME - AUTHORITATIVE".to_owned(),
748 ]
749}
750
751fn story_annotation_height<F: Display + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
752 selection: &StoryboardSelection<F>,
753 source: &FrameSequence<F, M, G, P>,
754 marker_assignments: &[Vec<usize>],
755 anchor: Timestamp,
756 limits: RenderLimits,
757) -> u32 {
758 let Some(tile_count) = u32::try_from(selection.selected_frames().len()).ok() else {
759 return STORY_ANNOTATION_HEIGHT;
760 };
761 let tile_width = PREFERRED_TILE_WIDTH.min(limits.max_width() / tile_count.max(1));
762 let max_cells = usize::try_from(tile_width / CELL_WIDTH)
763 .unwrap_or(0)
764 .saturating_sub(1);
765 let any_label_fits = selection
766 .selected_frames()
767 .iter()
768 .zip(marker_assignments)
769 .any(|(selected, markers)| {
770 story_annotation_lines(selected, source, markers, anchor)
771 .iter()
772 .enumerate()
773 .any(|(line, text)| matches!(line, 1 | 3) || untruncated(text, max_cells).is_some())
774 });
775 if any_label_fits {
776 STORY_ANNOTATION_HEIGHT
777 } else {
778 0
779 }
780}
781
782fn format_time(timestamp: Timestamp) -> String {
783 let milliseconds = timestamp.as_nanos() / 1_000_000;
784 let micros = timestamp.as_nanos() % 1_000_000 / 1_000;
785 format!("{milliseconds}.{micros:03} MS")
786}
787
788fn time_and_offset(timestamp: Timestamp, anchor: Timestamp) -> String {
789 let offset = i128::from(timestamp.as_nanos()) - i128::from(anchor.as_nanos());
790 let sign = if offset < 0 { '-' } else { '+' };
791 let magnitude = offset.unsigned_abs();
792 let milliseconds = magnitude / 1_000_000;
793 let micros = magnitude % 1_000_000 / 1_000;
794 format!(
795 "T {} | {sign}{milliseconds}.{micros:03} MS",
796 format_time(timestamp)
797 )
798}
799
800fn assign_markers<F, M>(
801 markers: &[Marker<M>],
802 selection: &StoryboardSelection<F>,
803) -> Vec<Vec<usize>> {
804 let mut assignments = vec![Vec::new(); selection.selected_frames().len()];
805 for (marker_index, marker) in markers.iter().enumerate() {
806 let tile = selection
807 .selected_frames()
808 .iter()
809 .position(|frame| frame.timestamp() >= marker.timestamp())
810 .unwrap_or(selection.selected_frames().len() - 1);
811 assignments[tile].push(marker_index);
812 }
813 assignments
814}
815
816fn gap_intersects<G>(gaps: &[DeclaredGap<G>], start: Timestamp, end: Timestamp) -> bool {
817 gaps.iter()
818 .any(|gap| gap.range().start() <= end && gap.range().end() >= start)
819}
820
821#[allow(clippy::too_many_arguments)]
822fn finish_artifact<A, F, M, G, P>(
823 artifact_id: A,
824 kind: ArtifactKind,
825 source: &FrameSequence<F, M, G, P>,
826 normalized: &NormalizedSequence<F>,
827 selected_ids: Vec<F>,
828 selection: &StoryboardSelection<F>,
829 marker_assignments: &[Vec<usize>],
830 request: &StoryboardParameters,
831 raster: Raster,
832 layout_name: &'static str,
833) -> Result<GeneratedArtifact<A, F, M, G>>
834where
835 F: Clone + Eq + Display,
836 M: Clone + Eq,
837 G: Clone + Eq,
838 P: AsRef<[u8]>,
839{
840 let dimensions = raster.canvas.dimensions();
841 let (bytes, hash) = crate::encode::encode_png(
842 dimensions,
843 raster.canvas.pixels(),
844 request.limits.max_encoded_bytes(),
845 )?;
846 let mut normalization = normalized.normalization_steps().to_vec();
847 normalization.push(request.measurement.provenance_step()?);
848 normalization.push(display_conversion_step()?);
849 let parameters = artifact_parameters(
850 kind,
851 selection,
852 marker_assignments,
853 request,
854 source.source_frame_count(),
855 raster.tile_width,
856 raster.image_height,
857 layout_name,
858 )?;
859 let manifest = ArtifactManifest::from_storyboard_sequence(
860 artifact_id,
861 kind,
862 EvidenceClass::SourceDerived,
863 {
864 let descriptor = generator_descriptor(kind);
865 AlgorithmDescriptor::new(descriptor.name, descriptor.version)?
866 },
867 source,
868 selected_ids,
869 selection.clone(),
870 normalization,
871 parameters,
872 dimensions,
873 hash,
874 )?;
875 Ok(GeneratedArtifact::new(
876 EncodedImage::new(dimensions, bytes),
877 manifest,
878 ))
879}
880
881fn display_conversion_step() -> Result<NormalizationStep> {
882 NormalizationStep::new(
883 NormalizationKind::ColorSpaceConversion,
884 "linear16-to-srgb8-v1",
885 make_parameters([
886 ("input", ParameterValue::Text("rgb16_linear_opaque".into())),
887 ("output", ParameterValue::Text("rgb8_srgb_opaque".into())),
888 (
889 "mapping",
890 ParameterValue::Text("nearest_checked_lut_entry".into()),
891 ),
892 (
893 "tie_break",
894 ParameterValue::Text("lower_encoded_value".into()),
895 ),
896 ])?,
897 )
898}
899
900#[allow(clippy::too_many_arguments)]
901fn artifact_parameters<F>(
902 kind: ArtifactKind,
903 selection: &StoryboardSelection<F>,
904 marker_assignments: &[Vec<usize>],
905 request: &StoryboardParameters,
906 source_frame_count: usize,
907 tile_width: u32,
908 image_height: u32,
909 layout_name: &'static str,
910) -> Result<Parameters>
911where
912 F: Display,
913{
914 let selected = selection
915 .selected_frames()
916 .iter()
917 .map(|frame| {
918 object([
919 ("frame_index", unsigned_usize(frame.frame_index())?),
920 (
921 "frame_label",
922 ParameterValue::Text(frame.frame_id().to_string().into()),
923 ),
924 (
925 "timestamp_nanos",
926 ParameterValue::Unsigned(frame.timestamp().as_nanos()),
927 ),
928 (
929 "reasons",
930 ParameterValue::List(
931 frame
932 .reasons()
933 .iter()
934 .map(|reason| ParameterValue::Text(reason.as_str().into()))
935 .collect(),
936 ),
937 ),
938 ])
939 })
940 .collect::<Result<Vec<_>>>()?;
941 let omitted = selection
942 .omitted_anchors()
943 .iter()
944 .map(|anchor| {
945 object([
946 ("frame_index", unsigned_usize(anchor.frame_index())?),
947 (
948 "reason",
949 ParameterValue::Text(anchor.reason().as_str().into()),
950 ),
951 ])
952 })
953 .collect::<Result<Vec<_>>>()?;
954 let marker_buckets = marker_assignments
955 .iter()
956 .enumerate()
957 .map(|(tile, markers)| {
958 object([
959 ("tile_index", unsigned_usize(tile)?),
960 (
961 "marker_declaration_indices",
962 ParameterValue::List(
963 markers
964 .iter()
965 .map(|index| unsigned_usize(*index))
966 .collect::<Result<Vec<_>>>()?,
967 ),
968 ),
969 ])
970 })
971 .collect::<Result<Vec<_>>>()?;
972 let roles = object([
973 (
974 "before_source_index",
975 unsigned_usize(selection.before_index())?,
976 ),
977 (
978 "during_source_index",
979 unsigned_usize(selection.during_index())?,
980 ),
981 (
982 "after_source_index",
983 unsigned_usize(selection.after_index())?,
984 ),
985 (
986 "during_rule",
987 ParameterValue::Text(during_label(selection).into()),
988 ),
989 ])?;
990 let mut values = BTreeMap::new();
991 for (key, value) in [
992 (
993 "algorithm_version",
994 ParameterValue::Text(generator_descriptor(kind).version.into()),
995 ),
996 ("artifact_kind", ParameterValue::Text(kind.as_str().into())),
997 (
998 "anchor_nanos",
999 ParameterValue::Unsigned(request.anchor.as_nanos()),
1000 ),
1001 (
1002 "tile_limit",
1003 ParameterValue::Unsigned(u64::from(request.tile_limit.get())),
1004 ),
1005 ("title", ParameterValue::Text(request.labels.title().into())),
1006 (
1007 "source_context",
1008 ParameterValue::Text(request.labels.source().into()),
1009 ),
1010 ("layout", ParameterValue::Text(layout_name.into())),
1011 (
1012 "tile_width",
1013 ParameterValue::Unsigned(u64::from(tile_width)),
1014 ),
1015 (
1016 "image_height",
1017 ParameterValue::Unsigned(u64::from(image_height)),
1018 ),
1019 (
1020 "preferred_tile_width",
1021 ParameterValue::Unsigned(u64::from(PREFERRED_TILE_WIDTH)),
1022 ),
1023 (
1024 "minimum_tile_width",
1025 ParameterValue::Unsigned(u64::from(MINIMUM_TILE_WIDTH)),
1026 ),
1027 (
1028 "max_output_width",
1029 ParameterValue::Unsigned(u64::from(request.limits.max_width())),
1030 ),
1031 (
1032 "max_output_height",
1033 ParameterValue::Unsigned(u64::from(request.limits.max_height())),
1034 ),
1035 (
1036 "max_canvas_bytes",
1037 unsigned_usize(request.limits.max_canvas_bytes())?,
1038 ),
1039 (
1040 "max_encoded_bytes",
1041 unsigned_usize(request.limits.max_encoded_bytes())?,
1042 ),
1043 (
1044 "scale_kernel",
1045 ParameterValue::Text("nearest_neighbor_integer_center".into()),
1046 ),
1047 (
1048 "source_fit",
1049 ParameterValue::Text("contain_preserve_aspect".into()),
1050 ),
1051 (
1052 "font",
1053 ParameterValue::Text("embedded-5x7-in-6x10-ascii-v1".into()),
1054 ),
1055 (
1056 "text_policy",
1057 ParameterValue::Text("escaped_ascii_middle_notice_exact_text_in_manifest".into()),
1058 ),
1059 (
1060 "png",
1061 ParameterValue::Text("png-0.17.16-rgb8-best-no_filter-no_chunks".into()),
1062 ),
1063 (
1064 "continuity_segments",
1065 unsigned_usize(selection.continuity_segment_count())?,
1066 ),
1067 ("selected", ParameterValue::List(selected)),
1068 ("omitted_anchors", ParameterValue::List(omitted)),
1069 ("marker_assignments", ParameterValue::List(marker_buckets)),
1070 ("orientation_roles", roles),
1071 ] {
1072 values.insert(key.into(), value);
1073 }
1074 if let Some(indices) = request.analysis_source_indices() {
1075 values.insert(
1076 "analysis_sampling".into(),
1077 object([
1078 ("source_frame_count", unsigned_usize(source_frame_count)?),
1079 ("analyzed_frame_count", unsigned_usize(indices.len())?),
1080 ("mode", ParameterValue::Text("uniform_bounded".into())),
1081 ("spacing", ParameterValue::Text("uniform".into())),
1082 (
1083 "analyzed_source_indices",
1084 ParameterValue::List(
1085 indices
1086 .iter()
1087 .map(|index| unsigned_usize(*index))
1088 .collect::<Result<Vec<_>>>()?,
1089 ),
1090 ),
1091 ])?,
1092 );
1093 }
1094 Parameters::new(values)
1095}
1096
1097fn unsigned_usize(value: usize) -> Result<ParameterValue> {
1098 Ok(ParameterValue::Unsigned(
1099 u64::try_from(value).map_err(|_| canvas_limit_error())?,
1100 ))
1101}
1102
1103fn object<const N: usize>(entries: [(&'static str, ParameterValue); N]) -> Result<ParameterValue> {
1104 let map: BTreeMap<Box<str>, ParameterValue> = entries
1105 .into_iter()
1106 .map(|(key, value)| (key.into(), value))
1107 .collect();
1108 Parameters::new(map.clone())?;
1109 Ok(ParameterValue::Object(map))
1110}
1111
1112#[cfg(test)]
1113mod tests {
1114 use super::*;
1115
1116 #[test]
1117 fn checked_layout_rejects_small_tiles_height_and_canvas() {
1118 let dimensions = PixelDimensions::new(16, 9).unwrap();
1119 let small_width = RenderLimits::new(
1120 NonZeroU32::new(479).unwrap(),
1121 NonZeroU32::new(4096).unwrap(),
1122 NonZeroUsize::new(DEFAULT_MAX_BYTES).unwrap(),
1123 NonZeroUsize::new(DEFAULT_MAX_BYTES).unwrap(),
1124 );
1125 assert!(checked_layout(3, dimensions, STORY_ANNOTATION_HEIGHT, small_width).is_err());
1126 let small_height = RenderLimits::new(
1127 NonZeroU32::new(720).unwrap(),
1128 NonZeroU32::new(100).unwrap(),
1129 NonZeroUsize::new(DEFAULT_MAX_BYTES).unwrap(),
1130 NonZeroUsize::new(DEFAULT_MAX_BYTES).unwrap(),
1131 );
1132 assert!(checked_layout(3, dimensions, STORY_ANNOTATION_HEIGHT, small_height).is_err());
1133 }
1134
1135 #[test]
1136 fn gap_intersection_includes_equal_boundaries() {
1137 let gap = DeclaredGap::new(
1138 1_u8,
1139 crate::TimeRange::new(Timestamp::from_nanos(2), Timestamp::from_nanos(2)).unwrap(),
1140 "loss",
1141 None,
1142 )
1143 .unwrap();
1144 assert!(gap_intersects(
1145 &[gap],
1146 Timestamp::from_nanos(1),
1147 Timestamp::from_nanos(2)
1148 ));
1149 }
1150}