1use super::{
2 FusedRequest, fused_predicates_rgba8_cg, is_opaque_ga8, is_opaque_ga16, is_opaque_rgba16,
3 scan_opacity_and_grayscale,
4};
5use core::fmt;
6use zenpixels::{
7 AlphaMode, ChannelOrder, ColorSpace, ExactDepth, ExactDepthError, F16Sample, FloatClaims,
8 PixelRect, PixelView, SampleClaims, SampleLayout, SampleType, SignalRange,
9};
10
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum SampleBounds {
15 #[default]
20 Format,
21 Nominal,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum SampleValidationError {
31 NonFiniteColor,
33 ColorOutOfRange,
35 AlphaOutOfRange,
37 NonOpaqueAlpha,
39}
40
41impl fmt::Display for SampleValidationError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 f.write_str(match self {
44 Self::NonFiniteColor => "non-finite color",
45 Self::ColorOutOfRange => "color outside nominal range",
46 Self::AlphaOutOfRange => "alpha outside its range",
47 Self::NonOpaqueAlpha => "stored alpha differs from maximum",
48 })
49 }
50}
51
52impl core::error::Error for SampleValidationError {}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub struct PixelCheckError {
57 reason: SampleValidationError,
58 pixel: PixelRect,
59}
60
61impl PixelCheckError {
62 #[must_use]
64 pub const fn reason(self) -> SampleValidationError {
65 self.reason
66 }
67
68 #[must_use]
70 pub const fn pixel(self) -> PixelRect {
71 self.pixel
72 }
73}
74
75impl fmt::Display for PixelCheckError {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 write!(
78 f,
79 "{} at pixel ({}, {})",
80 self.reason, self.pixel.x, self.pixel.y
81 )
82 }
83}
84
85impl core::error::Error for PixelCheckError {}
86
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum ClaimVerificationError {
91 ExactDepthMismatch(ExactDepth),
93 ExactDepthIncompatible(ExactDepthError),
95 NonOpaqueAlpha { row: u32 },
97 NonBinaryAlpha { row: u32 },
99 Float {
101 required: FloatClaims,
103 observed: FloatClaims,
105 },
106 NotGrayscale,
108}
109
110impl fmt::Display for ClaimVerificationError {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 match self {
113 Self::ExactDepthMismatch(depth) => write!(
114 f,
115 "samples are not exact on the required {:?} grid ({} color bits, {} alpha bits)",
116 depth.range(),
117 depth.color_bits(),
118 depth.alpha_bits(),
119 ),
120 Self::ExactDepthIncompatible(cause) => write!(f, "cannot verify exact depth ({cause})"),
121 Self::NonOpaqueAlpha { row } => {
122 write!(f, "stored alpha differs from maximum in row {row}")
123 }
124 Self::NonBinaryAlpha { row } => {
125 write!(f, "stored alpha is neither zero nor maximum in row {row}")
126 }
127 Self::Float { required, observed } => {
128 f.write_str("unproven float properties")?;
129 let mut separator = ": ";
130 for (fact, label) in [
131 (FloatClaims::NO_NAN, "no NaN"),
132 (FloatClaims::NO_INFINITE, "no infinity"),
133 (FloatClaims::NO_SUBNORMALS, "no subnormals"),
134 (FloatClaims::NON_NEGATIVE, "non-negative"),
135 (FloatClaims::POSITIVE, "positive"),
136 (FloatClaims::AT_MOST_ONE, "at most one"),
137 ] {
138 if required.contains(fact) && !observed.contains(fact) {
139 write!(f, "{separator}{label}")?;
140 separator = ", ";
141 }
142 }
143 Ok(())
144 }
145 Self::NotGrayscale => f.write_str("could not verify grayscale samples"),
146 }
147 }
148}
149
150impl core::error::Error for ClaimVerificationError {
151 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
152 match self {
153 Self::ExactDepthIncompatible(cause) => Some(cause),
154 _ => None,
155 }
156 }
157}
158
159type RowError = (u32, SampleValidationError);
160
161#[cold]
162fn locate_error(
163 view: &PixelView<'_>,
164 bounds: SampleBounds,
165 (y, reason): RowError,
166) -> PixelCheckError {
167 let mut x = 0;
168 let mut width = view.width();
169 while width > 1 {
170 let half = width / 2;
171 let left = view
172 .crop(PixelRect::new(x, y, half, 1))
173 .expect("subregion stays inside the failing row");
174 let same_failure = validate_rows(&left, bounds).is_err_and(|(_, found)| found == reason);
178 if same_failure {
179 width = half;
180 } else {
181 x += half;
182 width -= half;
183 }
184 }
185 PixelCheckError {
186 reason,
187 pixel: PixelRect::new(x, y, 1, 1),
188 }
189}
190
191pub(super) fn check_samples(
192 view: &PixelView<'_>,
193 bounds: SampleBounds,
194) -> Result<(), PixelCheckError> {
195 validate_rows(view, bounds).map_err(|error| locate_error(view, bounds, error))
196}
197
198fn validate_rows(view: &PixelView<'_>, bounds: SampleBounds) -> Result<(), RowError> {
199 let color = view.format().color();
200 let layout = view.format().layout();
201 let alpha = color.alpha();
202 if layout.sample().is_float() {
203 let check_color = !matches!(color, ColorSpace::Untagged { .. });
204 let nominal = bounds == SampleBounds::Nominal
205 && matches!(
206 color,
207 ColorSpace::Rgb { .. }
208 | ColorSpace::RgbCustom { .. }
209 | ColorSpace::Gray { .. }
210 | ColorSpace::Cmyk { .. }
211 );
212 return match layout.sample() {
213 SampleType::F16 => {
214 validate_float::<F16Sample>(view, check_color, nominal, |v| f64::from(v.to_f32()))
215 }
216 SampleType::F32 => validate_float::<f32>(view, check_color, nominal, f64::from),
217 SampleType::F64 => validate_float::<f64>(view, check_color, nominal, |v| v),
218 _ => unreachable!("floating-point layout"),
219 };
220 }
221
222 if alpha == AlphaMode::Opaque {
223 verify_alpha(view, true).map_err(|y| (y, SampleValidationError::NonOpaqueAlpha))?;
224 } else if layout.order().has_alpha_slot() && layout.sample().is_signed() {
225 let alpha_offset = layout.bytes_per_pixel() - layout.sample().byte_size();
226 let sign = 1u64 << (layout.sample().bits() - 1);
227 for y in 0..view.height() {
228 if view
229 .row(y)
230 .chunks_exact(layout.bytes_per_pixel())
231 .any(|pixel| read_word(&pixel[alpha_offset..]) & sign != 0)
232 {
233 return Err((y, SampleValidationError::AlphaOutOfRange));
234 }
235 }
236 }
237
238 if bounds == SampleBounds::Nominal && color.range() == Some(SignalRange::Narrow) {
239 validate_narrow(view)?;
240 }
241 Ok(())
242}
243
244fn validate_float<T: bytemuck::Pod>(
245 view: &PixelView<'_>,
246 check_color: bool,
247 nominal: bool,
248 value: impl Fn(T) -> f64,
249) -> Result<(), RowError> {
250 let layout = view.format().layout();
251 let alpha = view.format().color().alpha();
252 let has_alpha = layout.order().has_alpha_slot();
253 if !check_color && !has_alpha {
254 return Ok(());
255 }
256 let channels = layout.channels();
257 let color_channels = channels - usize::from(has_alpha || layout.order().has_padding_slot());
258 for y in 0..view.height() {
259 let row: &[T] = bytemuck::cast_slice(view.row(y));
260 if color_channels == channels {
261 let valid = if nominal {
264 row.iter().fold(true, |ok, &sample| {
265 ok & (0.0..=1.0).contains(&value(sample))
266 })
267 } else {
268 row.iter()
269 .fold(true, |ok, &sample| ok & value(sample).is_finite())
270 };
271 if valid {
272 continue;
273 }
274 }
275 for pixel in row.chunks_exact(channels) {
276 if check_color {
277 for &sample in &pixel[..color_channels] {
278 let v = value(sample);
279 if !v.is_finite() {
280 return Err((y, SampleValidationError::NonFiniteColor));
281 }
282 if nominal && !(0.0..=1.0).contains(&v) {
283 return Err((y, SampleValidationError::ColorOutOfRange));
284 }
285 }
286 }
287 if has_alpha {
288 let v = value(pixel[color_channels]);
289 if !(0.0..=1.0).contains(&v) {
290 return Err((y, SampleValidationError::AlphaOutOfRange));
291 }
292 if alpha == AlphaMode::Opaque && v != 1.0 {
293 return Err((y, SampleValidationError::NonOpaqueAlpha));
294 }
295 }
296 }
297 }
298 Ok(())
299}
300
301fn validate_narrow(view: &PixelView<'_>) -> Result<(), RowError> {
302 let layout = view.format().layout();
303 let sample = layout.sample();
304 let packing = layout.packing();
305 let color_channels = layout.channels()
306 - usize::from(layout.order().has_alpha_slot() || layout.order().has_padding_slot());
307 let mut bounds = [(0u32, 0u32); 4];
308 for (c, range) in bounds[..color_channels].iter_mut().enumerate() {
309 let max = packing.max_code(sample, c);
310 let bits = 32 - max.leading_zeros();
311 let up = bits.saturating_sub(8);
312 let down = 8u32.saturating_sub(bits);
313 *range = (((16 << up) >> down).min(max), (235 << up).min(max));
315 }
316 for y in 0..view.height() {
317 for pixel in view.row(y).chunks_exact(layout.bytes_per_pixel()) {
318 for (c, &(lo, hi)) in bounds[..color_channels].iter().enumerate() {
319 let code = integer_code(layout, pixel, c);
320 if code < u64::from(lo) || code > u64::from(hi) {
321 return Err((y, SampleValidationError::ColorOutOfRange));
322 }
323 }
324 }
325 }
326 Ok(())
327}
328
329fn verify_alpha(view: &PixelView<'_>, opaque_only: bool) -> Result<(), u32> {
330 let layout = view.format().layout();
331 if !layout.order().has_alpha_slot() {
332 return Ok(());
333 }
334 let alpha_index = layout.channels() - 1;
335 let sample = layout.sample();
336 let packing = layout.packing();
337 let want = if packing.is_full() {
338 match sample {
339 SampleType::F16 => u64::from(F16Sample::ONE.to_bits()),
340 SampleType::F32 => u64::from(1.0f32.to_bits()),
341 SampleType::F64 => 1.0f64.to_bits(),
342 _ => u64::MAX >> (64 - sample.bits() + u8::from(sample.is_signed())),
343 }
344 } else {
345 u64::from(packing.max_code(sample, alpha_index))
346 };
347 let signed_zero = if sample.is_float() {
348 1u64 << (sample.bits() - 1)
349 } else {
350 0
351 };
352 let row_matches = |row: &[u8]| {
353 if opaque_only && packing.is_full() {
354 match (sample, layout.order()) {
355 (SampleType::U8, ChannelOrder::Rgba | ChannelOrder::Bgra) => {
356 return fused_predicates_rgba8_cg(
357 row,
358 FusedRequest {
359 check_opaque: true,
360 check_grayscale: false,
361 },
362 )
363 .is_opaque;
364 }
365 (SampleType::U8, ChannelOrder::GrayAlpha) => return is_opaque_ga8(row),
366 (SampleType::U16, ChannelOrder::Rgba | ChannelOrder::Bgra) => {
367 return is_opaque_rgba16(bytemuck::cast_slice(row));
368 }
369 (SampleType::U16, ChannelOrder::GrayAlpha) => {
370 return is_opaque_ga16(bytemuck::cast_slice(row));
371 }
372 _ => {}
373 }
374 }
375 row.chunks_exact(layout.bytes_per_pixel()).all(|pixel| {
376 let code = integer_code(layout, pixel, alpha_index);
377 code == want || (!opaque_only && (code == 0 || code == signed_zero))
378 })
379 };
380 for y in 0..view.height() {
381 if !row_matches(view.row(y)) {
382 return Err(y);
383 }
384 }
385 Ok(())
386}
387
388fn integer_code(layout: SampleLayout, pixel: &[u8], channel: usize) -> u64 {
389 let packing = layout.packing();
390 let sample = layout.sample();
391 let size = sample.byte_size();
392 let word = if packing.is_packed_word() {
393 read_word(pixel)
394 } else {
395 read_word(&pixel[channel * size..(channel + 1) * size])
396 };
397 if packing.is_full() {
398 word
399 } else {
400 u64::from(packing.extract_code(sample, channel, word as u32))
401 }
402}
403
404fn read_word(bytes: &[u8]) -> u64 {
405 match *bytes {
406 [a] => u64::from(a),
407 [a, b] => u64::from(u16::from_ne_bytes([a, b])),
408 [a, b, c, d] => u64::from(u32::from_ne_bytes([a, b, c, d])),
409 [a, b, c, d, e, f, g, h] => u64::from_ne_bytes([a, b, c, d, e, f, g, h]),
410 _ => unreachable!("validated sample layout"),
411 }
412}
413
414pub(super) fn verify_claims(
415 view: &PixelView<'_>,
416 required: SampleClaims,
417) -> Result<(), ClaimVerificationError> {
418 if let Some(depth) = required.depth {
419 match depth.holds_for(view) {
420 Ok(true) => {}
421 Ok(false) => return Err(ClaimVerificationError::ExactDepthMismatch(depth)),
422 Err(error) => return Err(ClaimVerificationError::ExactDepthIncompatible(error)),
423 }
424 }
425 if required.all_opaque || required.binary_alpha {
426 verify_alpha(view, required.all_opaque).map_err(|row| {
427 if required.all_opaque {
428 ClaimVerificationError::NonOpaqueAlpha { row }
429 } else {
430 ClaimVerificationError::NonBinaryAlpha { row }
431 }
432 })?;
433 }
434 if required.float != FloatClaims::NONE {
435 let observed = view.measure_float_claims();
436 if !observed.contains(required.float) {
437 return Err(ClaimVerificationError::Float {
438 required: required.float,
439 observed,
440 });
441 }
442 }
443 if required.all_grayscale && !scan_opacity_and_grayscale(view, false).1 {
444 return Err(ClaimVerificationError::NotGrayscale);
445 }
446 Ok(())
447}