pub(crate) mod iso15415;
pub(crate) mod margin;
pub(crate) mod structural;
pub(crate) mod uec;
pub(crate) mod warp;
use web_time::Instant;
use crate::engine::{self, content::ContentKey};
use crate::error::Result;
use crate::input::LumaImage;
use crate::ladder::{CancelToken, MergedDetection, ScoreDepth};
use crate::report::{AxisScore, EcLevel, Grade, Hint, Score, StressAxis, Symbology};
use crate::transform;
type RampBuilder<'a> = &'a dyn Fn(&LumaImage, usize) -> LumaImage;
type RampRefiner<'a> = &'a dyn Fn(&LumaImage, usize) -> (LumaImage, String);
const STRESS_BASE_SIDE: u32 = 512;
const LINEAR_BASE_SIDE_CAP: u32 = 2048;
fn stress_base_side(width: u32, height: u32, symbology: Symbology) -> u32 {
if !symbology.is_linear() {
return STRESS_BASE_SIDE;
}
let longest = u64::from(width.max(height));
let shortest = u64::from(width.min(height).max(1));
let budget = u64::from(STRESS_BASE_SIDE) * u64::from(STRESS_BASE_SIDE);
let side = (budget * longest / shortest).isqrt();
u32::try_from(side)
.unwrap_or(LINEAR_BASE_SIDE_CAP)
.clamp(STRESS_BASE_SIDE, LINEAR_BASE_SIDE_CAP)
}
fn ramp_side(side: u32, unit: u32) -> u32 {
u32::try_from(u64::from(side) * u64::from(unit) / u64::from(STRESS_BASE_SIDE)).unwrap_or(side)
}
#[cfg(test)]
thread_local! {
static STRESS_BASES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
pub(crate) static JUDGMENT_FAULT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
const WEIGHTS: [(StressAxis, u32); 6] = [
(StressAxis::Resolution, 22),
(StressAxis::Blur, 18),
(StressAxis::Contrast, 15),
(StressAxis::Perspective, 20),
(StressAxis::Rotation, 10),
(StressAxis::Lighting, 15),
];
const FINDER_INTEGRITY_FLOOR: f32 = 0.5;
const FINDER_DAMAGE_CAP: u8 = 40;
const QUIET_ZONE_CAP: u8 = 60;
const UEC_HEALTHY_MARGIN: f32 = 0.5;
const UEC_ZERO_MARGIN_CAP: u8 = 40;
fn uec_margin_cap(margin: f32) -> u8 {
if margin >= UEC_HEALTHY_MARGIN {
return 100;
}
let span = f32::from(100 - UEC_ZERO_MARGIN_CAP);
let cap = f32::from(UEC_ZERO_MARGIN_CAP) + (margin.max(0.0) / UEC_HEALTHY_MARGIN) * span;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "cap in 40..=100"
)]
let cap = cap.round() as u8;
cap
}
#[cfg(test)]
fn detections_match(found: &[engine::RawDetection], expected: &ContentKey) -> bool {
found.iter().any(|d| expected.admits(d))
}
#[cfg(test)]
fn cell_decode(img: &LumaImage, symbology: crate::report::Symbology) -> engine::EngineOutcome {
engine::decode_filtered(img, engine::FormatFilter::Only(symbology))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Variant {
Plain,
Otsu,
Rung,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Pair {
variant: Variant,
reader: crate::report::EngineKind,
}
impl Pair {
fn slot(self) -> usize {
let variant = match self.variant {
Variant::Otsu => 0,
Variant::Plain => 1,
Variant::Rung => 2,
};
variant * 2 + usize::from(self.reader == crate::report::EngineKind::Rqrr)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Trial {
read: bool,
cost: u8,
}
#[derive(Debug, Clone, Copy)]
struct Schedule {
first: crate::report::EngineKind,
trials: [Option<Trial>; 6],
floor: Option<u8>,
}
impl Schedule {
const FAILED: u8 = 2;
fn new() -> Self {
Self {
first: crate::report::EngineKind::Rxing,
trials: [None; 6],
floor: None,
}
}
fn class_of(elapsed: std::time::Duration) -> u8 {
let bits = u128::BITS - elapsed.as_micros().leading_zeros();
u8::try_from(bits).unwrap_or(u8::MAX)
}
fn order(&self, probe: CellProbe) -> Vec<Pair> {
let readers = engine::probe_readers(probe.symbology);
let mut pairs = Vec::with_capacity(6);
for variant in [Variant::Otsu, Variant::Plain, Variant::Rung] {
if variant == Variant::Rung && probe.rung.is_none() {
continue;
}
let ordered = std::iter::once(self.first)
.filter(|reader| readers.contains(reader))
.chain(readers.iter().copied().filter(|r| *r != self.first));
for reader in ordered {
pairs.push(Pair { variant, reader });
}
}
pairs.sort_by_key(|pair| match self.trials[pair.slot()] {
Some(Trial { read: true, cost }) => (cost, 0u8),
None => (self.floor.map_or(0, |floor| floor.saturating_add(1)), 1),
Some(Trial { read: false, cost }) => (cost.saturating_add(Self::FAILED), 2),
});
pairs
}
fn record(&mut self, pair: Pair, read: bool, elapsed: std::time::Duration) {
let cost = Self::class_of(elapsed);
self.trials[pair.slot()] = Some(Trial { read, cost });
if read {
self.floor = Some(self.floor.map_or(cost, |floor| floor.min(cost)));
}
}
}
pub(crate) struct Bound<'a> {
cancel: &'a CancelToken,
deadline: Option<Instant>,
quota: Option<u32>,
spent: u32,
cut: bool,
panics: u8,
schedule: Schedule,
}
impl<'a> Bound<'a> {
pub(crate) fn new(cancel: &'a CancelToken, deadline: Option<Instant>) -> Self {
Self {
cancel,
deadline,
quota: None,
spent: 0,
cut: false,
panics: 0,
schedule: Schedule::new(),
}
}
fn lead_with(&mut self, engines: &[crate::report::EngineKind]) {
if engines.contains(&crate::report::EngineKind::Rqrr) {
self.schedule.first = crate::report::EngineKind::Rqrr;
}
}
#[cfg(test)]
fn with_quota(self, units: u32) -> Self {
Self {
quota: Some(units),
..self
}
}
#[cfg(test)]
fn spent(&self) -> u32 {
self.spent
}
pub(crate) fn admit(&mut self) -> Result<bool> {
if self.cancel.is_cancelled() {
return Err(crate::error::ScanError::Cancelled);
}
if self.deadline.is_some_and(|d| Instant::now() >= d)
|| self.quota.is_some_and(|units| self.spent >= units)
{
self.cut = true;
return Ok(false);
}
self.spent += 1;
Ok(true)
}
pub(crate) fn cut(&self) -> bool {
self.cut
}
pub(crate) fn panics(&self) -> u8 {
self.panics
}
fn reads(
&mut self,
img: &LumaImage,
symbology: crate::report::Symbology,
pair: Pair,
expected: &ContentKey,
) -> bool {
let started = Instant::now();
let probe = engine::probe(img, symbology, pair.reader, &|read| expected.admits(read));
self.schedule
.record(pair, probe.accepted, started.elapsed());
self.panics = self.panics.saturating_add(probe.panics);
probe.accepted
}
}
pub(crate) fn plans_cells(depth: ScoreDepth, skip: &[StressAxis]) -> bool {
!depth_indices(depth).is_empty() && !WEIGHTS.iter().all(|(axis, _)| skip.contains(axis))
}
#[derive(Debug)]
pub(crate) enum Judgment {
Complete(Score, Vec<Hint>),
NoAxes,
Interrupted,
}
pub(crate) enum Calibrated {
Class(CellProbe),
Undecodable,
Interrupted,
}
#[derive(Clone, Copy)]
pub(crate) struct CellProbe {
pub(crate) rung: Option<crate::ladder::Rung>,
pub(crate) symbology: crate::report::Symbology,
}
impl CellProbe {
#[cfg(test)]
pub(crate) fn calibrate(
base: &LumaImage,
expected: &ContentKey,
symbology: crate::report::Symbology,
) -> Option<Self> {
let never = CancelToken::new();
let mut unbounded = Bound::new(&never, None);
match Self::calibrate_within(base, expected, symbology, &mut unbounded) {
Ok(Calibrated::Class(probe)) => Some(probe),
Ok(Calibrated::Undecodable | Calibrated::Interrupted) | Err(_) => None,
}
}
#[cfg(test)]
fn calibrate_within(
base: &LumaImage,
expected: &ContentKey,
symbology: crate::report::Symbology,
bound: &mut Bound<'_>,
) -> Result<Calibrated> {
if !bound.admit()? {
return Ok(Calibrated::Interrupted);
}
Self::calibrate_admitted(base, expected, symbology, bound)
}
pub(crate) fn calibrate_admitted(
base: &LumaImage,
expected: &ContentKey,
symbology: crate::report::Symbology,
bound: &mut Bound<'_>,
) -> Result<Calibrated> {
let shallow = Self {
rung: None,
symbology,
};
if cell_passes(base, expected, shallow, bound) {
return Ok(Calibrated::Class(shallow));
}
for rung in crate::ladder::DEEP_RUNGS {
if !bound.admit()? {
return Ok(Calibrated::Interrupted);
}
let boosted = rung.apply(base);
let class = Self {
rung: Some(rung),
symbology,
};
let pairs = bound.schedule.order(class);
for pair in pairs
.into_iter()
.filter(|pair| pair.variant == Variant::Rung)
{
if bound.reads(&boosted, symbology, pair, expected) {
return Ok(Calibrated::Class(class));
}
}
}
Ok(Calibrated::Undecodable)
}
}
pub(crate) fn cell_passes(
img: &LumaImage,
expected: &ContentKey,
probe: CellProbe,
bound: &mut Bound<'_>,
) -> bool {
let mut otsu: Option<LumaImage> = None;
let mut boosted: Option<LumaImage> = None;
for pair in bound.schedule.order(probe) {
let image = match (pair.variant, probe.rung) {
(Variant::Plain, _) => img,
(Variant::Otsu, _) => otsu.get_or_insert_with(|| transform::otsu_threshold(img)),
(Variant::Rung, Some(rung)) => boosted.get_or_insert_with(|| rung.apply(img)),
(Variant::Rung, None) => continue,
};
if bound.reads(image, probe.symbology, pair, expected) {
return true;
}
}
false
}
fn depth_indices(depth: ScoreDepth) -> &'static [usize] {
match depth {
ScoreDepth::Off => &[],
ScoreDepth::Reduced => &[1, 3],
ScoreDepth::Full => &[0, 1, 2, 3, 4],
}
}
fn lighting_indices(depth: ScoreDepth) -> &'static [usize] {
match depth {
ScoreDepth::Off => &[],
ScoreDepth::Reduced => &[1, 2],
ScoreDepth::Full => &[0, 1, 2, 3, 4],
}
}
fn run_ramp(
base: &LumaImage,
expected: &ContentKey,
bound: &mut Bound<'_>,
probe: CellProbe,
indices: &[usize],
build: impl Fn(&LumaImage, usize) -> LumaImage,
) -> Result<Option<(u8, Option<usize>)>> {
let mut passed = 0u8;
for &i in indices {
if !bound.admit()? {
return Ok(None);
}
let cell = build(base, i);
if !cell_passes(&cell, expected, probe, bound) {
return Ok(Some((passed, Some(i))));
}
passed += 1;
}
Ok(Some((passed, None)))
}
fn cell_label(axis: StressAxis, i: usize) -> &'static str {
match axis {
StressAxis::Resolution => ["358px", "256px", "179px", "128px", "90px"][i.min(4)],
StressAxis::Blur => ["blur 0.5", "blur 1.0", "blur 1.5", "blur 2.0", "blur 2.5"][i.min(4)],
StressAxis::Contrast => [
"contrast 70%",
"contrast 55%",
"contrast 40%",
"contrast 30%",
"contrast 20%",
][i.min(4)],
StressAxis::Perspective => ["10°", "18°", "26°", "34°", "42°"][i.min(4)],
StressAxis::Rotation => ["10°", "20°", "30°", "40°", "50°"][i.min(4)],
StressAxis::Lighting => [
"soft shadow",
"hard shadow",
"glare",
"overexposure",
"underexposure",
][i.min(4)],
}
}
fn knee_label(axis: StressAxis, i: usize, resolution_sides: &[u32; 5]) -> String {
match axis {
StressAxis::Resolution => format!("{}px", resolution_sides[i.min(4)]),
_ => cell_label(axis, i).to_owned(),
}
}
fn refine_knee(
base: &LumaImage,
expected: &ContentKey,
probe: CellProbe,
knee: (usize, &str),
bound: &mut Bound<'_>,
refine: RampRefiner<'_>,
) -> Result<Option<String>> {
if !bound.admit()? {
return Ok(None);
}
let (knee, knee_label) = knee;
let (cell, label) = refine(base, knee);
Ok(Some(if cell_passes(&cell, expected, probe, bound) {
knee_label.to_owned()
} else {
label
}))
}
fn run_lighting(
base: &LumaImage,
expected: &ContentKey,
depth: ScoreDepth,
bound: &mut Bound<'_>,
probe: CellProbe,
) -> Result<Option<AxisScore>> {
#[allow(
clippy::cast_precision_loss,
reason = "image dimensions bounded by Limits::max_dimension (lint presence varies by build shape)"
)]
let (cx, cy, radius) = (
base.width() as f32 * 0.5,
base.height() as f32 * 0.5,
base.width().min(base.height()) as f32 * 0.18,
);
let lighting_cells: [&dyn Fn(&LumaImage) -> LumaImage; 5] = [
&|b| warp::shadow_gradient(b, 0.4),
&|b| warp::shadow_gradient(b, 0.7),
&|b| warp::glare_blob(b, cx, cy, radius),
&|b| warp::exposure(b, 60),
&|b| warp::exposure(b, -60),
];
let lighting_picks = lighting_indices(depth);
let mut lighting_passed = 0u8;
let mut first_failed = None;
for &i in lighting_picks {
if !bound.admit()? {
return Ok(None);
}
if cell_passes(&lighting_cells[i](base), expected, probe, bound) {
lighting_passed += 1;
} else if first_failed.is_none() {
first_failed = Some(i);
}
}
Ok(Some(AxisScore {
axis: StressAxis::Lighting,
passed: lighting_passed,
total: u8::try_from(lighting_picks.len()).unwrap_or(u8::MAX),
failed_at: first_failed.map(|i| cell_label(StressAxis::Lighting, i).to_owned()),
refined_failed_at: None,
}))
}
fn run_axes(
base: &LumaImage,
expected: &ContentKey,
depth: ScoreDepth,
skip: &[StressAxis],
bound: &mut Bound<'_>,
probe: CellProbe,
) -> Result<Option<Vec<AxisScore>>> {
let unit = base.width().max(base.height()).max(STRESS_BASE_SIDE);
let resolution_sides: [u32; 5] = [358, 256, 179, 128, 90].map(|side| ramp_side(side, unit));
let blur_sigmas: [f32; 5] = [0.5, 1.0, 1.5, 2.0, 2.5];
let contrast_factors: [f32; 5] = [0.7, 0.55, 0.4, 0.3, 0.2];
let tilt_degrees: [f32; 5] = [10.0, 18.0, 26.0, 34.0, 42.0];
let rotation_degrees: [f32; 5] = [10.0, 20.0, 30.0, 40.0, 50.0];
let indices = depth_indices(depth);
let mut axes = Vec::with_capacity(6);
let mid = |arr: &[f32; 5], i: usize, unstressed: f32| -> f32 {
f32::midpoint(if i == 0 { unstressed } else { arr[i - 1] }, arr[i])
};
let ramps: [(StressAxis, RampBuilder<'_>, RampRefiner<'_>); 5] = [
(
StressAxis::Resolution,
&|b, i| transform::downscale_to(b, resolution_sides[i]),
&|b, i| {
let side = u32::midpoint(
if i == 0 {
unit
} else {
resolution_sides[i - 1]
},
resolution_sides[i],
);
(transform::downscale_to(b, side), format!("{side}px"))
},
),
(
StressAxis::Blur,
&|b, i| transform::gaussian_blur(b, blur_sigmas[i]),
&|b, i| {
let sigma = mid(&blur_sigmas, i, 0.0);
(transform::gaussian_blur(b, sigma), format!("blur {sigma}"))
},
),
(
StressAxis::Contrast,
&|b, i| transform::contrast_boost(b, contrast_factors[i], 1.0),
&|b, i| {
let factor = mid(&contrast_factors, i, 1.0);
(
transform::contrast_boost(b, factor, 1.0),
format!("contrast {:.0}%", factor * 100.0),
)
},
),
(
StressAxis::Perspective,
&|b, i| warp::perspective_tilt(b, tilt_degrees[i]),
&|b, i| {
let deg = mid(&tilt_degrees, i, 0.0);
(warp::perspective_tilt(b, deg), format!("{deg}\u{b0}"))
},
),
(
StressAxis::Rotation,
&|b, i| warp::rotate(b, rotation_degrees[i]),
&|b, i| {
let deg = mid(&rotation_degrees, i, 0.0);
(warp::rotate(b, deg), format!("{deg}\u{b0}"))
},
),
];
let mut knees = Vec::new();
for (axis, build, refine) in ramps {
if skip.contains(&axis) {
continue; }
let Some((passed, knee)) = run_ramp(base, expected, bound, probe, indices, build)? else {
return Ok(None);
};
if let Some(i) = knee {
knees.push((axes.len(), i, refine));
}
axes.push(AxisScore {
axis,
passed,
total: u8::try_from(indices.len()).unwrap_or(u8::MAX),
failed_at: knee.map(|i| knee_label(axis, i, &resolution_sides)),
refined_failed_at: None,
});
}
if !skip.contains(&StressAxis::Lighting) {
let Some(lighting) = run_lighting(base, expected, depth, bound, probe)? else {
return Ok(None);
};
axes.push(lighting);
}
if matches!(depth, ScoreDepth::Full) {
for (slot, knee, refine) in knees {
if let Some(entry) = axes.get_mut(slot) {
let label = entry.failed_at.clone().unwrap_or_default();
entry.refined_failed_at =
refine_knee(base, expected, probe, (knee, &label), bound, refine)?;
}
}
}
Ok(Some(axes))
}
fn compose(
axes: Vec<AxisScore>,
structural: Option<crate::report::StructuralReport>,
uec: Option<crate::report::UecReport>,
publish_uec: bool,
iso15415: Option<crate::report::Iso15415Report>,
detection: &MergedDetection,
) -> (Score, Vec<Hint>) {
let mut weighted = 0u32;
let mut weight_run = 0u32;
for score in &axes {
let weight = WEIGHTS
.iter()
.find(|(axis, _)| *axis == score.axis)
.map_or(0, |(_, w)| *w);
weight_run += weight;
if score.total > 0 {
weighted += weight * u32::from(score.passed) * 100 / u32::from(score.total);
}
}
let mut value = u8::try_from((weighted / weight_run.max(1)).min(100)).unwrap_or(100);
let mut hints = Vec::new();
if let Some(s) = &structural {
let weakest = s
.finder_integrity
.iter()
.enumerate()
.min_by(|a, b| a.1.total_cmp(b.1))
.map(|(i, v)| (i, *v));
if let Some((corner, integrity)) = weakest
&& integrity < FINDER_INTEGRITY_FLOOR
{
value = value.min(FINDER_DAMAGE_CAP);
#[expect(clippy::cast_possible_truncation, reason = "corner in 0..3")]
hints.push(Hint::FixFinderPattern {
corner: corner as u8,
});
}
if !s.quiet_zone_ok {
value = value.min(QUIET_ZONE_CAP);
hints.push(Hint::RestoreQuietZone);
}
}
let pre_margin_cap = value;
if let Some(u) = &uec {
value = value.min(uec_margin_cap(u.margin));
}
let uec = uec.filter(|_| publish_uec);
let fraction = |axis: StressAxis| -> Option<(u8, u8)> {
axes.iter()
.find(|a| a.axis == axis)
.map(|a| (a.passed, a.total))
};
if let Some((p, t)) = fraction(StressAxis::Contrast)
&& t > 0
&& u32::from(p) * 100 / u32::from(t) <= 40
{
hints.push(Hint::IncreaseContrast);
}
if let Some((p, t)) = fraction(StressAxis::Resolution)
&& t > 0
&& u32::from(p) * 100 / u32::from(t) <= 40
{
hints.push(Hint::EnlargeModules);
}
if let Some((p, t)) = fraction(StressAxis::Blur)
&& t > 0
&& p == 0
{
hints.push(Hint::ReduceArtTexture);
}
let thin_margin = uec.is_some_and(|u| {
matches!(
u.grade,
crate::report::UecGrade::D | crate::report::UecGrade::F
)
});
if let Some(current) = detection.ec
&& current < EcLevel::H
&& (pre_margin_cap < 70 || thin_margin)
{
hints.push(Hint::RaiseErrorCorrection { current });
}
if let Some(u) = &uec
&& u.margin <= 0.0
{
hints.push(Hint::LowCorrectionMargin {
errors: u.worst_block_errors,
capacity: u.worst_block_capacity,
});
}
let score = Score {
value,
grade: Grade::from_value(value),
weights_run: u8::try_from(weight_run.min(100)).unwrap_or(100),
axes,
structural,
uec,
iso15415,
};
(score, hints)
}
pub(crate) fn evaluate(
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
depth: ScoreDepth,
skip: &[StressAxis],
skip_checks: &[crate::ladder::ScoreCheck],
bound: &mut Bound<'_>,
) -> Result<Option<(Score, Vec<Hint>)>> {
Ok(
match judge(luma, detection, key, depth, skip, skip_checks, bound)? {
Judgment::Complete(score, hints) => Some((score, hints)),
Judgment::NoAxes | Judgment::Interrupted => None,
},
)
}
pub(crate) fn judge(
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
depth: ScoreDepth,
skip: &[StressAxis],
skip_checks: &[crate::ladder::ScoreCheck],
bound: &mut Bound<'_>,
) -> Result<Judgment> {
if !plans_cells(depth, skip) {
return Ok(Judgment::NoAxes);
}
if !bound.admit()? {
return Ok(Judgment::Interrupted);
}
#[cfg(test)]
STRESS_BASES.with(|built| built.set(built.get() + 1));
#[cfg(test)]
assert!(
!JUDGMENT_FAULT.with(std::cell::Cell::get),
"injected judgment fault"
);
let base = transform::downscale_to(
luma,
stress_base_side(luma.width(), luma.height(), detection.symbology),
);
bound.lead_with(&detection.engines);
let probe = match CellProbe::calibrate_admitted(&base, key, detection.symbology, bound)? {
Calibrated::Class(probe) => probe,
Calibrated::Undecodable => CellProbe {
rung: None,
symbology: detection.symbology,
},
Calibrated::Interrupted => return Ok(Judgment::Interrupted),
};
let Some(axes) = run_axes(&base, key, depth, skip, bound, probe)? else {
return Ok(Judgment::Interrupted);
};
let photometric_view = detection
.photometric_inverted
.then(|| transform::invert(luma));
let sample_luma = photometric_view.as_ref().unwrap_or(luma);
let structural = match (detection.corners, detection.version) {
(Some(corners), Some(version)) => structural::check(sample_luma, corners, version),
_ => None,
};
let publish_uec = !skip_checks.contains(&crate::ladder::ScoreCheck::Uec);
let skip_iso = skip_checks.contains(&crate::ladder::ScoreCheck::Iso15415);
let source = if detection
.engines
.contains(&crate::report::EngineKind::Rescue)
{
uec::Stream::Rescued
} else {
uec::Stream::Decoded
};
let uec_report = match (
&detection.masked_stream,
detection.version,
detection.ec,
detection.mask,
) {
(Some(stream), Some(version), Some(ec), Some(mask)) => {
uec::compute(&stream.bits, stream.bit_len, version, ec, mask, source)
}
_ => None,
};
let iso = if skip_iso {
None
} else {
match (detection.corners, detection.version, &structural) {
(Some(corners), Some(version), Some(s)) => {
iso15415::compute(sample_luma, corners, version, s, uec_report.as_ref()).map(
|mut card| {
if !publish_uec {
card.unused_error_correction = None;
}
card
},
)
}
_ => None,
}
};
let (score, hints) = compose(axes, structural, uec_report, publish_uec, iso, detection);
Ok(Judgment::Complete(score, hints))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::input::{ImageInput, Limits};
use crate::ladder::{self, ScanConfig};
use crate::transform::normalize;
#[test]
fn a_linear_base_keeps_the_pixel_count_of_the_square_base() {
assert_eq!(stress_base_side(2000, 2000, Symbology::Code128), 512);
for other in Symbology::ALL.into_iter().filter(|s| !s.is_linear()) {
assert_eq!(stress_base_side(1600, 400, other), 512, "{other:?}");
}
assert_eq!(stress_base_side(4000, 1000, Symbology::Ean13), 1024);
assert_eq!(stress_base_side(1000, 4000, Symbology::Ean13), 1024);
assert!(stress_base_side(1032, 240, Symbology::Code128) >= 1032);
assert!(stress_base_side(516, 121, Symbology::Code128) >= 516);
assert_eq!(stress_base_side(60_000, 30, Symbology::Code128), 2048);
assert_eq!(stress_base_side(u32::MAX, 1, Symbology::Itf), 2048);
assert_eq!(stress_base_side(0, 0, Symbology::Itf), 512);
for (width, height) in [(1037, 205), (892, 233), (604, 385), (3000, 700), (640, 480)] {
for linear in Symbology::ALL.into_iter().filter(|s| s.is_linear()) {
let side = u64::from(stress_base_side(width, height, linear));
let short = side * u64::from(height) / u64::from(width);
assert!(
side * short <= 512 * 512,
"{width}x{height} {linear:?}: {side}"
);
assert!(side >= 512, "{width}x{height} {linear:?}: {side}");
}
}
assert_eq!(
Symbology::ALL.into_iter().filter(|s| s.is_linear()).count(),
12,
"seven of the nineteen symbologies are matrix or stacked"
);
}
#[test]
fn the_resolution_ramp_keeps_its_shares_on_a_wider_base() {
let cells = [358, 256, 179, 128, 90];
assert_eq!(cells.map(|side| ramp_side(side, 512)), cells);
assert_eq!(
cells.map(|side| ramp_side(side, 1024)),
[716, 512, 358, 256, 180]
);
assert_eq!(
cells.map(|side| ramp_side(side, 1037)),
[725, 518, 362, 259, 182]
);
}
fn detection_with(ec: Option<EcLevel>) -> MergedDetection {
MergedDetection {
symbology: crate::report::Symbology::QrCode,
raw: b"x".to_vec(),
text: "x".into(),
charset: crate::report::Charset::Utf8,
masked_stream: None,
corners: None,
version: Some(2),
ec,
mask: Some(0),
fnc1: false,
photometric_inverted: false,
engines: vec![crate::report::EngineKind::Rqrr],
occurrences: vec![crate::engine::occurrence::Footprint::unavailable()],
}
}
fn compose_published(
axes: Vec<AxisScore>,
structural: Option<crate::report::StructuralReport>,
uec: Option<crate::report::UecReport>,
iso15415: Option<crate::report::Iso15415Report>,
detection: &MergedDetection,
) -> (Score, Vec<Hint>) {
compose(axes, structural, uec, true, iso15415, detection)
}
fn axes_with(overrides: &[(StressAxis, u8, u8)]) -> Vec<AxisScore> {
let mut axes: Vec<AxisScore> = WEIGHTS
.iter()
.map(|&(axis, _)| AxisScore {
axis,
passed: 5,
total: 5,
failed_at: None,
refined_failed_at: None,
})
.collect();
for &(axis, passed, total) in overrides {
let slot = axes.iter_mut().find(|a| a.axis == axis).unwrap();
slot.passed = passed;
slot.total = total;
}
axes
}
#[test]
fn composite_weights_are_exact() {
let d = detection_with(Some(EcLevel::H));
let (score, _) = compose_published(axes_with(&[]), None, None, None, &d);
assert_eq!(score.value, 100);
let (score, _) = compose_published(
axes_with(&[(StressAxis::Resolution, 4, 5)]),
None,
None,
None,
&d,
);
assert_eq!(score.value, 95);
let (score, hints) =
compose_published(axes_with(&[(StressAxis::Blur, 0, 5)]), None, None, None, &d);
assert_eq!(score.value, 82);
assert!(hints.contains(&Hint::ReduceArtTexture), "{hints:?}");
let (score, _) = compose_published(
axes_with(&[(StressAxis::Rotation, 2, 5)]),
None,
None,
None,
&d,
);
assert_eq!(score.value, 94);
}
#[test]
fn structural_caps_are_exact_with_boundaries() {
use crate::report::StructuralReport;
let d = detection_with(Some(EcLevel::H));
let (score, hints) = compose_published(
axes_with(&[]),
Some(StructuralReport {
finder_integrity: [1.0, 1.0, 0.49],
quiet_zone_ok: true,
}),
None,
None,
&d,
);
assert_eq!(score.value, FINDER_DAMAGE_CAP);
assert!(
hints.contains(&Hint::FixFinderPattern { corner: 2 }),
"{hints:?}"
);
let (score, hints) = compose_published(
axes_with(&[]),
Some(StructuralReport {
finder_integrity: [1.0, 1.0, 0.5],
quiet_zone_ok: true,
}),
None,
None,
&d,
);
assert_eq!(score.value, 100);
assert!(hints.is_empty(), "{hints:?}");
let (score, hints) = compose_published(
axes_with(&[]),
Some(StructuralReport {
finder_integrity: [1.0, 1.0, 1.0],
quiet_zone_ok: false,
}),
None,
None,
&d,
);
assert_eq!(score.value, QUIET_ZONE_CAP);
assert!(hints.contains(&Hint::RestoreQuietZone));
}
#[test]
fn hint_thresholds_fire_exactly_at_the_published_boundaries() {
let d = detection_with(Some(EcLevel::H));
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Contrast, 2, 5)]),
None,
None,
None,
&d,
);
assert!(hints.contains(&Hint::IncreaseContrast), "{hints:?}");
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Contrast, 3, 5)]),
None,
None,
None,
&d,
);
assert!(!hints.contains(&Hint::IncreaseContrast), "{hints:?}");
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Resolution, 2, 5)]),
None,
None,
None,
&d,
);
assert!(hints.contains(&Hint::EnlargeModules), "{hints:?}");
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Resolution, 3, 5)]),
None,
None,
None,
&d,
);
assert!(!hints.contains(&Hint::EnlargeModules), "{hints:?}");
let (_, hints) =
compose_published(axes_with(&[(StressAxis::Blur, 1, 5)]), None, None, None, &d);
assert!(!hints.contains(&Hint::ReduceArtTexture), "{hints:?}");
}
#[test]
fn raise_ec_hint_value_and_uec_paths() {
use crate::report::{UecGrade, UecReport};
let d = detection_with(Some(EcLevel::Q));
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Rotation, 2, 5)]),
None,
None,
None,
&d,
);
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
"{hints:?}"
);
let (score, hints) = compose_published(
axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]),
None,
None,
None,
&d,
);
assert!(score.value < 70, "{}", score.value);
assert!(
hints.iter().any(|h| matches!(
h,
Hint::RaiseErrorCorrection {
current: EcLevel::Q
}
)),
"{hints:?}"
);
let thin = UecReport {
margin: 0.30,
grade: UecGrade::D,
worst_block_errors: 6,
worst_block_capacity: 18,
};
let (score, hints) = compose_published(axes_with(&[]), None, Some(thin), None, &d);
assert_eq!(score.value, 76);
assert!(
hints
.iter()
.any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
"{hints:?}"
);
let limit = UecReport {
margin: 0.0,
grade: UecGrade::F,
worst_block_errors: 12,
worst_block_capacity: 24,
};
let (_, hints) = compose_published(axes_with(&[]), None, Some(limit), None, &d);
assert!(
hints.contains(&Hint::LowCorrectionMargin {
errors: 12,
capacity: 24
}),
"{hints:?}"
);
let (_, hints) = compose_published(axes_with(&[]), None, Some(thin), None, &d);
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
"{hints:?}"
);
let dh = detection_with(Some(EcLevel::H));
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Blur, 0, 5)]),
None,
Some(thin),
None,
&dh,
);
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
"{hints:?}"
);
}
#[test]
fn uec_margin_caps_the_composite_continuously() {
use crate::report::{UecGrade, UecReport};
let d = detection_with(Some(EcLevel::H));
let at = |margin: f32| UecReport {
margin,
grade: UecGrade::from_margin(margin),
worst_block_errors: 6,
worst_block_capacity: 24,
};
let value = |uec: Option<UecReport>| {
compose_published(axes_with(&[]), None, uec, None, &d)
.0
.value
};
assert_eq!(value(None), 100, "no measurement → no penalty");
assert_eq!(value(Some(at(1.0))), 100);
assert_eq!(
value(Some(at(0.5))),
100,
"continuous seam at the threshold"
);
let v37 = value(Some(at(0.37))); let v25 = value(Some(at(0.25))); let v10 = value(Some(at(0.10)));
let v0 = value(Some(at(0.0))); assert!(
v37 < 100 && v25 < v37 && v10 < v25 && v0 < v10,
"monotone slope: {v37} {v25} {v10} {v0}"
);
assert_eq!(v25, 70, "ISO D lands at 70 — visibly below the far band");
assert_eq!(v0, 40, "RS limit = the finder-damage floor, never a pass");
let sunk = compose_published(
axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]),
None,
Some(at(0.45)),
None,
&d,
)
.0
.value;
assert!(sunk < 94, "axes verdict survives under a mild cap: {sunk}");
}
#[test]
fn depth_index_sets_pinned() {
assert_eq!(depth_indices(ScoreDepth::Off), &[] as &[usize]);
assert_eq!(depth_indices(ScoreDepth::Reduced), &[1, 3]);
assert_eq!(depth_indices(ScoreDepth::Full), &[0, 1, 2, 3, 4]);
assert_eq!(lighting_indices(ScoreDepth::Off), &[] as &[usize]);
assert_eq!(lighting_indices(ScoreDepth::Reduced), &[1, 2]);
assert_eq!(lighting_indices(ScoreDepth::Full), &[0, 1, 2, 3, 4]);
}
#[test]
fn zero_total_axes_are_skipped_not_divided() {
let d = detection_with(Some(EcLevel::H));
let (score, _) = compose_published(
axes_with(&[(StressAxis::Resolution, 0, 0)]),
None,
None,
None,
&d,
);
assert_eq!(score.value, 78);
let (score, hints) = compose_published(
axes_with(&[(StressAxis::Contrast, 0, 0)]),
None,
None,
None,
&d,
);
assert_eq!(score.value, 85);
assert!(!hints.contains(&Hint::IncreaseContrast), "{hints:?}");
let (_, hints) = compose_published(
axes_with(&[(StressAxis::Resolution, 0, 0)]),
None,
None,
None,
&d,
);
assert!(!hints.contains(&Hint::EnlargeModules), "{hints:?}");
let (score, hints) =
compose_published(axes_with(&[(StressAxis::Blur, 0, 0)]), None, None, None, &d);
assert_eq!(score.value, 82);
assert!(!hints.contains(&Hint::ReduceArtTexture), "{hints:?}");
}
#[test]
fn raise_ec_hint_uses_strict_less_than_at_the_value_boundary() {
let d = detection_with(Some(EcLevel::Q));
let (score, hints) = compose_published(
axes_with(&[
(StressAxis::Perspective, 0, 5),
(StressAxis::Rotation, 0, 5),
]),
None,
None,
None,
&d,
);
assert_eq!(score.value, 70);
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::RaiseErrorCorrection { .. })),
"value==70 is NOT below the strict-< 70 threshold: {hints:?}"
);
}
fn plain_key(payload: &[u8]) -> ContentKey {
ContentKey {
raw: payload.to_vec(),
eci: crate::engine::content::EciEvidence::NoEci,
fnc1: crate::engine::content::Fnc1::None,
}
}
fn render_qr_candidate(payload: &[u8], version: i16, module: u32, white: u8) -> LumaImage {
let code = qrcode::QrCode::with_version(
payload,
qrcode::Version::Normal(version),
qrcode::EcLevel::Q,
)
.unwrap();
let rendered = code
.render::<image::Luma<u8>>()
.module_dimensions(module, module)
.dark_color(image::Luma([0]))
.light_color(image::Luma([white]))
.build();
let (width, height) = rendered.dimensions();
LumaImage::new(rendered.into_raw(), width, height)
}
fn score_base_fingerprint(base: &LumaImage) -> u64 {
base.width()
.to_le_bytes()
.into_iter()
.chain(base.height().to_le_bytes())
.chain(base.data().iter().copied())
.fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
})
}
fn assert_measured_axis(
base: &LumaImage,
payload: &[u8],
expected: AxisScore,
expected_units: u32,
) {
let key = plain_key(payload);
let cancel = CancelToken::new();
let mut calibration = Bound::new(&cancel, None).with_quota(16);
let Calibrated::Class(probe) = CellProbe::calibrate_within(
base,
&key,
crate::report::Symbology::QrCode,
&mut calibration,
)
.unwrap() else {
panic!("the measured QR witness must calibrate");
};
assert_eq!(
(calibration.spent(), calibration.cut(), calibration.panics()),
(1, false, 0)
);
assert!(probe.rung.is_none());
assert_eq!(probe.symbology, crate::report::Symbology::QrCode);
let skip: Vec<_> = WEIGHTS
.iter()
.map(|&(other, _)| other)
.filter(|&other| other != expected.axis)
.collect();
let mut bound = Bound::new(&cancel, None).with_quota(6);
let axes = run_axes(base, &key, ScoreDepth::Full, &skip, &mut bound, probe).unwrap();
assert_eq!(axes, Some(vec![expected]));
assert_eq!(
(bound.spent(), bound.cut(), bound.panics()),
(expected_units, false, 0)
);
}
#[test]
fn low_luma_qr_fails_only_the_underexposure_cell() {
let payload = b"https://qrcode-ai.com/c/v5q";
let image = render_qr_candidate(payload, 5, 4, 60);
let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
assert_eq!((base.width(), base.height()), (180, 180));
assert_eq!(score_base_fingerprint(&base), 0x09ca_6527_c122_72e5);
assert_measured_axis(
&base,
payload,
AxisScore {
axis: StressAxis::Lighting,
passed: 4,
total: 5,
failed_at: Some("underexposure".to_owned()),
refined_failed_at: None,
},
5,
);
}
#[test]
fn qr_blur_knee_refines_to_the_measured_failing_midpoint() {
let payload = b"refine knee pin";
let image = render_qr_candidate(payload, 5, 3, 255);
let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
assert_eq!((base.width(), base.height()), (135, 135));
assert_eq!(score_base_fingerprint(&base), 0x9b0a_eeab_5c72_e34c);
assert_measured_axis(
&base,
payload,
AxisScore {
axis: StressAxis::Blur,
passed: 3,
total: 5,
failed_at: Some("blur 2.0".to_owned()),
refined_failed_at: Some("blur 1.75".to_owned()),
},
5,
);
}
#[test]
fn qr_resolution_knee_refines_to_the_measured_failing_midpoint() {
let payload = b"https://qrcode-ai.com/c/v5q";
let image = render_qr_candidate(payload, 13, 3, 255);
assert_eq!((image.width(), image.height()), (231, 231));
let base = transform::downscale_to(&image, STRESS_BASE_SIDE);
assert_eq!((base.width(), base.height()), (231, 231));
assert_eq!(score_base_fingerprint(&base), 0x54d9_83f4_4539_6ebc);
assert_measured_axis(
&base,
payload,
AxisScore {
axis: StressAxis::Resolution,
passed: 4,
total: 5,
failed_at: Some("90px".to_owned()),
refined_failed_at: Some("109px".to_owned()),
},
6,
);
}
fn primary_of(planes: &crate::transform::SourcePlanes) -> (MergedDetection, ContentKey) {
let outcome = ladder::run(planes, &ScanConfig::full(), &CancelToken::new(), None).unwrap();
(outcome.merged[0].clone(), outcome.contents[0].0.clone())
}
fn clean_base_and_probe() -> (LumaImage, ContentKey, CellProbe) {
let code =
qrcode::QrCode::with_error_correction_level(b"stress-axis pin", qrcode::EcLevel::Q)
.unwrap();
let img = code
.render::<image::Luma<u8>>()
.module_dimensions(8, 8)
.build();
let mut png = Vec::new();
image::DynamicImage::ImageLuma8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
let (d, key) = primary_of(&planes);
let base = transform::downscale_to(&planes.luma, STRESS_BASE_SIDE);
let probe = CellProbe::calibrate(&base, &key, d.symbology).unwrap();
(base, key, probe)
}
fn assert_honest_axes(axes: &[AxisScore], depth: ScoreDepth) {
for a in axes {
let picks = if a.axis == StressAxis::Lighting {
lighting_indices(depth)
} else {
depth_indices(depth)
};
assert_eq!(usize::from(a.total), picks.len(), "planned cells: {a:?}");
assert_eq!(
a.passed == a.total,
a.failed_at.is_none(),
"passed == total iff nothing failed: {a:?}"
);
if let Some(label) = a.failed_at.as_deref() {
let at = picks.iter().position(|&i| cell_label(a.axis, i) == label);
assert!(at.is_some(), "failed_at names a planned cell: {a:?}");
if a.axis != StressAxis::Lighting {
assert_eq!(
at,
Some(usize::from(a.passed)),
"a ramp's knee follows its survivors: {a:?}"
);
}
}
}
}
fn unbounded_axes(
base: &LumaImage,
key: &ContentKey,
skip: &[StressAxis],
probe: CellProbe,
) -> Vec<AxisScore> {
let cancel = CancelToken::new();
let axes = run_axes(
base,
key,
ScoreDepth::Full,
skip,
&mut Bound::new(&cancel, None),
probe,
)
.unwrap()
.expect("an unbounded run is never cut");
assert_honest_axes(&axes, ScoreDepth::Full);
axes
}
fn judged(
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
depth: ScoreDepth,
skip: &[StressAxis],
checks: &[crate::ladder::ScoreCheck],
) -> (Score, Vec<Hint>) {
let cancel = CancelToken::new();
let mut bound = Bound::new(&cancel, None);
let judged = evaluate(luma, detection, key, depth, skip, checks, &mut bound).unwrap();
assert!(!bound.cut(), "an unbounded judgment is never cut");
let (score, hints) = judged.expect("an unbounded judgment with axes completes");
assert_honest_axes(&score.axes, depth);
(score, hints)
}
#[test]
fn pristine_symbol_survives_all_lighting_cells() {
let (base, key, probe) = clean_base_and_probe();
let axes = unbounded_axes(&base, &key, &[], probe);
let lighting = axes
.iter()
.find(|a| a.axis == StressAxis::Lighting)
.unwrap();
assert_eq!(
lighting.passed, 5,
"a pristine full-frame symbol must survive every lighting cell \
(glare sits on the data region, not a finder): {lighting:?}"
);
assert!(
lighting.failed_at.is_none(),
"all-passed carries no failed_at: {lighting:?}"
);
}
#[test]
fn builder_default_render_reaches_100_and_styled_explains_its_losses() {
let score_of = |rel: &str| {
let path = format!("{}/../../{rel}", env!("CARGO_MANIFEST_DIR"));
let bytes = std::fs::read(&path).expect("builder fixture present");
let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
let (detection, key) = primary_of(&planes);
judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[])
};
let (default_score, _) = score_of("fixtures/clean/builder-default-rounded-1024.png");
assert_eq!(
default_score.value, 100,
"the pristine default render must reach 100 — a ceiling below that \
measures the instrument, not the design: {:?}",
default_score.axes
);
let (styled_score, _) = score_of("fixtures/artistic/builder-template-hearts-web-1024.png");
assert!(
styled_score.value < 100,
"the pale styled template keeps real, explained losses: {}",
styled_score.value
);
let lighting = styled_score
.axes
.iter()
.find(|a| a.axis == StressAxis::Lighting)
.unwrap();
assert!(
lighting.passed < lighting.total,
"the styled template loses lighting cells: {lighting:?}"
);
assert_eq!(
lighting.failed_at.as_deref(),
Some("hard shadow"),
"the first failed cell is named on the wire: {lighting:?}"
);
}
#[test]
fn rotation_ramp_measures_engine_tolerance_not_frame_cropping() {
let code = qrcode::QrCode::with_version(
b"rotation probe: the frame must never eat the finders",
qrcode::Version::Normal(10),
qrcode::EcLevel::Q,
)
.unwrap();
let img = code
.render::<image::Luma<u8>>()
.module_dimensions(4, 4)
.build();
let (w, h) = (img.width(), img.height());
let base = LumaImage::new(img.into_raw(), w, h);
let key = plain_key(b"rotation probe: the frame must never eat the finders");
let probe = CellProbe::calibrate(&base, &key, crate::report::Symbology::QrCode)
.expect("flawless base calibrates");
let axes = unbounded_axes(&base, &key, &[], probe);
let rotation = axes
.iter()
.find(|a| a.axis == StressAxis::Rotation)
.unwrap();
assert_eq!(
rotation.passed, 5,
"a flawless v10 died on the rotation ramp — the probe is measuring \
frame cropping, not engine tolerance: {rotation:?}"
);
}
#[test]
fn skipped_axes_never_run_and_the_composite_renormalizes() {
let (base, key, probe) = clean_base_and_probe();
let full = unbounded_axes(&base, &key, &[], probe);
let skipped = unbounded_axes(
&base,
&key,
&[StressAxis::Perspective, StressAxis::Rotation],
probe,
);
assert_eq!(skipped.len(), 4, "six axes minus the two skipped");
assert!(
skipped
.iter()
.all(|a| a.axis != StressAxis::Perspective && a.axis != StressAxis::Rotation),
"skipped axes are absent from the report: {skipped:?}"
);
for a in &skipped {
let twin = full.iter().find(|f| f.axis == a.axis).unwrap();
assert_eq!((a.passed, a.total), (twin.passed, twin.total));
}
let d = detection_with(Some(EcLevel::H));
let (score_full, _) = compose_published(full, None, None, None, &d);
let (score_skip, _) = compose_published(skipped, None, None, None, &d);
assert_eq!(score_full.value, 100, "full six-axis composite");
assert_eq!(score_skip.value, 100, "renormalized four-axis composite");
let lone = vec![AxisScore {
axis: StressAxis::Lighting,
passed: 1,
total: 2,
failed_at: None,
refined_failed_at: None,
}];
let (score_lone, _) = compose_published(lone, None, None, None, &d);
assert_eq!(score_lone.value, 50, "weights re-span the run set");
}
#[test]
fn glare_cell_stays_lethal_on_a_finder_and_names_itself() {
let code =
qrcode::QrCode::with_error_correction_level(b"canvas glare pin", qrcode::EcLevel::H)
.unwrap();
let qr = code
.render::<image::Luma<u8>>()
.module_dimensions(6, 6)
.build();
let (qw, qh) = (qr.width(), qr.height());
let (cw, ch) = (qw * 2, qh * 2);
let mut canvas = vec![255u8; (cw * ch) as usize];
for yy in 0..qh {
for xx in 0..qw {
canvas[((yy + qh) * cw + (xx + qw)) as usize] = qr.get_pixel(xx, yy).0[0];
}
}
let base = LumaImage::new(canvas, cw, ch);
let key = plain_key(b"canvas glare pin");
let probe = CellProbe::calibrate(&base, &key, crate::report::Symbology::QrCode)
.expect("corner symbol calibrates");
let axes = unbounded_axes(&base, &key, &[], probe);
let lighting = axes
.iter()
.find(|a| a.axis == StressAxis::Lighting)
.unwrap();
assert_eq!(
lighting.passed, 4,
"the canvas-centre blob sits on the corner symbol's TL finder and \
must kill exactly the glare cell: {lighting:?}"
);
assert_eq!(
lighting.failed_at.as_deref(),
Some("glare"),
"the kill names itself on the wire: {lighting:?}"
);
}
#[test]
fn lighting_pass_count_accumulates() {
let (base, key, probe) = clean_base_and_probe();
let axes = unbounded_axes(&base, &key, &[], probe);
let lighting = axes
.iter()
.find(|a| a.axis == StressAxis::Lighting)
.unwrap();
assert!(
lighting.passed >= 1,
"clean symbol must survive ≥1 lighting cell: {lighting:?}"
);
}
#[test]
fn a_past_deadline_stops_the_lighting_set() {
let (base, key, probe) = clean_base_and_probe();
let cancel = CancelToken::new();
let mut bound = Bound::new(&cancel, Some(Instant::now()));
let lighting = run_lighting(&base, &key, ScoreDepth::Full, &mut bound, probe).unwrap();
assert!(
lighting.is_none(),
"a past deadline interrupts the set: {lighting:?}"
);
assert_eq!(bound.spent(), 0, "no lighting cell ran");
}
#[test]
fn kanji_symbol_scores_with_content_keyed_cells() {
let sjis: &[u8] = &[0x82, 0xB1, 0x82, 0xF1, 0x82, 0xC9, 0x82, 0xBF, 0x82, 0xCD];
let code = qrcode::QrCode::with_error_correction_level(sjis, qrcode::EcLevel::Q).unwrap();
let img = code
.render::<image::Luma<u8>>()
.module_dimensions(8, 8)
.build();
let mut png = Vec::new();
image::DynamicImage::ImageLuma8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
let (detection, key) = primary_of(&planes);
assert_eq!(detection.text, "こんにちは");
let (score, _) = judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[]);
let total_passed: u32 = score.axes.iter().map(|a| u32::from(a.passed)).sum();
assert!(
total_passed >= 12,
"kanji symbol must survive stress cells: {:?}",
score.axes
);
assert!(score.value >= 50, "score {}", score.value);
}
#[test]
fn skip_checks_null_their_sections_and_leave_value_alone() {
use crate::ladder::ScoreCheck;
let (luma, detection, key) = pristine_q_example();
let run =
|checks: &[ScoreCheck]| judged(&luma, &detection, &key, ScoreDepth::Full, &[], checks);
let (full, _) = run(&[]);
assert!(full.uec.is_some(), "clean rqrr decode must measure UEC");
assert!(full.iso15415.is_some(), "corners + version must yield ISO");
let (skipped, hints) = run(&[ScoreCheck::Uec, ScoreCheck::Iso15415]);
assert!(skipped.uec.is_none());
assert!(skipped.iso15415.is_none());
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
"no uec → its miscorrection hint cannot fire"
);
assert_eq!(
skipped.value, full.value,
"checks are surface truth — the axis composite never moves"
);
let (uec_only, _) = run(&[ScoreCheck::Uec]);
assert!(uec_only.uec.is_none());
let iso = uec_only.iso15415.expect("iso block still runs");
assert!(
iso.unused_error_correction.is_none(),
"no uec input → the ISO parameter reads null, never faked"
);
}
fn thin_margin_v2q(k: u8) -> (LumaImage, MergedDetection, ContentKey) {
const MODULE: usize = 10;
const QUIET: usize = 4;
let code = qrcode::QrCode::with_version(
b"thin margin pin",
qrcode::Version::Normal(2),
qrcode::EcLevel::Q,
)
.unwrap();
let width = code.width();
let mut dark: Vec<bool> = code
.into_colors()
.into_iter()
.map(|c| c == qrcode::Color::Dark)
.collect();
for &(y, x) in crate::matrix::zigzag::zigzag_positions(2)
.iter()
.step_by(8)
.take(usize::from(k))
{
dark[y * width + x] ^= true;
}
let side = (width + 2 * QUIET) * MODULE;
let mut pixels = vec![255u8; side * side];
for (i, _) in dark.iter().enumerate().filter(|(_, is_dark)| **is_dark) {
let (my, mx) = (i / width + QUIET, i % width + QUIET);
for row in pixels.chunks_mut(side).skip(my * MODULE).take(MODULE) {
row[mx * MODULE..(mx + 1) * MODULE].fill(0);
}
}
let side = u32::try_from(side).unwrap();
let planes =
normalize(&ImageInput::luma8(&pixels, side, side), &Limits::default()).unwrap();
let (detection, key) = primary_of(&planes);
(planes.luma, detection, key)
}
#[test]
fn skipping_uec_never_moves_a_thin_margin_composite() {
use crate::ladder::ScoreCheck;
use crate::report::UecGrade;
const K: u8 = 8;
let (luma, detection, key) = thin_margin_v2q(K);
assert!(
detection.masked_stream.is_some(),
"precondition: the rqrr stream is present — the margin is measurable"
);
let only_contrast = [
StressAxis::Resolution,
StressAxis::Blur,
StressAxis::Perspective,
StressAxis::Rotation,
StressAxis::Lighting,
];
let run = |checks: &[ScoreCheck]| {
judged(
&luma,
&detection,
&key,
ScoreDepth::Full,
&only_contrast,
checks,
)
};
let (shown, shown_hints) = run(&[]);
let uec = shown.uec.expect("the default checks publish the margin");
assert_eq!(
(uec.worst_block_errors, uec.worst_block_capacity),
(K, 22),
"precondition: exactly K errors in the one v2-Q block: {uec:?}"
);
let expected_margin = 1.0 - 2.0 * f32::from(K) / 22.0;
assert!(
(uec.margin - expected_margin).abs() < 1e-6,
"precondition: margin {} vs 1 − 2·{K}/22",
uec.margin
);
assert_eq!(uec.grade, UecGrade::D);
assert_eq!(
shown
.axes
.iter()
.map(|a| (a.axis, a.passed, a.total))
.collect::<Vec<_>>(),
vec![(StressAxis::Contrast, 5, 5)],
"precondition: the uncapped composite is 100"
);
assert_eq!(shown.value, uec_margin_cap(uec.margin));
assert_eq!(shown.value, 73, "0.2727/0.5 × 60 + 40 = 72.7 → 73");
assert!(
shown_hints.contains(&Hint::RaiseErrorCorrection {
current: EcLevel::Q
}),
"a published grade-D margin drives the raise-EC hint: {shown_hints:?}"
);
let (hidden, hidden_hints) = run(&[ScoreCheck::Uec]);
assert_eq!(
(hidden.value, hidden.grade, hidden.weights_run),
(shown.value, shown.grade, shown.weights_run),
"skipping a check never moves the composite"
);
assert_eq!(hidden.axes, shown.axes);
assert!(hidden.uec.is_none(), "the skipped section stays withheld");
let shown_iso = shown.iso15415.expect("the ISO block runs");
let hidden_iso = hidden.iso15415.expect("the ISO block still runs");
assert!(
hidden_iso.unused_error_correction.is_none(),
"the ISO UEC parameter follows the published section"
);
let margin_grade = shown_iso
.unused_error_correction
.expect("published by default")
.grade;
assert_eq!(shown_iso.overall, margin_grade, "{shown_iso:?}");
assert_eq!(
hidden_iso.overall, shown_iso.overall,
"skipping a check never moves the ISO overall"
);
assert!(
!hidden_hints.iter().any(|h| matches!(
h,
Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
)),
"UEC-driven hints follow the published section: {hidden_hints:?}"
);
}
fn scan_v1l_codeword_damage(
corrupt: &[usize],
checks: &[crate::ladder::ScoreCheck],
) -> crate::report::ScanReport {
use crate::rescue::test_symbols::{drawn_v1l, v1l_codewords};
let mut codewords = v1l_codewords(b"abc");
assert_eq!(codewords.len(), 26, "19 data + 7 parity codewords");
for &index in corrupt {
codewords[index] ^= 0xFF;
}
let luma = drawn_v1l(&codewords);
let mut config = ScanConfig::full();
config.budget_ms = None;
config.score_skip_axes = vec![
StressAxis::Resolution,
StressAxis::Blur,
StressAxis::Perspective,
StressAxis::Rotation,
StressAxis::Lighting,
];
config.score_skip_checks = checks.to_vec();
crate::Scanner::builder()
.profile(crate::ScanProfile::Custom(config))
.build()
.scan(ImageInput::luma8(luma.data(), luma.width(), luma.height()))
.unwrap()
}
#[test]
fn v1l_acceptance_limit_keeps_synthetic_uec_and_skipped_check_caps() {
use crate::ladder::ScoreCheck;
use crate::report::{Charset, IsoGrade, IsoParameter, Symbology, UecGrade};
let shown = scan_v1l_codeword_damage(&[0, 2], &[]);
assert_eq!(shown.trace.budget_exhausted, Some(false));
assert_eq!(shown.trace.engine_panics, 0);
assert_eq!(shown.detections.len(), 1, "{shown:?}");
let detection = &shown.detections[0];
assert_eq!(detection.symbology, Symbology::QrCode);
assert_eq!(detection.content.raw, b"abc");
assert_eq!(detection.content.text, "abc");
assert_eq!(detection.content.charset, Charset::Utf8);
assert_eq!(detection.content.eci, None);
assert_eq!(detection.content.fnc1, None);
let meta = detection.meta;
assert_eq!(
(meta.version, meta.ec_level, meta.modules, meta.mask),
(Some(1), Some(EcLevel::L), Some(21), Some(3))
);
let score = shown.score.as_ref().expect("unbounded complete judgment");
let uec = score.uec.expect("the two errors are measurable");
assert_eq!(
(uec.worst_block_errors, uec.worst_block_capacity, uec.grade),
(2, 7, UecGrade::C)
);
assert!((uec.margin - 3.0 / 7.0).abs() < 1e-6, "{uec:?}");
assert_eq!(
score.axes,
vec![AxisScore {
axis: StressAxis::Contrast,
passed: 5,
total: 5,
failed_at: None,
refined_failed_at: None,
}],
"precondition: the uncapped composite is 100"
);
assert_eq!(score.weights_run, 15);
assert_eq!((score.value, score.grade), (91, Grade::Excellent));
let iso = score.iso15415.expect("the ISO-informed card is measured");
assert_eq!(
iso.unused_error_correction,
Some(IsoParameter {
value: uec.margin,
grade: IsoGrade::C,
})
);
assert!(!shown.hints.iter().any(|hint| matches!(
hint,
Hint::LowCorrectionMargin { .. } | Hint::RaiseErrorCorrection { .. }
)));
for checks in [
&[ScoreCheck::Uec][..],
&[ScoreCheck::Iso15415][..],
&[ScoreCheck::Uec, ScoreCheck::Iso15415][..],
] {
let hidden = scan_v1l_codeword_damage(&[0, 2], checks);
assert_eq!(hidden.trace.budget_exhausted, Some(false));
assert_eq!(hidden.trace.engine_panics, 0);
assert_eq!(hidden.detections, shown.detections, "{checks:?}");
let mut expected = score.clone();
if checks.contains(&ScoreCheck::Uec) {
expected.uec = None;
if let Some(card) = &mut expected.iso15415 {
card.unused_error_correction = None;
}
}
if checks.contains(&ScoreCheck::Iso15415) {
expected.iso15415 = None;
}
assert_eq!(hidden.score, Some(expected), "{checks:?}");
assert_eq!(hidden.hints, shown.hints, "{checks:?}");
}
let refused = scan_v1l_codeword_damage(&[0, 2, 4], &[]);
assert_eq!(refused.trace.budget_exhausted, Some(false));
assert_eq!(refused.trace.engine_panics, 0);
assert_eq!(refused.detections, Vec::new(), "{refused:?}");
assert_eq!(refused.score, None);
assert_eq!(refused.hints, Vec::new());
}
fn pristine_q_example() -> (LumaImage, MergedDetection, ContentKey) {
let code =
qrcode::QrCode::with_error_correction_level(b"https://example.com", qrcode::EcLevel::Q)
.unwrap();
let img = code
.render::<image::Luma<u8>>()
.module_dimensions(8, 8)
.build();
let mut png = Vec::new();
image::DynamicImage::ImageLuma8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
let (detection, key) = primary_of(&planes);
(planes.luma, detection, key)
}
#[test]
fn an_expired_deadline_yields_no_judgment() {
let (luma, detection, key) = pristine_q_example();
let cancel = CancelToken::new();
for depth in [ScoreDepth::Full, ScoreDepth::Reduced] {
let mut expired = Bound::new(&cancel, Some(Instant::now()));
let judged = evaluate(&luma, &detection, &key, depth, &[], &[], &mut expired).unwrap();
assert!(
judged.is_none(),
"{depth:?}: an expired deadline must yield no judgment, got {judged:?}"
);
assert!(expired.cut(), "{depth:?}: and says the deadline cut it");
let mut bound = Bound::new(&cancel, Some(Instant::now()));
let outcome = judge(&luma, &detection, &key, depth, &[], &[], &mut bound).unwrap();
assert!(
matches!(outcome, Judgment::Interrupted),
"{depth:?}: {outcome:?}"
);
assert_eq!(bound.spent(), 0, "{depth:?}: no calibration step, no cell");
}
}
#[test]
fn a_judgment_refused_at_its_first_step_builds_nothing() {
let (luma, detection, key) = pristine_q_example();
let cancel = CancelToken::new();
let built = || STRESS_BASES.with(std::cell::Cell::get);
let before = built();
let mut bound = Bound::new(&cancel, None).with_quota(0);
let outcome = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut bound,
)
.unwrap();
assert!(matches!(outcome, Judgment::Interrupted), "{outcome:?}");
assert_eq!(bound.spent(), 0);
assert_eq!(built() - before, 0, "no stress base for a refused judgment");
let mut bound = Bound::new(&cancel, None).with_quota(1);
let outcome = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut bound,
)
.unwrap();
assert!(matches!(outcome, Judgment::Interrupted), "{outcome:?}");
assert_eq!(built() - before, 1);
}
#[test]
fn a_cut_bisection_keeps_the_score_and_reports_the_cut() {
let (luma, detection, key) = kneed_example();
let cancel = CancelToken::new();
let mut free = Bound::new(&cancel, None);
let Judgment::Complete(reference, _) = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut free,
)
.unwrap() else {
panic!("an unbounded judgment completes");
};
assert!(!free.cut(), "an unbounded judgment is never cut");
let complete = complete_units(&luma, &detection, &key, &reference);
assert!(
free.spent() > complete,
"precondition: knees to bisect after the cells"
);
let mut bound = Bound::new(&cancel, None).with_quota(complete);
let Judgment::Complete(score, _) = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut bound,
)
.unwrap() else {
panic!("every planned cell fits the quota");
};
assert_eq!(
(score.value, score.grade),
(reference.value, reference.grade)
);
assert!(score.axes.iter().all(|a| a.refined_failed_at.is_none()));
assert!(bound.cut(), "the refused bisections are a cut");
}
#[test]
fn judge_no_axes_iff_config_computes_no_score() {
let (luma, detection, key) = pristine_q_example();
let cancel = CancelToken::new();
let every: Vec<StressAxis> = WEIGHTS.iter().map(|&(axis, _)| axis).collect();
let skips: [&[StressAxis]; 4] = [
&[],
&[StressAxis::Lighting],
&every[..every.len() - 1],
&every,
];
for depth in [ScoreDepth::Off, ScoreDepth::Reduced, ScoreDepth::Full] {
for skip in skips {
let mut config = ScanConfig::full();
config.score_depth = depth;
config.score_skip_axes = skip.to_vec();
let mut bound = Bound::new(&cancel, None).with_quota(0);
let outcome = judge(&luma, &detection, &key, depth, skip, &[], &mut bound).unwrap();
assert_eq!(
matches!(outcome, Judgment::NoAxes),
!config.computes_score(),
"{depth:?} skipping {skip:?}: {outcome:?}"
);
}
}
assert!(ScanConfig::full().computes_score() && ScanConfig::fast().computes_score());
assert!(!ScanConfig::frame().computes_score());
}
#[test]
fn no_planned_cell_judges_nothing() {
let (luma, detection, key) = pristine_q_example();
let cancel = CancelToken::new();
let every_axis: Vec<StressAxis> = WEIGHTS.iter().map(|&(axis, _)| axis).collect();
for (depth, skip) in [
(ScoreDepth::Full, every_axis.as_slice()),
(ScoreDepth::Reduced, every_axis.as_slice()),
(ScoreDepth::Off, &[][..]),
] {
let mut bound = Bound::new(&cancel, None);
let outcome = judge(&luma, &detection, &key, depth, skip, &[], &mut bound).unwrap();
assert!(
matches!(outcome, Judgment::NoAxes),
"{depth:?}: {outcome:?}"
);
assert_eq!(bound.spent(), 0);
let mut free = Bound::new(&cancel, None);
let judged = evaluate(&luma, &detection, &key, depth, skip, &[], &mut free).unwrap();
assert!(
judged.is_none() && !free.cut(),
"{depth:?}: nothing planned, nothing cut: {judged:?}"
);
}
}
#[test]
fn cancellation_reaches_calibration() {
let (luma, detection, key) = pristine_q_example();
let cancel = CancelToken::new();
cancel.cancel();
let mut bound = Bound::new(&cancel, None);
let outcome = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut bound,
);
assert!(
matches!(outcome, Err(crate::error::ScanError::Cancelled)),
"{outcome:?}"
);
assert_eq!(bound.spent(), 0);
}
fn fixture_example(rel: &str) -> (LumaImage, MergedDetection, ContentKey) {
let path = format!("{}/../../fixtures/{rel}", env!("CARGO_MANIFEST_DIR"));
let bytes = std::fs::read(&path).expect("fixture present");
let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
let (detection, key) = primary_of(&planes);
(planes.luma, detection, key)
}
fn kneed_example() -> (LumaImage, MergedDetection, ContentKey) {
fixture_example("artistic/blob-style-monkey-logo.webp")
}
fn rescue_example() -> (LumaImage, MergedDetection, ContentKey) {
let (luma, detection, key) = fixture_example("degraded/logo-occluded-rescue.png");
assert_eq!(
detection.engines,
vec![crate::report::EngineKind::Rescue],
"precondition: a rescue-only decode"
);
(luma, detection, key)
}
fn calibration_walk(
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
) -> (Calibrated, u32) {
let base = transform::downscale_to(luma, STRESS_BASE_SIDE);
let cancel = CancelToken::new();
let mut walk = Bound::new(&cancel, None);
let calibrated =
CellProbe::calibrate_within(&base, key, detection.symbology, &mut walk).unwrap();
(calibrated, walk.spent())
}
#[test]
fn a_walk_that_ends_on_a_rung_remembers_the_rungs_own_pairs() {
let (luma, detection, key) = kneed_example();
let base = transform::downscale_to(&luma, STRESS_BASE_SIDE);
let cancel = CancelToken::new();
let mut walk = Bound::new(&cancel, None);
let calibrated =
CellProbe::calibrate_within(&base, &key, detection.symbology, &mut walk).unwrap();
assert!(
matches!(
calibrated,
Calibrated::Class(CellProbe { rung: Some(_), .. })
),
"precondition: only a rung reads the base"
);
let read = |variant: Variant| {
engine::probe_readers(detection.symbology)
.iter()
.filter_map(|reader| {
let pair = Pair {
variant,
reader: *reader,
};
walk.schedule.trials[pair.slot()]
})
.map(|trial| trial.read)
.collect::<Vec<bool>>()
};
assert!(read(Variant::Rung).contains(&true), "the rung's pass");
for variant in [Variant::Otsu, Variant::Plain] {
let passes = read(variant);
assert!(!passes.is_empty(), "{variant:?}: the base was tried");
assert!(!passes.contains(&true), "{variant:?}: the base reads");
}
}
fn complete_units(
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
score: &Score,
) -> u32 {
let (calibrated, walk) = calibration_walk(luma, detection, key);
assert!(
!matches!(calibrated, Calibrated::Interrupted),
"an unbounded walk ends"
);
let cells: u32 = score
.axes
.iter()
.map(|a| {
if a.axis == StressAxis::Lighting {
u32::from(a.total)
} else {
u32::from(a.passed) + u32::from(a.failed_at.is_some())
}
})
.sum();
walk + cells
}
fn assert_sweep_preconditions(
name: &str,
luma: &LumaImage,
detection: &MergedDetection,
key: &ContentKey,
reference: &Score,
bisections: usize,
) {
match name {
"kneed" => assert!(bisections > 0, "precondition: knees to bisect"),
"undecodable" => {
let (calibrated, walk) = calibration_walk(luma, detection, key);
assert!(matches!(calibrated, Calibrated::Undecodable));
let every_class = u32::try_from(crate::ladder::DEEP_RUNGS.len()).unwrap() + 1;
assert_eq!(walk, every_class, "shallow class + every deep rung tried");
assert_eq!(reference.value, 0, "{:?}", reference.axes);
}
_ => {}
}
}
#[test]
fn work_quota_cuts_are_absent_never_partial() {
let cancel = CancelToken::new();
for (name, (luma, detection, key)) in [
("pristine", pristine_q_example()),
("kneed", kneed_example()),
("undecodable", rescue_example()),
] {
let mut free = Bound::new(&cancel, None);
let Judgment::Complete(reference, reference_hints) = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut free,
)
.unwrap() else {
panic!("{name}: an unbounded judgment completes");
};
assert_honest_axes(&reference.axes, ScoreDepth::Full);
let complete = complete_units(&luma, &detection, &key, &reference);
let bisections = reference
.axes
.iter()
.filter(|a| a.refined_failed_at.is_some())
.count();
let total = complete + u32::try_from(bisections).unwrap();
assert_eq!(free.spent(), total, "{name}: no hidden step");
assert_sweep_preconditions(name, &luma, &detection, &key, &reference, bisections);
for quota in 0..=total + 1 {
let mut bound = Bound::new(&cancel, None).with_quota(quota);
let outcome = judge(
&luma,
&detection,
&key,
ScoreDepth::Full,
&[],
&[],
&mut bound,
);
assert!(bound.spent() <= quota, "{name}: the quota bounds the spend");
assert_eq!(
bound.cut(),
quota < total,
"{name}: quota {quota} of {total}: the bound reports a refused step"
);
let (score, hints) = match outcome.unwrap() {
Judgment::Complete(score, hints) => (score, hints),
Judgment::Interrupted => {
assert!(
quota < complete,
"{name}: quota {quota} ≥ {complete} completes"
);
continue;
}
Judgment::NoAxes => panic!("{name}: every axis is planned"),
};
assert!(
quota >= complete,
"{name}: quota {quota} < {complete} judged"
);
assert_honest_axes(&score.axes, ScoreDepth::Full);
assert_eq!(
(score.value, score.grade, score.weights_run),
(reference.value, reference.grade, reference.weights_run),
"{name}: quota {quota}"
);
assert_eq!(hints, reference_hints, "{name}: quota {quota}");
assert_eq!(
(score.structural, score.uec, score.iso15415),
(reference.structural, reference.uec, reference.iso15415)
);
assert_eq!(score.axes.len(), reference.axes.len());
for (a, r) in score.axes.iter().zip(&reference.axes) {
assert_eq!(
(a.axis, a.passed, a.total, &a.failed_at),
(r.axis, r.passed, r.total, &r.failed_at),
"{name}: quota {quota}"
);
let refined_ok = if quota >= total {
a.refined_failed_at == r.refined_failed_at
} else if quota == complete {
a.refined_failed_at.is_none()
} else {
a.refined_failed_at.is_none() || a.refined_failed_at == r.refined_failed_at
};
assert!(refined_ok, "{name}: quota {quota}: {a:?} vs {r:?}");
}
}
}
}
fn as_sampled(luma: &LumaImage) -> (crate::engine::MaskedStream, u8, EcLevel, u8) {
let width = luma.width() as usize;
let data = luma.data();
let mut prepared =
rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
data[y * width + x]
});
let grid = prepared.detect_grids().remove(0);
let (meta, raw) = grid.get_raw_data().expect("the sampled format decodes");
let ec = [EcLevel::M, EcLevel::L, EcLevel::H, EcLevel::Q][usize::from(meta.ecc_level)];
let stream = crate::engine::MaskedStream {
bits: raw.data[..raw.len.div_ceil(8)].to_vec(),
bit_len: raw.len,
};
(
stream,
u8::try_from(meta.version.0).unwrap(),
ec,
u8::try_from(meta.mask).unwrap(),
)
}
#[test]
fn a_stream_that_does_not_verify_has_no_uec_and_no_cap() {
use crate::rescue::{Acceptance, Rederived, Unverified};
let luma = crate::rescue::test_symbols::from_segments_mirrored(
qrcode::Version::Normal(3),
qrcode::EcLevel::M,
|b| b.push_byte_data(b"https://qrc-ai.com/mirrored"),
);
let planes = normalize(
&ImageInput::luma8(luma.data(), luma.width(), luma.height()),
&Limits::default(),
)
.unwrap();
let (detection, key) = primary_of(&planes);
let (verified, _) = judged(&planes.luma, &detection, &key, ScoreDepth::Full, &[], &[]);
let (stream, version, ec, mask) = as_sampled(&planes.luma);
assert!(
matches!(
crate::rescue::rederive(&stream, version, ec, mask, Acceptance::Engine),
Rederived::Unverified(Unverified::NothingVerifies)
),
"precondition: the as-sampled stream does not error-correct"
);
assert_ne!(
(Some(ec), Some(mask)),
(detection.ec, detection.mask),
"precondition: as sampled, the format word reads another EC level and mask"
);
let misread = MergedDetection {
masked_stream: Some(stream),
version: Some(version),
ec: Some(ec),
mask: Some(mask),
..detection.clone()
};
let (score, hints) = judged(&planes.luma, &misread, &key, ScoreDepth::Full, &[], &[]);
assert!(score.uec.is_none(), "no margin from it: {:?}", score.uec);
assert!(
score
.iso15415
.is_some_and(|iso| iso.unused_error_correction.is_none()),
"{:?}",
score.iso15415
);
assert_eq!(
(score.value, score.grade),
(verified.value, verified.grade),
"no margin, no cap"
);
assert!(
!hints
.iter()
.any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
"{hints:?}"
);
let (luma, detection, key) = rescue_example();
let (score, hints) = judged(&luma, &detection, &key, ScoreDepth::Full, &[], &[]);
let uec = score.uec.expect("the rescued stream keeps its margin");
assert_eq!(
(uec.margin, uec.worst_block_errors, uec.worst_block_capacity),
(0.0, 11, 22)
);
assert!(hints.contains(&Hint::LowCorrectionMargin {
errors: 11,
capacity: 22
}));
}
fn scan_luma(luma: &LumaImage) -> crate::report::ScanReport {
let mut config = ScanConfig::full();
config.budget_ms = None;
crate::Scanner::builder()
.profile(crate::ScanProfile::Custom(config))
.build()
.scan(ImageInput::luma8(luma.data(), luma.width(), luma.height()))
.unwrap()
}
#[test]
fn a_mirrored_symbol_scores_like_its_upright_twin() {
use crate::report::UecGrade;
use crate::rescue::test_symbols::{
from_segments, from_segments_mirrored, masked_colors, mirror, render,
};
let url = |b: &mut qrcode::bits::Bits| b.push_byte_data(b"https://qrc-ai.com/x03");
let eci26 = |b: &mut qrcode::bits::Bits| {
b.push_eci_designator(26)?;
b.push_byte_data(b"https://qrc-ai.com/x02")
};
let (v3, m) = (qrcode::Version::Normal(3), qrcode::EcLevel::M);
let (l0, width) = masked_colors(
qrcode::Version::Normal(2),
qrcode::EcLevel::L,
qrcode::canvas::MaskPattern::Checkerboard,
|b| b.push_byte_data(b"https://qrc-ai.com/x5"),
);
let twins = [
(
"no-ECI URL",
from_segments(v3, m, url),
from_segments_mirrored(v3, m, url),
),
(
"ECI 26 URL",
from_segments(v3, m, eci26),
from_segments_mirrored(v3, m, eci26),
),
(
"format word L0",
render(&l0, width),
render(&mirror(&l0, width), width),
),
];
for (name, upright, mirrored) in twins {
let (up, down) = (scan_luma(&upright), scan_luma(&mirrored));
let whole = up.score.expect("the upright twin is judged");
let score = down.score.expect("the mirrored twin is judged");
let uec = score.uec.expect("the verified stream measures a margin");
assert_eq!((uec.margin, uec.grade), (1.0, UecGrade::A), "{name}");
if name == "format word L0" {
let meta = &down.detections[0].meta;
assert_eq!((meta.ec_level, meta.mask), (Some(EcLevel::L), Some(0)));
assert_eq!(score.uec, whole.uec, "{name}");
assert!(
!down
.hints
.iter()
.any(|h| matches!(h, Hint::LowCorrectionMargin { .. })),
"{name}: {:?}",
down.hints
);
continue;
}
assert_eq!(
(score.value, score.grade, &score.axes),
(whole.value, whole.grade, &whole.axes),
"{name}"
);
assert_eq!(
(score.uec, score.structural, score.iso15415),
(whole.uec, whole.structural, whole.iso15415),
"{name}"
);
assert!(
!down.hints.iter().any(|h| matches!(
h,
Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
)),
"{name}: {:?}",
down.hints
);
assert_eq!(down.hints, up.hints, "{name}");
if name == "no-ECI URL" {
assert_eq!((score.value, score.grade), (100, Grade::Excellent));
}
}
}
#[test]
fn uec_cap_reads_the_measured_margin_published_or_not() {
use crate::report::{UecGrade, UecReport};
let d = detection_with(Some(EcLevel::Q));
let at = |margin: f32| UecReport {
margin,
grade: UecGrade::from_margin(margin),
worst_block_errors: 12,
worst_block_capacity: 24,
};
for margin in [1.0, 0.5, 0.45, 0.37, 0.30, 0.25, 0.2458, 0.10, 0.0] {
let (shown, _) = compose(axes_with(&[]), None, Some(at(margin)), true, None, &d);
let (withheld, hints) =
compose(axes_with(&[]), None, Some(at(margin)), false, None, &d);
assert_eq!(
(withheld.value, withheld.grade, withheld.weights_run),
(shown.value, shown.grade, shown.weights_run),
"margin {margin}"
);
assert_eq!(withheld.value, uec_margin_cap(margin), "margin {margin}");
assert!(shown.uec.is_some() && withheld.uec.is_none());
assert!(
!hints.iter().any(|h| matches!(
h,
Hint::RaiseErrorCorrection { .. } | Hint::LowCorrectionMargin { .. }
)),
"a withheld margin drives no hint (margin {margin}): {hints:?}"
);
}
let value = |margin: f32| {
compose(axes_with(&[]), None, Some(at(margin)), false, None, &d)
.0
.value
};
assert_eq!((value(0.30), value(0.25), value(0.0)), (76, 70, 40));
let (_, hints) = compose(axes_with(&[]), None, Some(at(0.0)), true, None, &d);
assert!(
hints.contains(&Hint::LowCorrectionMargin {
errors: 12,
capacity: 24
}) && hints.contains(&Hint::RaiseErrorCorrection {
current: EcLevel::Q
}),
"{hints:?}"
);
for publish in [true, false] {
let (score, _) = compose(axes_with(&[]), None, None, publish, None, &d);
assert_eq!(score.value, 100);
}
}
#[test]
fn uec_cap_band_edges_and_the_pre_cap_gate() {
use crate::report::{UecGrade, UecReport};
let raised = |hints: &[Hint]| {
hints
.iter()
.any(|h| matches!(h, Hint::RaiseErrorCorrection { .. }))
};
let at = |margin: f32| UecReport {
margin,
grade: UecGrade::from_margin(margin),
worst_block_errors: 0,
worst_block_capacity: 0,
};
for ec in [EcLevel::Q, EcLevel::H] {
let d = detection_with(Some(ec));
for (margin, cap, grade, band) in [
(0.25, 70, Grade::Good, UecGrade::D),
(0.2458, 69, Grade::Acceptable, UecGrade::F),
] {
assert_eq!(at(margin).grade, band);
for publish in [true, false] {
let (score, hints) =
compose(axes_with(&[]), None, Some(at(margin)), publish, None, &d);
let case = format!("{ec:?} margin {margin} publish {publish}");
assert_eq!((score.value, score.grade), (cap, grade), "{case}");
assert_eq!(
raised(&hints),
publish && ec < EcLevel::H,
"{case}: {hints:?}"
);
}
}
}
let d = detection_with(Some(EcLevel::Q));
let edge = axes_with(&[
(StressAxis::Perspective, 0, 5),
(StressAxis::Rotation, 0, 5),
]);
let (score, hints) = compose(edge, None, Some(at(0.2458)), false, None, &d);
assert_eq!(score.value, 69);
assert!(!raised(&hints), "{hints:?}");
let sunk = axes_with(&[(StressAxis::Blur, 0, 5), (StressAxis::Perspective, 0, 5)]);
let (score, hints) = compose(sunk, None, Some(at(0.2458)), false, None, &d);
assert_eq!(score.value, 62);
assert!(raised(&hints), "{hints:?}");
}
#[test]
#[ignore = "dev diagnostic"]
fn pdf417_stress_cells_repeatability() {
const RUNS: usize = 100;
let path = format!(
"{}/../../fixtures/symbology/pdf417.png",
env!("CARGO_MANIFEST_DIR")
);
let bytes = std::fs::read(&path).expect("fixture present");
let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
let (d, key) = primary_of(&planes);
assert_eq!(d.symbology, crate::report::Symbology::Pdf417);
let base = transform::downscale_to(&planes.luma, STRESS_BASE_SIDE);
let probe = CellProbe::calibrate(&base, &key, d.symbology).expect("base decodes");
let survives = |img: &LumaImage| {
(0..RUNS)
.filter(|_| detections_match(&cell_decode(img, d.symbology).detections, &key))
.count()
};
let cancel = CancelToken::new();
for side in [358u32, 256, 179, 128, 90] {
let cell = transform::downscale_to(&base, side);
let judged = (0..RUNS)
.filter(|_| cell_passes(&cell, &key, probe, &mut Bound::new(&cancel, None)))
.count();
println!(
"{side}px cell ({}x{}): direct {}/{RUNS} · otsu {}/{RUNS} · cell_passes {judged}/{RUNS}",
cell.width(),
cell.height(),
survives(&cell),
survives(&transform::otsu_threshold(&cell)),
);
}
let walk = |planes: &crate::transform::SourcePlanes| {
let mut seen = std::collections::BTreeMap::new();
for _ in 0..RUNS {
let o =
ladder::run(planes, &ScanConfig::full(), &CancelToken::new(), None).unwrap();
let texts: Vec<_> = o.merged.iter().map(|m| m.text.clone()).collect();
let stages: Vec<_> = o
.trace
.stages
.iter()
.map(|s| (s.stage.clone(), s.transforms_tried, s.detections_found))
.collect();
*seen.entry(format!("{texts:?} via {stages:?}")).or_insert(0) += 1;
}
seen
};
println!("full frame, {RUNS} ladder walks: {:#?}", walk(&planes));
let cell = transform::downscale_to(&base, 256);
let cell_input = ImageInput::luma8(cell.data(), cell.width(), cell.height());
let cell_planes = normalize(&cell_input, &Limits::default()).unwrap();
println!(
"256px pixels as an input, {RUNS} ladder walks: {:#?}",
walk(&cell_planes)
);
}
use crate::report::EngineKind as Reader;
fn qr_class(rung: bool) -> CellProbe {
CellProbe {
rung: rung.then_some(crate::ladder::DEEP_RUNGS[0]),
symbology: crate::report::Symbology::QrCode,
}
}
fn pair(variant: Variant, reader: Reader) -> Pair {
Pair { variant, reader }
}
fn micros(micros: u64) -> std::time::Duration {
std::time::Duration::from_micros(micros)
}
#[test]
fn a_fresh_schedule_tries_the_binarized_cell_first_under_the_detections_reader() {
let cancel = CancelToken::new();
let mut bound = Bound::new(&cancel, None);
bound.lead_with(&[Reader::Rxing]);
assert_eq!(
bound.schedule.order(qr_class(false)),
vec![
pair(Variant::Otsu, Reader::Rxing),
pair(Variant::Otsu, Reader::Rqrr),
pair(Variant::Plain, Reader::Rxing),
pair(Variant::Plain, Reader::Rqrr),
]
);
bound.lead_with(&[Reader::Rxing, Reader::Rqrr]);
assert_eq!(
bound.schedule.order(qr_class(true)),
vec![
pair(Variant::Otsu, Reader::Rqrr),
pair(Variant::Otsu, Reader::Rxing),
pair(Variant::Plain, Reader::Rqrr),
pair(Variant::Plain, Reader::Rxing),
pair(Variant::Rung, Reader::Rqrr),
pair(Variant::Rung, Reader::Rxing),
]
);
let linear = CellProbe {
rung: None,
symbology: crate::report::Symbology::Code128,
};
assert_eq!(
bound.schedule.order(linear),
vec![
pair(Variant::Otsu, Reader::Rxing),
pair(Variant::Plain, Reader::Rxing),
]
);
}
#[test]
fn a_schedule_tries_the_cheapest_expected_pair_first() {
let class = qr_class(false);
let otsu_x = pair(Variant::Otsu, Reader::Rxing);
let otsu_q = pair(Variant::Otsu, Reader::Rqrr);
let plain_x = pair(Variant::Plain, Reader::Rxing);
let plain_q = pair(Variant::Plain, Reader::Rqrr);
let mut schedule = Schedule::new();
schedule.record(plain_q, true, micros(900));
assert_eq!(
schedule.order(class),
vec![plain_q, otsu_x, otsu_q, plain_x]
);
schedule.record(otsu_q, true, micros(3_000));
assert_eq!(
schedule.order(class),
vec![plain_q, otsu_x, plain_x, otsu_q]
);
schedule.record(otsu_x, false, micros(900));
schedule.record(plain_x, true, micros(5_000));
assert_eq!(
schedule.order(class),
vec![plain_q, otsu_q, otsu_x, plain_x]
);
schedule.record(otsu_x, false, micros(100));
assert_eq!(
schedule.order(class),
vec![otsu_x, plain_q, otsu_q, plain_x]
);
assert_eq!(schedule.floor, Some(Schedule::class_of(micros(900))));
}
#[test]
fn a_wall_time_classes_by_its_doublings() {
for (elapsed, class) in [
(0, 0),
(1, 1),
(2, 2),
(3, 2),
(4, 3),
(1_000, 10),
(1_023, 10),
(1_024, 11),
(1_000_000, 20),
] {
assert_eq!(Schedule::class_of(micros(elapsed)), class, "{elapsed} µs");
}
assert_eq!(Schedule::class_of(std::time::Duration::MAX), 84);
}
#[test]
fn every_history_orders_every_pair_of_the_step_exactly_once() {
let class = qr_class(true);
let fresh = Schedule::new().order(class);
let mut slots: Vec<usize> = fresh.iter().map(|pair| pair.slot()).collect();
slots.sort_unstable();
assert_eq!(slots, [0, 1, 2, 3, 4, 5], "one slot per pair");
let outcomes = [
None,
Some((true, 5)),
Some((true, 9_000)),
Some((false, 5)),
Some((false, 9_000)),
];
for history in 0..outcomes.len().pow(6) {
let mut schedule = Schedule::new();
let mut rest = history;
for pair in &fresh {
if let Some((read, elapsed)) = outcomes[rest % outcomes.len()] {
schedule.record(*pair, read, micros(elapsed));
}
rest /= outcomes.len();
}
let mut order = schedule.order(class);
order.sort_by_key(|pair| pair.slot());
let mut every = fresh.clone();
every.sort_by_key(|pair| pair.slot());
assert_eq!(order, every, "history {history}");
}
}
fn whole_pass_reads(img: &LumaImage, key: &ContentKey, probe: CellProbe) -> bool {
let reads =
|img: &LumaImage| detections_match(&cell_decode(img, probe.symbology).detections, key);
reads(img)
|| reads(&transform::otsu_threshold(img))
|| probe.rung.is_some_and(|rung| reads(&rung.apply(img)))
}
#[test]
fn a_step_passes_exactly_when_the_whole_pass_reads_whatever_the_history() {
let cancel = CancelToken::new();
let (base, key, probe) = clean_base_and_probe();
let mut examples = vec![("clean".to_owned(), base, key, probe)];
for rel in [
"artistic/blob-style-monkey-logo.webp",
"symbology/code128.png",
"symbology/datamatrix.png",
"symbology/microqr.png",
] {
let (luma, detection, key) = fixture_example(rel);
let base = transform::downscale_to(&luma, STRESS_BASE_SIDE);
let probe = CellProbe::calibrate(&base, &key, detection.symbology)
.unwrap_or_else(|| panic!("{rel}: the base decodes"));
examples.push((rel.to_owned(), base, key, probe));
}
let (mut passed, mut failed) = (0, 0);
for (name, base, key, probe) in &examples {
let mut cells = vec![base.clone()];
cells.extend([256u32, 128, 72].map(|side| transform::downscale_to(base, side)));
cells.extend([2.0f32, 6.0].map(|sigma| transform::gaussian_blur(base, sigma)));
cells.extend([0.3f32, 0.02].map(|gain| transform::contrast_boost(base, gain, 1.0)));
let mut carried = [Reader::Rxing, Reader::Rqrr].map(|first| {
let mut bound = Bound::new(&cancel, None);
bound.schedule.first = first;
bound
});
for (index, cell) in cells.iter().enumerate() {
let expected = whole_pass_reads(cell, key, *probe);
if expected {
passed += 1;
} else {
failed += 1;
}
for bound in &mut carried {
assert_eq!(
cell_passes(cell, key, *probe, bound),
expected,
"{name} cell {index} carried from {:?}",
bound.schedule.first
);
}
for read in [false, true] {
let mut adverse = Bound::new(&cancel, None);
let reversed = adverse.schedule.order(*probe).into_iter().rev();
for (rank, pair) in reversed.enumerate() {
adverse.schedule.record(pair, read, micros(1 << (2 * rank)));
}
assert_eq!(
cell_passes(cell, key, *probe, &mut adverse),
expected,
"{name} cell {index} after every pair {read}"
);
}
}
}
assert!(
passed >= 12 && failed >= 8,
"the witness needs both outcomes: {passed} passed, {failed} failed"
);
}
}