diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e3bd865389..7ea894bfb9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -962,11 +962,26 @@ pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option { fn quantize(b: &mut Buffer, q: f32) { for p in &mut b.px { for v in p.iter_mut() { - *v = (*v * q + 0.5).floor() / q; + *v = branchless_floor(*v * q + 0.5) / q; } } } +/// `x.floor()`, bit for bit (signed zeros, infinities and NaNs included), without a call: baseline +/// x86-64 has no SSE4.1 `roundss`, so `floor` is a software routine there, called once per sample +/// of the backdrop under every adjustment layer ([`quantize`]). This form has no branch, so the +/// loop vectorizes. +#[inline] +fn branchless_floor(x: f32) -> f32 { + // From 2^23 on every f32 is whole. Below it, adding and taking away 2^23 rounds to the + // nearest whole number; where that went up, step down. + const WHOLE: f32 = 8_388_608.0; + let a = x.abs(); + let r = ((a + WHOLE) - WHOLE).copysign(x); + let r = if r > x { r - 1.0 } else { r }; + if a < WHOLE { r } else { x } +} + /// Blend an adjustment layer's result (`adjusted`) back into the backdrop it was made from, each /// pixel by its coverage `ks` (opacity × mask) in blend mode `mode`. fn blend_back(backdrop: &mut [[f32; 4]], adjusted: &[[f32; 4]], ks: impl Iterator, mode: BlendMode) { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 99823457fa..93b048b9f9 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3624,3 +3624,19 @@ fn fully_masked_adjustment_tiles_preserve_output_and_skip_tone_work() { } } } + +#[test] +fn branchless_floor_matches_floor_bitwise() { + // Every 4099th bit pattern (all exponents, both signs, NaNs and infinities among them), plus + // the values either side of the whole numbers and of 2^23 where the rounding steps. + let mut xs: Vec = (0..=u32::MAX).step_by(4099).map(f32::from_bits).collect(); + for w in [0.0f32, 1.0, 2.0, 254.0, 255.0, 32768.0, 4_194_303.0, 4_194_304.0, 8_388_607.0, 8_388_608.0, 16_777_216.0] { + for v in [w, -w] { + xs.extend([v, v.next_up(), v.next_down(), v + 0.5, v - 0.5]); + } + } + xs.extend([f32::INFINITY, f32::NEG_INFINITY, f32::NAN, -f32::NAN, f32::MIN_POSITIVE, -f32::MIN_POSITIVE, f32::MAX, f32::MIN]); + for x in xs { + assert_eq!(branchless_floor(x).to_bits(), x.floor().to_bits(), "{x:e} ({:#010x})", x.to_bits()); + } +}