Compose: quantize floors without a libm call

Baseline x86-64 has no SSE4.1 roundss, so f32::floor is a software routine there, called once per sample of the backdrop under every adjustment layer of an 8- or 16-bit document. branchless_floor rounds through 2^23 and steps down where that went up: bit-identical to floor for every f32 (a new test sweeps every 4099th bit pattern and the edges around whole numbers and 2^23), and with no branch the loop vectorizes.
This commit is contained in:
xsvm committed 2026-10-21 12:26:49 +08:00
1 parent 420353c5ae
commit f2dce80718
2 files changed
+32 -1

No files matched your search

+16 -1
View File
@@ -962,11 +962,26 @@ pub fn adjustment_quantum(depth: photocraft_color::SampleType) -> Option<f32> {
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<Item = f32>, mode: BlendMode) {
+16
View File
@@ -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<f32> = (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());
}
}