1use std::{
2 collections::BTreeMap,
3 mem::size_of,
4 num::{NonZeroU8, NonZeroUsize},
5};
6
7use serde::{Deserialize, Serialize};
8
9use crate::{
10 BinaryMask, ErrorCode, Frame, FrameSequence, NormalizationKind, NormalizationStep,
11 ParameterValue, Parameters, PixelDimensions, PixelRect, Result, TimeRange, Timestamp,
12 VisionError,
13};
14
15const MAX_SCALE_FACTOR: u8 = 8;
16const DEFAULT_MAX_FRAMES: usize = 4_096;
17const DEFAULT_MAX_PIXELS_PER_FRAME: usize = 16_777_216;
18const DEFAULT_MAX_RETAINED_BYTES: usize = 512 * 1024 * 1024;
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
22pub struct Rgb8 {
23 red: u8,
24 green: u8,
25 blue: u8,
26}
27
28impl Rgb8 {
29 pub const fn new(red: u8, green: u8, blue: u8) -> Self {
30 Self { red, green, blue }
31 }
32
33 pub const fn channels(self) -> [u8; 3] {
34 [self.red, self.green, self.blue]
35 }
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39enum ScaleDirection {
40 Identity,
41 Up,
42 Down,
43}
44
45#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47pub struct IntegerScale {
48 direction: ScaleDirection,
49 factor: NonZeroU8,
50}
51
52impl IntegerScale {
53 pub const IDENTITY: Self = Self {
54 direction: ScaleDirection::Identity,
55 factor: NonZeroU8::MIN,
56 };
57
58 pub fn up(factor: NonZeroU8) -> Result<Self> {
59 Self::new(ScaleDirection::Up, factor)
60 }
61
62 pub fn down(factor: NonZeroU8) -> Result<Self> {
63 Self::new(ScaleDirection::Down, factor)
64 }
65
66 fn new(direction: ScaleDirection, factor: NonZeroU8) -> Result<Self> {
67 if factor.get() > MAX_SCALE_FACTOR {
68 return Err(VisionError::new(
69 ErrorCode::InvalidScale,
70 "integer scale factor must be between one and eight",
71 ));
72 }
73 if factor.get() == 1 {
74 return Ok(Self::IDENTITY);
75 }
76 Ok(Self { direction, factor })
77 }
78
79 pub const fn factor(self) -> u8 {
80 self.factor.get()
81 }
82
83 pub const fn is_identity(self) -> bool {
84 matches!(self.direction, ScaleDirection::Identity)
85 }
86
87 pub(crate) fn direction_name(self) -> &'static str {
88 match self.direction {
89 ScaleDirection::Identity => "identity",
90 ScaleDirection::Up => "up",
91 ScaleDirection::Down => "down",
92 }
93 }
94}
95
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
98pub struct ProcessingLimits {
99 max_frames: NonZeroUsize,
100 max_pixels_per_frame: NonZeroUsize,
101 max_retained_bytes: NonZeroUsize,
102}
103
104impl ProcessingLimits {
105 pub const fn new(
106 max_frames: NonZeroUsize,
107 max_pixels_per_frame: NonZeroUsize,
108 max_retained_bytes: NonZeroUsize,
109 ) -> Self {
110 Self {
111 max_frames,
112 max_pixels_per_frame,
113 max_retained_bytes,
114 }
115 }
116
117 pub const fn max_frames(self) -> usize {
118 self.max_frames.get()
119 }
120
121 pub const fn max_pixels_per_frame(self) -> usize {
122 self.max_pixels_per_frame.get()
123 }
124
125 pub const fn max_retained_bytes(self) -> usize {
126 self.max_retained_bytes.get()
127 }
128}
129
130impl Default for ProcessingLimits {
131 fn default() -> Self {
132 Self::new(
133 NonZeroUsize::new(DEFAULT_MAX_FRAMES).expect("default is nonzero"),
134 NonZeroUsize::new(DEFAULT_MAX_PIXELS_PER_FRAME).expect("default is nonzero"),
135 NonZeroUsize::new(DEFAULT_MAX_RETAINED_BYTES).expect("default is nonzero"),
136 )
137 }
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
142pub struct NormalizationParameters {
143 background: Rgb8,
144 crop: Option<PixelRect>,
145 scale: IntegerScale,
146 limits: ProcessingLimits,
147}
148
149impl NormalizationParameters {
150 pub const fn new(
151 background: Rgb8,
152 crop: Option<PixelRect>,
153 scale: IntegerScale,
154 limits: ProcessingLimits,
155 ) -> Self {
156 Self {
157 background,
158 crop,
159 scale,
160 limits,
161 }
162 }
163
164 pub const fn background(self) -> Rgb8 {
165 self.background
166 }
167
168 pub const fn crop(self) -> Option<PixelRect> {
169 self.crop
170 }
171
172 pub const fn scale(self) -> IntegerScale {
173 self.scale
174 }
175
176 pub const fn limits(self) -> ProcessingLimits {
177 self.limits
178 }
179}
180
181#[derive(Clone, Debug, Eq, PartialEq)]
183pub struct NormalizedFrame<FrameId> {
184 id: FrameId,
185 timestamp: Timestamp,
186 dimensions: PixelDimensions,
187 linear_rgb16: Box<[u16]>,
188}
189
190impl<F> NormalizedFrame<F> {
191 pub fn id(&self) -> &F {
192 &self.id
193 }
194
195 pub const fn timestamp(&self) -> Timestamp {
196 self.timestamp
197 }
198
199 pub const fn dimensions(&self) -> PixelDimensions {
200 self.dimensions
201 }
202
203 pub fn linear_rgb16(&self) -> &[u16] {
204 &self.linear_rgb16
205 }
206}
207
208#[derive(Clone, Debug, PartialEq)]
210pub struct NormalizedSequence<FrameId> {
211 source_dimensions: PixelDimensions,
212 source_crop: PixelRect,
213 dimensions: PixelDimensions,
214 frames: Box<[NormalizedFrame<FrameId>]>,
215 analysis_mask: Option<BinaryMask>,
216 analysis_pixel_count: u64,
217 gap_ranges: Box<[TimeRange]>,
218 normalization_steps: Box<[NormalizationStep]>,
219}
220
221impl<F> NormalizedSequence<F> {
222 pub fn frames(&self) -> &[NormalizedFrame<F>] {
223 &self.frames
224 }
225
226 pub const fn dimensions(&self) -> PixelDimensions {
227 self.dimensions
228 }
229
230 pub const fn source_dimensions(&self) -> PixelDimensions {
231 self.source_dimensions
232 }
233
234 pub const fn source_crop(&self) -> PixelRect {
235 self.source_crop
236 }
237
238 pub fn analysis_mask(&self) -> Option<&BinaryMask> {
239 self.analysis_mask.as_ref()
240 }
241
242 pub fn normalization_steps(&self) -> &[NormalizationStep] {
243 &self.normalization_steps
244 }
245
246 pub fn gap_ranges(&self) -> &[TimeRange] {
247 &self.gap_ranges
248 }
249
250 pub const fn analysis_pixel_count(&self) -> u64 {
251 self.analysis_pixel_count
252 }
253}
254
255pub fn normalize_sequence<F: Clone + Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
257 sequence: &FrameSequence<F, M, G, P>,
258 parameters: NormalizationParameters,
259) -> Result<NormalizedSequence<F>> {
260 let source_dimensions = sequence.dimensions();
261 let crop = match parameters.crop {
262 Some(crop) if crop.fits_within(source_dimensions) => crop,
263 Some(_) => {
264 return Err(VisionError::new(
265 ErrorCode::InvalidRegion,
266 "normalization crop lies outside the source-frame dimensions",
267 ));
268 }
269 None => PixelRect::new(0, 0, source_dimensions.width(), source_dimensions.height())?,
270 };
271 let dimensions = scaled_dimensions(crop, parameters.scale)?;
272 let output_pixels = dimensions.pixel_count()?;
273 let restricted_domain = sequence.region().is_some() || sequence.mask().is_some();
274 validate_resource_limits(
275 sequence.frames().len(),
276 output_pixels,
277 restricted_domain,
278 parameters.limits,
279 )?;
280
281 let (analysis_mask, analysis_pixel_count) = transformed_analysis_mask(
283 sequence,
284 crop,
285 dimensions,
286 parameters.scale,
287 restricted_domain,
288 )?;
289 let background = parameters.background.channels().map(linear_channel);
290 let allow_opaque_crop_fast_path = !restricted_domain;
291 let frames = sequence
292 .frames()
293 .iter()
294 .map(|frame| {
295 normalize_frame(
296 frame,
297 crop,
298 dimensions,
299 parameters.scale,
300 background,
301 allow_opaque_crop_fast_path,
302 )
303 })
304 .collect::<Result<Vec<_>>>()?
305 .into_boxed_slice();
306 let gap_ranges = sequence
307 .gaps()
308 .iter()
309 .map(|gap| gap.range())
310 .collect::<Vec<_>>()
311 .into_boxed_slice();
312 let normalization_steps = normalization_steps(parameters, crop, dimensions)?;
313
314 Ok(NormalizedSequence {
315 source_dimensions,
316 source_crop: crop,
317 dimensions,
318 frames,
319 analysis_mask,
320 analysis_pixel_count,
321 gap_ranges,
322 normalization_steps: normalization_steps.into_boxed_slice(),
323 })
324}
325
326fn scaled_dimensions(crop: PixelRect, scale: IntegerScale) -> Result<PixelDimensions> {
327 let factor = u32::from(scale.factor());
328 let (width, height) = match scale.direction {
329 ScaleDirection::Identity => (crop.width(), crop.height()),
330 ScaleDirection::Up => (
331 crop.width().checked_mul(factor).ok_or_else(|| {
332 VisionError::new(
333 ErrorCode::InvalidScale,
334 "scaled width exceeds the coordinate space",
335 )
336 })?,
337 crop.height().checked_mul(factor).ok_or_else(|| {
338 VisionError::new(
339 ErrorCode::InvalidScale,
340 "scaled height exceeds the coordinate space",
341 )
342 })?,
343 ),
344 ScaleDirection::Down => {
345 if !crop.width().is_multiple_of(factor) || !crop.height().is_multiple_of(factor) {
346 return Err(VisionError::new(
347 ErrorCode::InvalidScale,
348 "downscale factor must exactly divide both cropped dimensions",
349 ));
350 }
351 (crop.width() / factor, crop.height() / factor)
352 }
353 };
354 PixelDimensions::new(width, height).map_err(|_| {
355 VisionError::new(
356 ErrorCode::InvalidScale,
357 "scaled dimensions exceed the supported address space",
358 )
359 })
360}
361
362fn validate_resource_limits(
363 frame_count: usize,
364 output_pixels: usize,
365 restricted_domain: bool,
366 limits: ProcessingLimits,
367) -> Result<()> {
368 if frame_count > limits.max_frames() {
369 return Err(sized_resource_limit_error(
370 "normalized frame count",
371 frame_count,
372 limits.max_frames(),
373 ));
374 }
375 if output_pixels > limits.max_pixels_per_frame() {
376 return Err(sized_resource_limit_error(
377 "normalized pixels per frame",
378 output_pixels,
379 limits.max_pixels_per_frame(),
380 ));
381 }
382 let values_per_frame = output_pixels
383 .checked_mul(3)
384 .ok_or_else(resource_limit_error)?;
385 let bytes_per_frame = values_per_frame
386 .checked_mul(size_of::<u16>())
387 .ok_or_else(resource_limit_error)?;
388 let frame_bytes = bytes_per_frame
389 .checked_mul(frame_count)
390 .ok_or_else(resource_limit_error)?;
391 let mask_bytes = if restricted_domain {
392 output_pixels
393 .checked_add(7)
394 .ok_or_else(resource_limit_error)?
395 / 8
396 } else {
397 0
398 };
399 let retained_bytes = frame_bytes
400 .checked_add(mask_bytes)
401 .ok_or_else(resource_limit_error)?;
402 if retained_bytes > limits.max_retained_bytes() {
403 return Err(sized_resource_limit_error(
404 "normalized retained bytes",
405 retained_bytes,
406 limits.max_retained_bytes(),
407 ));
408 }
409 Ok(())
410}
411
412fn resource_limit_error() -> VisionError {
413 VisionError::new(
414 ErrorCode::ResourceLimitExceeded,
415 "normalization processing exceeded the supported address space",
416 )
417}
418
419fn sized_resource_limit_error(
420 subject: impl std::fmt::Display,
421 actual: impl std::fmt::Display,
422 limit: impl std::fmt::Display,
423) -> VisionError {
424 VisionError {
425 code: ErrorCode::ResourceLimitExceeded,
426 message: format!("{subject}: {actual} exceeds limit {limit}").into(),
427 index: None,
428 }
429}
430
431fn transformed_analysis_mask<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
432 sequence: &FrameSequence<F, M, G, P>,
433 crop: PixelRect,
434 dimensions: PixelDimensions,
435 scale: IntegerScale,
436 restricted_domain: bool,
437) -> Result<(Option<BinaryMask>, u64)> {
438 let output_pixels = dimensions.pixel_count()?;
439 if !restricted_domain {
440 return Ok((
441 None,
442 u64::try_from(output_pixels).map_err(|_| resource_limit_error())?,
443 ));
444 }
445
446 let mut bits = vec![
447 0_u8;
448 output_pixels
449 .checked_add(7)
450 .ok_or_else(resource_limit_error)?
451 / 8
452 ];
453 let mut included = 0_u64;
454 for y in 0..dimensions.height() {
455 for x in 0..dimensions.width() {
456 if output_pixel_in_domain(sequence, crop, scale, x, y) {
457 let index = usize::try_from(y)
458 .ok()
459 .and_then(|row| row.checked_mul(usize::try_from(dimensions.width()).ok()?))
460 .and_then(|row| row.checked_add(usize::try_from(x).ok()?))
461 .ok_or_else(resource_limit_error)?;
462 bits[index / 8] |= 0x80 >> (index % 8);
463 included = included.checked_add(1).ok_or_else(resource_limit_error)?;
464 }
465 }
466 }
467 if included == 0 {
468 return Err(VisionError::new(
469 ErrorCode::EmptyAnalysisDomain,
470 "normalization crop, region, and mask have no measurable output pixels",
471 ));
472 }
473 Ok((Some(BinaryMask::new(dimensions, bits)?), included))
474}
475
476fn output_pixel_in_domain<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
477 sequence: &FrameSequence<F, M, G, P>,
478 crop: PixelRect,
479 scale: IntegerScale,
480 output_x: u32,
481 output_y: u32,
482) -> bool {
483 let factor = u32::from(scale.factor());
484 match scale.direction {
485 ScaleDirection::Identity => {
486 source_pixel_in_domain(sequence, crop.x() + output_x, crop.y() + output_y)
487 }
488 ScaleDirection::Up => source_pixel_in_domain(
489 sequence,
490 crop.x() + output_x / factor,
491 crop.y() + output_y / factor,
492 ),
493 ScaleDirection::Down => {
494 let source_x = crop.x() + output_x * factor;
495 let source_y = crop.y() + output_y * factor;
496 (0..factor).all(|dy| {
497 (0..factor).all(|dx| source_pixel_in_domain(sequence, source_x + dx, source_y + dy))
498 })
499 }
500 }
501}
502
503fn source_pixel_in_domain<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>>(
504 sequence: &FrameSequence<F, M, G, P>,
505 x: u32,
506 y: u32,
507) -> bool {
508 let in_region = sequence.region().is_none_or(|region| {
509 let rect = region.rect();
510 x >= rect.x()
511 && y >= rect.y()
512 && x < rect.right_exclusive().expect("validated region")
513 && y < rect.bottom_exclusive().expect("validated region")
514 });
515 in_region
516 && sequence
517 .mask()
518 .is_none_or(|mask| mask.includes(x, y) == Some(true))
519}
520
521fn normalize_frame<F: Clone, P: AsRef<[u8]>>(
522 frame: &Frame<F, P>,
523 crop: PixelRect,
524 dimensions: PixelDimensions,
525 scale: IntegerScale,
526 background: [u16; 3],
527 allow_opaque_crop_fast_path: bool,
528) -> Result<NormalizedFrame<F>> {
529 let capacity = dimensions
530 .pixel_count()?
531 .checked_mul(3)
532 .ok_or_else(resource_limit_error)?;
533 if can_use_opaque_full_frame_fast_path(
534 frame,
535 crop,
536 dimensions,
537 scale,
538 allow_opaque_crop_fast_path,
539 ) {
540 return normalize_opaque_crop(frame, crop, dimensions, scale, capacity);
541 }
542 normalize_frame_general(frame, crop, dimensions, scale, background, capacity)
543}
544
545fn can_use_opaque_full_frame_fast_path<F, P: AsRef<[u8]>>(
546 frame: &Frame<F, P>,
547 crop: PixelRect,
548 dimensions: PixelDimensions,
549 scale: IntegerScale,
550 allow_opaque_crop_fast_path: bool,
551) -> bool {
552 if !allow_opaque_crop_fast_path {
553 return false;
554 }
555 let expected_dimensions = match scale.direction {
556 ScaleDirection::Identity => match scaled_dimensions(crop, scale) {
557 Ok(dimensions) => dimensions,
558 Err(_) => return false,
559 },
560 ScaleDirection::Down => match scaled_dimensions(crop, scale) {
561 Ok(dimensions) => dimensions,
562 Err(_) => return false,
563 },
564 ScaleDirection::Up => return false,
565 };
566 dimensions == expected_dimensions
567 && frame
568 .pixels()
569 .chunks_exact(4)
570 .all(|rgba| rgba[3] == u8::MAX)
571}
572
573fn normalize_opaque_crop<F: Clone, P: AsRef<[u8]>>(
574 frame: &Frame<F, P>,
575 crop: PixelRect,
576 dimensions: PixelDimensions,
577 scale: IntegerScale,
578 capacity: usize,
579) -> Result<NormalizedFrame<F>> {
580 match scale.direction {
581 ScaleDirection::Identity => normalize_opaque_identity(frame, crop, dimensions, capacity),
582 ScaleDirection::Down => {
583 normalize_opaque_downscale(frame, crop, dimensions, scale, capacity)
584 }
585 ScaleDirection::Up => unreachable!("opaque fast path excludes upscaling"),
586 }
587}
588
589fn normalize_opaque_identity<F: Clone, P: AsRef<[u8]>>(
590 frame: &Frame<F, P>,
591 crop: PixelRect,
592 dimensions: PixelDimensions,
593 capacity: usize,
594) -> Result<NormalizedFrame<F>> {
595 let source_width =
600 usize::try_from(frame.dimensions().width()).map_err(|_| resource_limit_error())?;
601 let crop_x = usize::try_from(crop.x()).map_err(|_| resource_limit_error())?;
602 let crop_y = usize::try_from(crop.y()).map_err(|_| resource_limit_error())?;
603 let crop_width = usize::try_from(crop.width()).map_err(|_| resource_limit_error())?;
604 let mut output = Vec::with_capacity(capacity);
605 for y in 0..usize::try_from(crop.height()).map_err(|_| resource_limit_error())? {
606 let row = crop_y
607 .checked_add(y)
608 .and_then(|row| row.checked_mul(source_width))
609 .and_then(|row| row.checked_add(crop_x))
610 .and_then(|pixel| pixel.checked_mul(4))
611 .ok_or_else(resource_limit_error)?;
612 for rgba in frame.pixels()[row..row + crop_width * 4].chunks_exact(4) {
613 output.extend_from_slice(&[
614 linear_channel(rgba[0]),
615 linear_channel(rgba[1]),
616 linear_channel(rgba[2]),
617 ]);
618 }
619 }
620 Ok(NormalizedFrame {
621 id: frame.id().clone(),
622 timestamp: frame.timestamp(),
623 dimensions,
624 linear_rgb16: output.into_boxed_slice(),
625 })
626}
627
628fn normalize_opaque_downscale<F: Clone, P: AsRef<[u8]>>(
629 frame: &Frame<F, P>,
630 crop: PixelRect,
631 dimensions: PixelDimensions,
632 scale: IntegerScale,
633 capacity: usize,
634) -> Result<NormalizedFrame<F>> {
635 let factor = usize::from(scale.factor());
639 let source_width =
640 usize::try_from(frame.dimensions().width()).map_err(|_| resource_limit_error())?;
641 let output_width = usize::try_from(dimensions.width()).map_err(|_| resource_limit_error())?;
642 let output_height = usize::try_from(dimensions.height()).map_err(|_| resource_limit_error())?;
643 let source_row_bytes = source_width
644 .checked_mul(4)
645 .ok_or_else(resource_limit_error)?;
646 let count = u64::try_from(factor)
647 .ok()
648 .and_then(|factor| factor.checked_mul(factor))
649 .ok_or_else(resource_limit_error)?;
650 let mut output = Vec::with_capacity(capacity);
651 let crop_x = usize::try_from(crop.x()).map_err(|_| resource_limit_error())?;
652 let crop_y = usize::try_from(crop.y()).map_err(|_| resource_limit_error())?;
653 for output_y in 0..output_height {
654 let source_row = crop_y
655 .checked_add(
656 output_y
657 .checked_mul(factor)
658 .ok_or_else(resource_limit_error)?,
659 )
660 .and_then(|row| row.checked_mul(source_row_bytes))
661 .ok_or_else(resource_limit_error)?;
662 for output_x in 0..output_width {
663 let source_column = crop_x
664 .checked_add(
665 output_x
666 .checked_mul(factor)
667 .ok_or_else(resource_limit_error)?,
668 )
669 .and_then(|column| column.checked_mul(4))
670 .ok_or_else(resource_limit_error)?;
671 let mut sums = [0_u64; 3];
672 for row in 0..factor {
673 let row_offset = row
674 .checked_mul(source_row_bytes)
675 .and_then(|offset| source_row.checked_add(offset))
676 .ok_or_else(resource_limit_error)?;
677 for column in 0..factor {
678 let offset = column
679 .checked_mul(4)
680 .and_then(|offset| source_column.checked_add(offset))
681 .and_then(|offset| row_offset.checked_add(offset))
682 .ok_or_else(resource_limit_error)?;
683 let rgba = &frame.pixels()[offset..offset + 4];
684 for channel in 0..3 {
685 sums[channel] = sums[channel]
686 .checked_add(u64::from(linear_channel(rgba[channel])))
687 .ok_or_else(resource_limit_error)?;
688 }
689 }
690 }
691 for sum in sums {
692 let value = sum
693 .checked_add(count / 2)
694 .ok_or_else(resource_limit_error)?
695 / count;
696 output.push(u16::try_from(value).map_err(|_| resource_limit_error())?);
697 }
698 }
699 }
700 Ok(NormalizedFrame {
701 id: frame.id().clone(),
702 timestamp: frame.timestamp(),
703 dimensions,
704 linear_rgb16: output.into_boxed_slice(),
705 })
706}
707
708fn normalize_frame_general<F: Clone, P: AsRef<[u8]>>(
709 frame: &Frame<F, P>,
710 crop: PixelRect,
711 dimensions: PixelDimensions,
712 scale: IntegerScale,
713 background: [u16; 3],
714 capacity: usize,
715) -> Result<NormalizedFrame<F>> {
716 let mut output = Vec::with_capacity(capacity);
717 let factor = u32::from(scale.factor());
718 for y in 0..dimensions.height() {
719 for x in 0..dimensions.width() {
720 let pixel = match scale.direction {
721 ScaleDirection::Identity => {
722 composited_pixel(frame, crop.x() + x, crop.y() + y, background)?
723 }
724 ScaleDirection::Up => composited_pixel(
725 frame,
726 crop.x() + x / factor,
727 crop.y() + y / factor,
728 background,
729 )?,
730 ScaleDirection::Down => downscaled_pixel(
731 frame,
732 crop.x() + x * factor,
733 crop.y() + y * factor,
734 factor,
735 background,
736 )?,
737 };
738 output.extend_from_slice(&pixel);
739 }
740 }
741 Ok(NormalizedFrame {
742 id: frame.id().clone(),
743 timestamp: frame.timestamp(),
744 dimensions,
745 linear_rgb16: output.into_boxed_slice(),
746 })
747}
748
749fn composited_pixel<F, P: AsRef<[u8]>>(
750 frame: &Frame<F, P>,
751 x: u32,
752 y: u32,
753 background: [u16; 3],
754) -> Result<[u16; 3]> {
755 let width = usize::try_from(frame.dimensions().width()).map_err(|_| resource_limit_error())?;
756 let index = usize::try_from(y)
757 .ok()
758 .and_then(|row| row.checked_mul(width))
759 .and_then(|row| row.checked_add(usize::try_from(x).ok()?))
760 .and_then(|pixel| pixel.checked_mul(4))
761 .ok_or_else(resource_limit_error)?;
762 let rgba = &frame.pixels()[index..index + 4];
763 let alpha = u32::from(rgba[3]);
764 let inverse_alpha = 255 - alpha;
765 let mut result = [0_u16; 3];
766 for channel in 0..3 {
767 let source = u32::from(linear_channel(rgba[channel]));
768 let backdrop = u32::from(background[channel]);
769 let value = source
770 .checked_mul(alpha)
771 .and_then(|value| value.checked_add(backdrop * inverse_alpha))
772 .and_then(|value| value.checked_add(127))
773 .ok_or_else(resource_limit_error)?
774 / 255;
775 result[channel] = u16::try_from(value).map_err(|_| resource_limit_error())?;
776 }
777 Ok(result)
778}
779
780fn downscaled_pixel<F, P: AsRef<[u8]>>(
781 frame: &Frame<F, P>,
782 source_x: u32,
783 source_y: u32,
784 factor: u32,
785 background: [u16; 3],
786) -> Result<[u16; 3]> {
787 let mut sums = [0_u64; 3];
788 for dy in 0..factor {
789 for dx in 0..factor {
790 let pixel = composited_pixel(frame, source_x + dx, source_y + dy, background)?;
791 for channel in 0..3 {
792 sums[channel] = sums[channel]
793 .checked_add(u64::from(pixel[channel]))
794 .ok_or_else(resource_limit_error)?;
795 }
796 }
797 }
798 let count = u64::from(factor) * u64::from(factor);
799 let mut result = [0_u16; 3];
800 for channel in 0..3 {
801 let rounded = sums[channel]
802 .checked_add(count / 2)
803 .ok_or_else(resource_limit_error)?
804 / count;
805 result[channel] = u16::try_from(rounded).map_err(|_| resource_limit_error())?;
806 }
807 Ok(result)
808}
809
810fn normalization_steps(
811 parameters: NormalizationParameters,
812 crop: PixelRect,
813 output_dimensions: PixelDimensions,
814) -> Result<Vec<NormalizationStep>> {
815 let mut steps = vec![
816 NormalizationStep::new(
817 NormalizationKind::ColorSpaceConversion,
818 "srgb8-to-linear16-v1",
819 make_parameters([
820 ("input", ParameterValue::Text("rgba8_srgb_straight".into())),
821 ("output", ParameterValue::Text("rgb16_linear_opaque".into())),
822 ("transfer", ParameterValue::Text("iec-61966-2-1".into())),
823 ])?,
824 )?,
825 NormalizationStep::new(
826 NormalizationKind::AlphaCompositing,
827 "straight-alpha-linear-v1",
828 make_parameters([
829 (
830 "background_srgb8",
831 ParameterValue::List(
832 parameters
833 .background
834 .channels()
835 .into_iter()
836 .map(|value| ParameterValue::Unsigned(u64::from(value)))
837 .collect(),
838 ),
839 ),
840 ("rounding", ParameterValue::Text("round_half_up".into())),
841 ])?,
842 )?,
843 ];
844 if parameters.crop.is_some() {
845 steps.push(NormalizationStep::new(
846 NormalizationKind::FixedCrop,
847 "source-pixel-crop-v1",
848 rect_parameters(crop)?,
849 )?);
850 }
851 if !parameters.scale.is_identity() {
852 let kernel = match parameters.scale.direction {
853 ScaleDirection::Up => "nearest_neighbor",
854 ScaleDirection::Down => "non_overlapping_box_average",
855 ScaleDirection::Identity => unreachable!(),
856 };
857 steps.push(NormalizationStep::new(
858 NormalizationKind::IntegerScaling,
859 "integer-scale-v1",
860 make_parameters([
861 (
862 "direction",
863 ParameterValue::Text(parameters.scale.direction_name().into()),
864 ),
865 (
866 "factor",
867 ParameterValue::Unsigned(u64::from(parameters.scale.factor())),
868 ),
869 ("kernel", ParameterValue::Text(kernel.into())),
870 (
871 "output_width",
872 ParameterValue::Unsigned(u64::from(output_dimensions.width())),
873 ),
874 (
875 "output_height",
876 ParameterValue::Unsigned(u64::from(output_dimensions.height())),
877 ),
878 (
879 "mask_reduction",
880 ParameterValue::Text("all_source_pixels".into()),
881 ),
882 ])?,
883 )?);
884 }
885 Ok(steps)
886}
887
888fn rect_parameters(rect: PixelRect) -> Result<Parameters> {
889 make_parameters([
890 ("x", ParameterValue::Unsigned(u64::from(rect.x()))),
891 ("y", ParameterValue::Unsigned(u64::from(rect.y()))),
892 ("width", ParameterValue::Unsigned(u64::from(rect.width()))),
893 ("height", ParameterValue::Unsigned(u64::from(rect.height()))),
894 ])
895}
896
897pub(crate) fn make_parameters<const N: usize>(
898 entries: [(&'static str, ParameterValue); N],
899) -> Result<Parameters> {
900 Parameters::new(
901 entries
902 .into_iter()
903 .map(|(key, value)| (Box::<str>::from(key), value))
904 .collect::<BTreeMap<_, _>>(),
905 )
906}
907
908const fn linear_channel(value: u8) -> u16 {
909 SRGB8_TO_LINEAR16[value as usize]
910}
911
912pub(crate) fn linear16_to_srgb8(value: u16) -> u8 {
915 match SRGB8_TO_LINEAR16.binary_search(&value) {
916 Ok(index) => index as u8,
917 Err(0) => 0,
918 Err(256) => 255,
919 Err(upper) => {
920 let lower = upper - 1;
921 let lower_distance = value - SRGB8_TO_LINEAR16[lower];
922 let upper_distance = SRGB8_TO_LINEAR16[upper] - value;
923 if lower_distance <= upper_distance {
924 lower as u8
925 } else {
926 upper as u8
927 }
928 }
929 }
930}
931
932const SRGB8_TO_LINEAR16: [u16; 256] = [
934 0, 20, 40, 60, 80, 99, 119, 139, 159, 179, 199, 219, 241, 264, 288, 313, 340, 367, 396, 427,
935 458, 491, 526, 562, 599, 637, 677, 718, 761, 805, 851, 898, 947, 997, 1048, 1101, 1156, 1212,
936 1270, 1330, 1391, 1453, 1517, 1583, 1651, 1720, 1790, 1863, 1937, 2013, 2090, 2170, 2250, 2333,
937 2418, 2504, 2592, 2681, 2773, 2866, 2961, 3058, 3157, 3258, 3360, 3464, 3570, 3678, 3788, 3900,
938 4014, 4129, 4247, 4366, 4488, 4611, 4736, 4864, 4993, 5124, 5257, 5392, 5530, 5669, 5810, 5953,
939 6099, 6246, 6395, 6547, 6700, 6856, 7014, 7174, 7335, 7500, 7666, 7834, 8004, 8177, 8352, 8528,
940 8708, 8889, 9072, 9258, 9445, 9635, 9828, 10022, 10219, 10417, 10619, 10822, 11028, 11235,
941 11446, 11658, 11873, 12090, 12309, 12530, 12754, 12980, 13209, 13440, 13673, 13909, 14146,
942 14387, 14629, 14874, 15122, 15371, 15623, 15878, 16135, 16394, 16656, 16920, 17187, 17456,
943 17727, 18001, 18277, 18556, 18837, 19121, 19407, 19696, 19987, 20281, 20577, 20876, 21177,
944 21481, 21787, 22096, 22407, 22721, 23038, 23357, 23678, 24002, 24329, 24658, 24990, 25325,
945 25662, 26001, 26344, 26688, 27036, 27386, 27739, 28094, 28452, 28813, 29176, 29542, 29911,
946 30282, 30656, 31033, 31412, 31794, 32179, 32567, 32957, 33350, 33745, 34143, 34544, 34948,
947 35355, 35764, 36176, 36591, 37008, 37429, 37852, 38278, 38706, 39138, 39572, 40009, 40449,
948 40891, 41337, 41785, 42236, 42690, 43147, 43606, 44069, 44534, 45002, 45473, 45947, 46423,
949 46903, 47385, 47871, 48359, 48850, 49344, 49841, 50341, 50844, 51349, 51858, 52369, 52884,
950 53401, 53921, 54445, 54971, 55500, 56032, 56567, 57105, 57646, 58190, 58737, 59287, 59840,
951 60396, 60955, 61517, 62082, 62650, 63221, 63795, 64372, 64952, 65535,
952];
953
954#[cfg(test)]
955mod tests {
956 use super::*;
957 use crate::{
958 ArtifactLabels, DeclaredGap, FrameRegion, Marker, MeasurementParameters, PixelFormat,
959 RenderLimits, StoryboardParameters, StoryboardTileLimit, generate_storyboard,
960 };
961 use sha2::{Digest, Sha256};
962
963 fn frame(id: u8, dimensions: PixelDimensions, pixels: Vec<u8>) -> Frame<u8, Box<[u8]>> {
964 Frame::new(
965 id,
966 Timestamp::from_nanos(u64::from(id)),
967 dimensions,
968 PixelFormat::Rgba8SrgbStraight,
969 pixels.into_boxed_slice(),
970 )
971 .unwrap()
972 }
973
974 #[test]
975 fn lookup_table_is_stable() {
976 assert_eq!(SRGB8_TO_LINEAR16[0], 0);
977 assert_eq!(SRGB8_TO_LINEAR16[10], 199);
978 assert_eq!(SRGB8_TO_LINEAR16[128], 14_146);
979 assert_eq!(SRGB8_TO_LINEAR16[255], 65_535);
980 assert_eq!(
981 SRGB8_TO_LINEAR16
982 .iter()
983 .map(|value| u64::from(*value))
984 .sum::<u64>(),
985 5_217_863
986 );
987 assert_eq!(linear16_to_srgb8(0), 0);
988 assert_eq!(linear16_to_srgb8(65_535), 255);
989 let midpoint = (SRGB8_TO_LINEAR16[100] + SRGB8_TO_LINEAR16[101]) / 2;
990 assert_eq!(linear16_to_srgb8(midpoint), 100);
991 }
992
993 #[test]
994 fn opaque_full_frame_fast_path_matches_reference_across_rectangular_scales() {
995 let dimensions = PixelDimensions::new(40, 24).unwrap();
996 let sequence = opaque_rectangular_sequence(dimensions);
997
998 for (factor, scale) in [
999 (1, IntegerScale::IDENTITY),
1000 (2, IntegerScale::down(NonZeroU8::new(2).unwrap()).unwrap()),
1001 (4, IntegerScale::down(NonZeroU8::new(4).unwrap()).unwrap()),
1002 (8, IntegerScale::down(NonZeroU8::new(8).unwrap()).unwrap()),
1003 ] {
1004 let parameters = NormalizationParameters::new(
1005 Rgb8::new(19, 37, 73),
1006 None,
1007 scale,
1008 ProcessingLimits::default(),
1009 );
1010 let optimized = normalize_sequence(&sequence, parameters).unwrap();
1011 let crop = optimized.source_crop();
1012 let capacity = optimized.dimensions().pixel_count().unwrap() * 3;
1013 assert!(sequence.frames().iter().all(|frame| {
1014 can_use_opaque_full_frame_fast_path(
1015 frame,
1016 crop,
1017 optimized.dimensions(),
1018 scale,
1019 true,
1020 )
1021 }));
1022
1023 let mut reference = optimized.clone();
1027 reference.frames = sequence
1028 .frames()
1029 .iter()
1030 .map(|frame| {
1031 normalize_frame_general(
1032 frame,
1033 crop,
1034 optimized.dimensions(),
1035 scale,
1036 parameters.background.channels().map(linear_channel),
1037 capacity,
1038 )
1039 })
1040 .collect::<Result<Vec<_>>>()
1041 .unwrap()
1042 .into_boxed_slice();
1043 assert_eq!(optimized, reference, "opaque scale factor {factor}");
1044
1045 if factor == 4 {
1046 let labels = ArtifactLabels::new(
1047 "Opaque normalization equivalence",
1048 "rectangular generated fixture",
1049 )
1050 .unwrap();
1051 let request = StoryboardParameters::new(
1052 Timestamp::from_nanos(2),
1053 StoryboardTileLimit::new(5).unwrap(),
1054 MeasurementParameters::new(0),
1055 labels,
1056 RenderLimits::default(),
1057 );
1058 let optimized_artifacts =
1059 generate_storyboard(41_u8, Some(42_u8), &sequence, &optimized, request.clone())
1060 .unwrap();
1061 let reference_artifacts =
1062 generate_storyboard(41_u8, Some(42_u8), &sequence, &reference, request)
1063 .unwrap();
1064 assert_eq!(optimized_artifacts, reference_artifacts);
1065 for (optimized_artifact, reference_artifact) in [
1066 (
1067 optimized_artifacts.storyboard(),
1068 reference_artifacts.storyboard(),
1069 ),
1070 (
1071 optimized_artifacts.orientation().unwrap(),
1072 reference_artifacts.orientation().unwrap(),
1073 ),
1074 ] {
1075 assert_eq!(
1076 &optimized_artifact.image().bytes()[..8],
1077 b"\x89PNG\r\n\x1a\n"
1078 );
1079 assert_eq!(
1080 optimized_artifact.image().bytes(),
1081 reference_artifact.image().bytes()
1082 );
1083 assert_eq!(optimized_artifact.manifest(), reference_artifact.manifest());
1084 let output_digest: [u8; 32] =
1085 Sha256::digest(optimized_artifact.image().bytes()).into();
1086 assert_eq!(
1087 optimized_artifact.manifest().output_hash().as_bytes(),
1088 &output_digest
1089 );
1090 }
1091 }
1092 }
1093 }
1094
1095 #[test]
1096 fn opaque_cropped_fast_path_matches_reference() {
1097 let dimensions = PixelDimensions::new(40, 24).unwrap();
1098 let sequence = opaque_rectangular_sequence(dimensions);
1099 for (crop, scale) in [
1100 (
1101 PixelRect::new(3, 2, 32, 16).unwrap(),
1102 IntegerScale::IDENTITY,
1103 ),
1104 (
1105 PixelRect::new(2, 2, 36, 20).unwrap(),
1106 IntegerScale::down(NonZeroU8::new(2).unwrap()).unwrap(),
1107 ),
1108 (
1109 PixelRect::new(4, 4, 32, 16).unwrap(),
1110 IntegerScale::down(NonZeroU8::new(4).unwrap()).unwrap(),
1111 ),
1112 ] {
1113 let parameters = NormalizationParameters::new(
1114 Rgb8::new(19, 37, 73),
1115 Some(crop),
1116 scale,
1117 ProcessingLimits::default(),
1118 );
1119 let optimized = normalize_sequence(&sequence, parameters).unwrap();
1120 let capacity = optimized.dimensions().pixel_count().unwrap() * 3;
1121 assert!(sequence.frames().iter().all(|frame| {
1122 can_use_opaque_full_frame_fast_path(
1123 frame,
1124 crop,
1125 optimized.dimensions(),
1126 scale,
1127 true,
1128 )
1129 }));
1130 let mut reference = optimized.clone();
1131 reference.frames = sequence
1132 .frames()
1133 .iter()
1134 .map(|frame| {
1135 normalize_frame_general(
1136 frame,
1137 crop,
1138 optimized.dimensions(),
1139 scale,
1140 parameters.background.channels().map(linear_channel),
1141 capacity,
1142 )
1143 })
1144 .collect::<Result<Vec<_>>>()
1145 .unwrap()
1146 .into_boxed_slice();
1147 assert_eq!(optimized, reference, "opaque crop scale {scale:?}");
1148 }
1149 }
1150
1151 fn opaque_rectangular_sequence(
1152 dimensions: PixelDimensions,
1153 ) -> FrameSequence<u8, u8, u8, Box<[u8]>> {
1154 let frames = (0_u8..5)
1155 .map(|frame_index| {
1156 let mut pixels = vec![0_u8; dimensions.rgba8_byte_len().unwrap()];
1157 for y in 0..dimensions.height() {
1158 for x in 0..dimensions.width() {
1159 let offset = ((y * dimensions.width() + x) * 4) as usize;
1160 pixels[offset..offset + 4].copy_from_slice(&[
1161 (x * 13 + y * 7 + u32::from(frame_index) * 19) as u8,
1162 (x * 5 + y * 17 + u32::from(frame_index) * 29 + x * y) as u8,
1163 (x * 23 + y * 3 + u32::from(frame_index) * 11 + x * y * 2) as u8,
1164 u8::MAX,
1165 ]);
1166 }
1167 }
1168 frame(frame_index, dimensions, pixels)
1169 })
1170 .collect();
1171 FrameSequence::new(
1172 frames,
1173 Vec::<Marker<u8>>::new(),
1174 Vec::<DeclaredGap<u8>>::new(),
1175 None,
1176 None,
1177 )
1178 .unwrap()
1179 }
1180
1181 #[test]
1182 fn opaque_full_frame_fast_path_selection_excludes_other_semantics() {
1183 let dimensions = PixelDimensions::new(2, 2).unwrap();
1184 let crop = PixelRect::new(0, 0, dimensions.width(), dimensions.height()).unwrap();
1185 let opaque = frame(
1186 1,
1187 dimensions,
1188 vec![
1189 255, 0, 0, 255, 0, 128, 255, 255, 32, 64, 96, 255, 200, 180, 160, 255,
1190 ],
1191 );
1192 assert!(can_use_opaque_full_frame_fast_path(
1193 &opaque,
1194 crop,
1195 dimensions,
1196 IntegerScale::IDENTITY,
1197 true,
1198 ));
1199 assert!(!can_use_opaque_full_frame_fast_path(
1200 &opaque,
1201 crop,
1202 dimensions,
1203 IntegerScale::IDENTITY,
1204 false,
1205 ));
1206 assert!(can_use_opaque_full_frame_fast_path(
1207 &opaque,
1208 PixelRect::new(1, 0, 1, 2).unwrap(),
1209 PixelDimensions::new(1, 2).unwrap(),
1210 IntegerScale::IDENTITY,
1211 true,
1212 ));
1213 assert!(!can_use_opaque_full_frame_fast_path(
1214 &opaque,
1215 crop,
1216 dimensions,
1217 IntegerScale::up(NonZeroU8::new(2).unwrap()).unwrap(),
1218 true,
1219 ));
1220 assert!(can_use_opaque_full_frame_fast_path(
1221 &opaque,
1222 crop,
1223 PixelDimensions::new(1, 1).unwrap(),
1224 IntegerScale::down(NonZeroU8::new(2).unwrap()).unwrap(),
1225 true,
1226 ));
1227
1228 let mut alpha_pixels = opaque.pixels().to_vec();
1229 alpha_pixels[3] = 127;
1230 let alpha = frame(2, dimensions, alpha_pixels);
1231 assert!(!can_use_opaque_full_frame_fast_path(
1232 &alpha,
1233 crop,
1234 dimensions,
1235 IntegerScale::IDENTITY,
1236 true,
1237 ));
1238 }
1239
1240 #[test]
1241 fn exact_alpha_and_scaling_kernels_are_stable() {
1242 let dimensions = PixelDimensions::new(2, 1).unwrap();
1243 let sequence = FrameSequence::new(
1244 vec![frame(1, dimensions, vec![255, 0, 0, 0, 255, 255, 255, 128])],
1245 Vec::<Marker<u8>>::new(),
1246 Vec::<DeclaredGap<u8>>::new(),
1247 None,
1248 None,
1249 )
1250 .unwrap();
1251 let normalized = normalize_sequence(
1252 &sequence,
1253 NormalizationParameters::new(
1254 Rgb8::new(0, 128, 0),
1255 None,
1256 IntegerScale::IDENTITY,
1257 ProcessingLimits::default(),
1258 ),
1259 )
1260 .unwrap();
1261 assert_eq!(
1262 normalized.frames()[0].linear_rgb16(),
1263 &[0, 14_146, 0, 32_896, 39_941, 32_896]
1264 );
1265
1266 let upscaled = normalize_sequence(
1267 &sequence,
1268 NormalizationParameters::new(
1269 Rgb8::new(0, 128, 0),
1270 Some(PixelRect::new(1, 0, 1, 1).unwrap()),
1271 IntegerScale::up(NonZeroU8::new(2).unwrap()).unwrap(),
1272 ProcessingLimits::default(),
1273 ),
1274 )
1275 .unwrap();
1276 assert_eq!(upscaled.dimensions(), PixelDimensions::new(2, 2).unwrap());
1277 assert!(
1278 upscaled.frames()[0]
1279 .linear_rgb16()
1280 .chunks_exact(3)
1281 .all(|pixel| pixel == [32_896, 39_941, 32_896])
1282 );
1283 }
1284
1285 #[test]
1286 fn downscale_requires_complete_analysis_boxes() {
1287 let dimensions = PixelDimensions::new(2, 2).unwrap();
1288 let pixels = [0, 0, 0, 255].repeat(4);
1289 let sequence = FrameSequence::new(
1290 vec![frame(1, dimensions, pixels)],
1291 Vec::<Marker<u8>>::new(),
1292 Vec::<DeclaredGap<u8>>::new(),
1293 Some(FrameRegion::new(PixelRect::new(0, 0, 1, 2).unwrap(), dimensions).unwrap()),
1294 None,
1295 )
1296 .unwrap();
1297 let error = normalize_sequence(
1298 &sequence,
1299 NormalizationParameters::new(
1300 Rgb8::new(0, 0, 0),
1301 None,
1302 IntegerScale::down(NonZeroU8::new(2).unwrap()).unwrap(),
1303 ProcessingLimits::default(),
1304 ),
1305 )
1306 .unwrap_err();
1307 assert_eq!(error.code, ErrorCode::EmptyAnalysisDomain);
1308 }
1309
1310 #[test]
1311 fn validates_scale_arithmetic_and_retained_bytes() {
1312 assert_eq!(
1313 IntegerScale::up(NonZeroU8::new(9).unwrap())
1314 .unwrap_err()
1315 .code,
1316 ErrorCode::InvalidScale
1317 );
1318 let huge = PixelRect::new(0, 0, u32::MAX / 2 + 1, 1).unwrap();
1319 assert_eq!(
1320 scaled_dimensions(huge, IntegerScale::up(NonZeroU8::new(2).unwrap()).unwrap())
1321 .unwrap_err()
1322 .code,
1323 ErrorCode::InvalidScale
1324 );
1325 assert_eq!(
1326 validate_resource_limits(
1327 usize::MAX,
1328 usize::MAX,
1329 true,
1330 ProcessingLimits::new(NonZeroUsize::MAX, NonZeroUsize::MAX, NonZeroUsize::MAX),
1331 )
1332 .unwrap_err()
1333 .code,
1334 ErrorCode::ResourceLimitExceeded
1335 );
1336 let error = validate_resource_limits(
1337 5,
1338 1,
1339 false,
1340 ProcessingLimits::new(
1341 NonZeroUsize::new(4).unwrap(),
1342 NonZeroUsize::new(8).unwrap(),
1343 NonZeroUsize::new(128).unwrap(),
1344 ),
1345 )
1346 .unwrap_err();
1347 assert!(error.message.contains("5"));
1348 assert!(error.message.contains("4"));
1349 }
1350}