diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89b5a94..8f44559 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -29,8 +29,8 @@ jobs: run: cargo build --verbose --features simd - name: Run tests run: cargo test --verbose --features simd - - name: Run tests use_wide - run: cargo test --verbose --features use_wide + - name: Run tests portable_simd + run: cargo test --verbose --no-default-features --features portable_simd no_std: @@ -51,6 +51,10 @@ jobs: run: cargo build --verbose --no-default-features - name: Run tests run: cargo test --verbose --no-default-features --tests + - name: Build portable_simd_no_std + run: cargo build --verbose --no-default-features --features portable_simd_no_std + - name: Run tests portable_simd_no_std + run: cargo test --verbose --no-default-features --features portable_simd_no_std --tests rustfmt: @@ -62,4 +66,4 @@ jobs: with: components: rustfmt - name: Run rustfmt check - run: cargo fmt -- --check \ No newline at end of file + run: cargo fmt -- --check diff --git a/Cargo.toml b/Cargo.toml index 070a725..f19d396 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,15 +14,21 @@ rust-version = "1.89" [features] default = ["std"] simd = ["std"] -std = [] -use_wide = ["wide", "bytemuck"] +std = ["fearless_simd?/std"] +portable_simd = ["fearless_simd", "std"] +# without std there is no runtime CPU detection: +# x86 uses SSE2, Aarch64 uses NEON, others have no SIMD +# unless explicitly enabled with `-C target-cpu` or `-C target-feature` +portable_simd_no_std = ["fearless_simd", "fearless_simd/libm"] +# Internal implementation feature; use portable_simd or portable_simd_no_std instead. +fearless_simd = ["dep:fearless_simd"] # DO NOT USE THIS IN PRODUCTION. Expose several internal functions for benchmark purposes. benchmark = [] [dependencies] -wide = { version = "1.0", optional = true, default-features = false } -bytemuck = { version = "1.24", optional = true, default-features = false } +# pairwise_dot_product is not released yet: https://github.com/linebender/fearless_simd/pull/415 +fearless_simd = { version = "1.2.0", optional = true, default-features = false } [dev-dependencies] jpeg-decoder = { version = "0.3", default-features = false } diff --git a/README.md b/README.md index b1ec299..c20d5ad 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,10 @@ encoder.encode(&data, 2, 2, ColorType::Rgb)?; ## Crate features - `std` (default): Enables functionality dependent on the std lib - `simd`: Enables SIMD optimizations (implies `std` and only AVX2 as for now) +- `portable_simd`: Enables portable SIMD using `fearless_simd` and enables `std`, including runtime CPU detection. +- `portable_simd_no_std`: Enables portable SIMD using `fearless_simd` and its `libm` math backend without enabling `std`. Uses compile-time target features when `std` is disabled. + +To build with portable SIMD and `no_std`, use `--no-default-features --features portable_simd_no_std`. ## Minimum Supported Version of Rust (MSRV) diff --git a/criterion/Cargo.toml b/criterion/Cargo.toml index de7c5e6..8a13fcd 100644 --- a/criterion/Cargo.toml +++ b/criterion/Cargo.toml @@ -11,6 +11,10 @@ members = ["."] [features] simd = ["jpeg-encoder/simd"] +portable_simd = ["fearless_simd", "jpeg-encoder/portable_simd"] +portable_simd_no_std = ["fearless_simd", "jpeg-encoder/portable_simd_no_std"] +# Internal implementation feature shared by the portable SIMD benchmarks. +fearless_simd = ["jpeg-encoder/fearless_simd"] [dependencies] jpeg-encoder = {path = "..", features = ["benchmark"]} diff --git a/criterion/benches/fdct.rs b/criterion/benches/fdct.rs index bf77599..84f40d2 100644 --- a/criterion/benches/fdct.rs +++ b/criterion/benches/fdct.rs @@ -1,6 +1,6 @@ use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use jpeg_encoder::fdct; +use jpeg_encoder::{fdct, AlignedBlock}; use std::time::Duration; const INPUT1: [i16; 64] = [ @@ -18,7 +18,7 @@ fn criterion_benchmark(c: &mut Criterion) { group.bench_function("default fdct", |b| { b.iter(|| { - let mut input = INPUT1.clone(); + let mut input = AlignedBlock::new(INPUT1); fdct( black_box(&mut input), ); @@ -31,7 +31,7 @@ fn criterion_benchmark(c: &mut Criterion) { b.iter(|| { use jpeg_encoder::fdct_avx2; - let mut input = INPUT1.clone(); + let mut input = AlignedBlock::new(INPUT1); fdct_avx2( black_box(&mut input), ); diff --git a/criterion/benches/ycbcr.rs b/criterion/benches/ycbcr.rs index 0adeb56..9bfa40b 100644 --- a/criterion/benches/ycbcr.rs +++ b/criterion/benches/ycbcr.rs @@ -1,12 +1,12 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{ + black_box, criterion_group, criterion_main, measurement::WallTime, BenchmarkGroup, Criterion, + Throughput, +}; -use jpeg_encoder::{ImageBuffer, RgbImage}; +use jpeg_encoder::ImageBuffer; use std::time::Duration; -fn create_bench_img() -> (Vec, u16, u16) { - let width = 1001; - let height = 500; - +fn create_bench_img(width: usize, height: usize) -> Vec { let mut data = Vec::with_capacity(width * height * 3); for y in 0..height { @@ -51,53 +51,74 @@ fn create_bench_img() -> (Vec, u16, u16) { } } - (data, width as u16, height as u16) + data } -fn criterion_benchmark(c: &mut Criterion) { - let (data, width, height) = create_bench_img(); - let res1 = Vec::with_capacity(usize::from(width)); - let res2 = Vec::with_capacity(usize::from(width)); - let res3 = Vec::with_capacity(usize::from(width)); - let res4 = Vec::with_capacity(usize::from(width)); - - let mut res = [res1, res2, res3, res4]; - - let mut group = c.benchmark_group("ycbcr"); - group.measurement_time(Duration::from_secs(45)); - group.warm_up_time(Duration::from_secs(10)); - - group.bench_function("default ycbcr", |b| { - let image_buffer = RgbImage(&data, width, height); - +fn bench_image(group: &mut BenchmarkGroup<'_, WallTime>, name: &str, image: impl ImageBuffer) { + let mut res = core::array::from_fn(|_| Vec::with_capacity(usize::from(image.width()))); + group.bench_function(name, |b| { b.iter(|| { - for y in 0..height { + for y in 0..image.height() { res[0].clear(); res[1].clear(); res[2].clear(); - image_buffer.fill_buffers(y, black_box(&mut res)); + image.fill_buffers(y, black_box(&mut res)); } black_box(&res); }); }); +} - #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))] - group.bench_function("ycbcr avx2", |b| { - use jpeg_encoder::RgbImageAVX2; - let image_buffer = RgbImageAVX2(&data, width, height); - - b.iter(|| { - for y in 0..height { - res[0].clear(); - res[1].clear(); - res[2].clear(); - image_buffer.fill_buffers(y, black_box(&mut res)); - } - black_box(&res); - }) - }); +fn criterion_benchmark(c: &mut Criterion) { + for width in [1001, 1920] { + let height = 500; + let rgb = create_bench_img(width as usize, height as usize); + let rgba: Vec = rgb + .chunks_exact(3) + .flat_map(|p| [p[0], p[1], p[2], 255]) + .collect(); + let bgr: Vec = rgb + .chunks_exact(3) + .flat_map(|p| [p[2], p[1], p[0]]) + .collect(); + let bgra: Vec = rgb + .chunks_exact(3) + .flat_map(|p| [p[2], p[1], p[0], 255]) + .collect(); - group.finish(); + macro_rules! compare { + ($format:literal, $data:ident, $scalar:ident, $avx:ident, $portable:ident) => {{ + let mut group = c.benchmark_group(format!("ycbcr/{}/{width}", $format)); + group.measurement_time(Duration::from_secs(3)); + group.warm_up_time(Duration::from_secs(1)); + group.throughput(Throughput::Elements(u64::from(width) * u64::from(height))); + bench_image( + &mut group, + "scalar", + jpeg_encoder::$scalar(&$data, width, height), + ); + #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))] + if std::is_x86_feature_detected!("avx2") { + bench_image( + &mut group, + "avx2", + jpeg_encoder::$avx(&$data, width, height), + ); + } + #[cfg(feature = "fearless_simd")] + bench_image( + &mut group, + "portable", + jpeg_encoder::$portable(&$data, width, height), + ); + group.finish(); + }}; + } + compare!("rgb", rgb, RgbImage, RgbImageAVX2, RgbImageSimd); + compare!("rgba", rgba, RgbaImage, RgbaImageAVX2, RgbaImageSimd); + compare!("bgr", bgr, BgrImage, BgrImageAVX2, BgrImageSimd); + compare!("bgra", bgra, BgraImage, BgraImageAVX2, BgraImageSimd); + } } criterion_group!(benches, criterion_benchmark); diff --git a/src/avx2.rs b/src/avx2.rs index f8eb103..78f590e 100644 --- a/src/avx2.rs +++ b/src/avx2.rs @@ -1,12 +1,15 @@ mod fdct; mod ycbcr; +#[cfg(not(feature = "fearless_simd"))] use crate::encoder::{AlignedBlock, Operations}; pub use fdct::fdct_avx2; pub use ycbcr::*; +#[cfg(not(feature = "fearless_simd"))] pub(crate) struct AVX2Operations; +#[cfg(not(feature = "fearless_simd"))] impl Operations for AVX2Operations { #[inline(always)] fn fdct(data: &mut AlignedBlock) { diff --git a/src/encoder.rs b/src/encoder.rs index 5f41217..bd30f5b 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -3,6 +3,11 @@ use crate::huffman::{CodingClass, HuffmanTable}; use crate::image_buffer::*; use crate::marker::Marker; use crate::quantization::{QuantizationTable, QuantizationTableType}; +#[cfg(feature = "fearless_simd")] +use crate::simd::{ + BgrImageSimd as BgrImage, BgraImageSimd as BgraImage, RgbImageSimd as RgbImage, + RgbaImageSimd as RgbaImage, +}; use crate::writer::{JfifWrite, JfifWriter, ZIGZAG}; use crate::{EncodingError, PixelDensity}; @@ -36,7 +41,7 @@ pub enum JpegColorType { #[derive(Copy, Clone)] #[repr(C, align(32))] -pub(crate) struct AlignedBlock { +pub struct AlignedBlock { pub data: [i16; 64], } @@ -484,7 +489,11 @@ impl Encoder { }); } - #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))] + #[cfg(all( + feature = "simd", + not(feature = "fearless_simd"), + any(target_arch = "x86", target_arch = "x86_64") + ))] { if std::is_x86_feature_detected!("avx2") { use crate::avx2::*; @@ -535,7 +544,11 @@ impl Encoder { /// Encode an image pub fn encode_image(self, image: I) -> Result<(), EncodingError> { - #[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))] + #[cfg(all( + feature = "simd", + not(feature = "fearless_simd"), + any(target_arch = "x86", target_arch = "x86_64") + ))] { if std::is_x86_feature_detected!("avx2") { use crate::avx2::*; diff --git a/src/fdct.rs b/src/fdct.rs index 3997bf7..c8476fb 100644 --- a/src/fdct.rs +++ b/src/fdct.rs @@ -71,14 +71,13 @@ * scaled fixed-point arithmetic, with a minimal number of shifts. */ +#[cfg(any(not(feature = "fearless_simd"), test))] use crate::encoder::AlignedBlock; +#[cfg(any(not(feature = "fearless_simd"), test))] const CONST_BITS: i32 = 13; -#[cfg(not(feature = "use_wide"))] -pub use fdct_scalar as fdct; - -#[cfg(any(test, not(feature = "use_wide")))] +#[cfg(any(not(feature = "fearless_simd"), test))] #[allow(clippy::erasing_op)] #[allow(clippy::identity_op)] pub fn fdct_scalar(data: &mut AlignedBlock) { @@ -242,148 +241,20 @@ pub fn fdct_scalar(data: &mut AlignedBlock) { } } -/// This version uses the wide crate for SIMD operations, resulting in a 80% speedup on older SSE2-capable CPUs. -/// -/// It also means that these operations can be done on ARM and WASM targets that support SIMD. -/// -/// The pure AVX2 version is still another 10-20% faster if compiling for AVX2. -#[cfg(feature = "use_wide")] -pub fn fdct(data: &mut AlignedBlock) { - use bytemuck::cast; - use wide::{i16x8, i32x8}; - - const FIX_0_298631336: i16 = 2446; - const FIX_0_390180644: i16 = 3196; - const FIX_0_541196100: i16 = 4433; - const FIX_0_765366865: i16 = 6270; - const FIX_0_899976223: i16 = 7373; - const FIX_1_175875602: i16 = 9633; - const FIX_1_501321110: i16 = 12299; - const FIX_1_847759065: i16 = 15137; - const FIX_1_961570560: i16 = 16069; - const FIX_2_053119869: i16 = 16819; - const FIX_2_562915447: i16 = 20995; - const FIX_3_072711026: i16 = 25172; - - #[inline(always)] - fn descale_w(x: i32x8, n: i32) -> i16x8 { - // right shift with rounding - i16x8::from_i32x8_saturate((x + (1 << (n - 1))) >> n) - } - - #[inline(always)] - fn kernel_32(data_w: [i16x8; 8]) -> [i16x8; 8] { - let tmp0 = data_w[0] + data_w[7]; - let tmp7 = data_w[0] - data_w[7]; - let tmp1 = data_w[1] + data_w[6]; - let tmp6 = data_w[1] - data_w[6]; - let tmp2 = data_w[2] + data_w[5]; - let tmp5 = data_w[2] - data_w[5]; - let tmp3 = data_w[3] + data_w[4]; - let tmp4 = data_w[3] - data_w[4]; - - /* Even part per LL&M figure 1 --- note that published figure is faulty; - * rotator "sqrt(2)*c1" should be "sqrt(2)*c6". - */ - - let tmp10 = tmp0 + tmp3; - let tmp13 = tmp0 - tmp3; - let tmp11 = tmp1 + tmp2; - let tmp12 = tmp1 - tmp2; - - let data_0; - let data_4; - - if SHIFT_BITS < 0 { - data_0 = tmp10 + tmp11 << -SHIFT_BITS; - data_4 = tmp10 - tmp11 << -SHIFT_BITS; - } else { - data_0 = descale_w(i32x8::from(tmp10 + tmp11), SHIFT_BITS); - data_4 = descale_w(i32x8::from(tmp10 - tmp11), SHIFT_BITS); - } - - let z1 = (tmp12 + tmp13).mul_widen(i16x8::from(FIX_0_541196100)); - let data_2 = descale_w( - z1 + (tmp13.mul_widen(i16x8::from(FIX_0_765366865))), - CONST_BITS + SHIFT_BITS, - ); - let data_6 = descale_w( - z1 + (tmp12.mul_widen(i16x8::from(-FIX_1_847759065))), - CONST_BITS + SHIFT_BITS, - ); - - /* Odd part per figure 8 --- note paper omits factor of sqrt(2). - * cK represents cos(K*pi/16). - * i0..i3 in the paper are tmp4..tmp7 here. - */ - - let z1 = tmp4 + tmp7; - let z2 = tmp5 + tmp6; - let z3 = tmp4 + tmp6; - let z4 = tmp5 + tmp7; - let z5 = (z3 + z4).mul_widen(i16x8::from(FIX_1_175875602)); - /* sqrt(2) * c3 */ - - let tmp4 = tmp4.mul_widen(i16x8::from(FIX_0_298631336)); - /* sqrt(2) * (-c1+c3+c5-c7) */ - let tmp5 = tmp5.mul_widen(i16x8::from(FIX_2_053119869)); - /* sqrt(2) * ( c1+c3-c5+c7) */ - let tmp6 = tmp6.mul_widen(i16x8::from(FIX_3_072711026)); - /* sqrt(2) * ( c1+c3+c5-c7) */ - let tmp7 = tmp7.mul_widen(i16x8::from(FIX_1_501321110)); - /* sqrt(2) * ( c1+c3-c5-c7) */ - let z1 = z1.mul_widen(i16x8::from(-FIX_0_899976223)); - /* sqrt(2) * ( c7-c3) */ - let z2 = z2.mul_widen(i16x8::from(-FIX_2_562915447)); - /* sqrt(2) * (-c1-c3) */ - let z3 = z3.mul_widen(i16x8::from(-FIX_1_961570560)); - /* sqrt(2) * (-c3-c5) */ - let z4 = z4.mul_widen(i16x8::from(-FIX_0_390180644)); - /* sqrt(2) * ( c5-c3) */ - - let z3 = z3 + z5; - let z4 = z4 + z5; - - let data_7 = descale_w(tmp4 + z1 + z3, CONST_BITS + SHIFT_BITS); - let data_5 = descale_w(tmp5 + z2 + z4, CONST_BITS + SHIFT_BITS); - let data_3 = descale_w(tmp6 + z2 + z3, CONST_BITS + SHIFT_BITS); - let data_1 = descale_w(tmp7 + z1 + z4, CONST_BITS + SHIFT_BITS); - - [ - data_0, data_1, data_2, data_3, data_4, data_5, data_6, data_7, - ] - } - - let data = &mut data.data; - - /* Pass 1: process rows. */ - /* Note results are scaled up by sqrt(8) compared to a true DCT; */ - /* furthermore, we scale the results by 2**PASS1_BITS. */ - - let data_w = i16x8::transpose(cast(*data)); - - let pass1 = kernel_32::<-2>(data_w); - - let data2 = i16x8::transpose(pass1); - - /* Pass 2: process columns. - * We remove the PASS1_BITS scaling, but leave the results scaled up - * by an overall factor of 8. - */ - - let pass2 = kernel_32::<2>(data2); +#[cfg(not(feature = "fearless_simd"))] +pub use fdct_scalar as fdct; - *data = cast(pass2); -} +#[cfg(feature = "fearless_simd")] +pub use crate::simd::fdct; #[cfg(test)] -mod tests { +pub(crate) mod tests { // Inputs and outputs are taken from libjpegs jpeg_fdct_islow for a typical image use super::*; - const INPUT1: [i16; 64] = [ + pub(crate) const INPUT1: [i16; 64] = [ -70, -71, -70, -68, -67, -67, -67, -67, -72, -73, -72, -70, -69, -69, -68, -69, -75, -76, -74, -73, -73, -72, -71, -70, -77, -78, -77, -75, -76, -75, -73, -71, -78, -77, -77, -76, -79, -77, -76, -75, -78, -78, -77, -77, -77, -77, -78, -77, -79, -79, -78, -78, -78, -78, @@ -396,7 +267,7 @@ mod tests { 3, 0, 1, -5, 0, -1, 4, 1, -5, 7, 0, -3, -6, 1, 1, -4, ]; - const INPUT2: [i16; 64] = [ + pub(crate) const INPUT2: [i16; 64] = [ 21, 28, 11, 24, -45, -37, -55, -103, 38, -8, 31, 17, -19, 49, 15, -76, 22, -48, -36, -31, -23, 35, -23, -72, 13, -30, -45, -42, -44, -15, -20, -44, 13, -30, -45, -42, -44, -15, -20, -44, 13, -30, -45, -42, -44, -15, -20, -44, 13, -30, -45, -42, -44, -15, -20, -44, 13, -30, diff --git a/src/image_buffer.rs b/src/image_buffer.rs index 2da8273..ab30e2e 100644 --- a/src/image_buffer.rs +++ b/src/image_buffer.rs @@ -132,6 +132,7 @@ fn get_line(data: &[u8], y: u16, width: u16, num_colors: usize) -> &[u8] { &data[start..end] } +#[cfg(any(not(feature = "fearless_simd"), feature = "benchmark"))] macro_rules! ycbcr_image { ($name:ident, $num_colors:expr, $o1:expr, $o2:expr, $o3:expr) => { pub struct $name<'a>(pub &'a [u8], pub u16, pub u16); @@ -198,9 +199,13 @@ macro_rules! ycbcr_image { }; } +#[cfg(any(not(feature = "fearless_simd"), feature = "benchmark"))] ycbcr_image!(RgbImage, 3, 0, 1, 2); +#[cfg(any(not(feature = "fearless_simd"), feature = "benchmark"))] ycbcr_image!(RgbaImage, 4, 0, 1, 2); +#[cfg(any(not(feature = "fearless_simd"), feature = "benchmark"))] ycbcr_image!(BgrImage, 3, 2, 1, 0); +#[cfg(any(not(feature = "fearless_simd"), feature = "benchmark"))] ycbcr_image!(BgraImage, 4, 2, 1, 0); pub(crate) struct YCbCrImage<'a>(pub &'a [u8], pub u16, pub u16); diff --git a/src/lib.rs b/src/lib.rs index 88503e3..36e9465 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,7 +31,11 @@ extern crate std; extern crate alloc; extern crate core; -#[cfg(all(feature = "simd", any(target_arch = "x86", target_arch = "x86_64")))] +#[cfg(all( + feature = "simd", + any(not(feature = "fearless_simd"), feature = "benchmark"), + any(target_arch = "x86", target_arch = "x86_64") +))] mod avx2; mod encoder; mod error; @@ -40,6 +44,8 @@ mod huffman; mod image_buffer; mod marker; mod quantization; +#[cfg(feature = "fearless_simd")] +mod simd; mod writer; pub use encoder::{ChromaSubsamplingMethod, ColorType, Encoder, JpegColorType, SamplingFactor}; @@ -48,11 +54,17 @@ pub use image_buffer::{ImageBuffer, cmyk_to_ycck, rgb_to_ycbcr}; pub use quantization::QuantizationTableType; pub use writer::{JfifWrite, PixelDensity, PixelDensityUnit}; +#[cfg(feature = "benchmark")] +pub use encoder::AlignedBlock; + #[cfg(feature = "benchmark")] pub use fdct::fdct; #[cfg(feature = "benchmark")] -pub use image_buffer::RgbImage; +pub use image_buffer::{BgrImage, BgraImage, RgbImage, RgbaImage}; + +#[cfg(all(feature = "benchmark", feature = "fearless_simd"))] +pub use simd::{BgrImageSimd, BgraImageSimd, RgbImageSimd, RgbaImageSimd}; #[cfg(all( feature = "benchmark", @@ -66,7 +78,7 @@ pub use avx2::fdct_avx2; feature = "simd", any(target_arch = "x86", target_arch = "x86_64") ))] -pub use avx2::RgbImageAVX2; +pub use avx2::{BgrImageAVX2, BgraImageAVX2, RgbImageAVX2, RgbaImageAVX2}; #[cfg(test)] mod tests { diff --git a/src/simd/fdct.rs b/src/simd/fdct.rs new file mode 100644 index 0000000..84bdcfc --- /dev/null +++ b/src/simd/fdct.rs @@ -0,0 +1,391 @@ +/* + * Portable translation of ../avx2/fdct.rs, originally ported from mozjpeg. + * Copyright 2009 Pierre Ossman for Cendio AB + * Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander. + * Based on the x86 SIMD extension for IJG JPEG library + * Copyright (C) 1999-2006, MIYASAKA Masaru. + * See ../fdct.rs for the IJG license terms. + */ + +use crate::encoder::AlignedBlock; +use fearless_simd::{Level, dispatch, i16x16, i32x8, prelude::*}; + +pub fn fdct(data: &mut AlignedBlock) { + let level = Level::try_detect().unwrap_or_else(Level::baseline); + dispatch!(level, simd => transform(simd, data)); +} + +// All helpers must inline into dispatch!'s target-feature context. +#[cfg(target_arch = "x86")] +use core::arch::x86::{__m256i, _mm256_packs_epi32}; +#[cfg(target_arch = "x86_64")] +use core::arch::x86_64::{__m256i, _mm256_packs_epi32}; + +// AVX2 unpack operates separately in each 128-bit block. Whole-vector +// interleave would instead put all of a's lower half into the first output. +#[inline(always)] +fn unpack16(a: i16x16, b: i16x16) -> (i16x16, i16x16) { + let (al, ah) = a.split(); + let (bl, bh) = b.split(); + let (ll, lh) = al.interleave(bl); + let (hl, hh) = ah.interleave(bh); + (ll.combine(hl), lh.combine(hh)) +} + +#[inline(always)] +fn unpack32(a: i16x16, b: i16x16) -> (i16x16, i16x16) { + let a = i32x8::from_bytes(a.to_bytes()); + let b = i32x8::from_bytes(b.to_bytes()); + let (al, ah) = a.split(); + let (bl, bh) = b.split(); + let (ll, lh) = al.interleave(bl); + let (hl, hh) = ah.interleave(bh); + ( + i16x16::from_bytes(ll.combine(hl).to_bytes()), + i16x16::from_bytes(lh.combine(hh).to_bytes()), + ) +} + +#[inline(always)] +fn pack(a: i32x8, b: i32x8) -> i16x16 { + // Narrow each 128-bit half: [a0..a3, b0..b3, a4..a7, b4..b7]. + // Descaled FDCT values fit i16. + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if let Some(avx512) = a.simd.level().as_avx512() { + return pack_avx512(a, b); + } else if let Some(avx2) = a.simd.level().as_avx2() { + return pack_avx2(avx2, a.into(), b.into()).simd_into(a.simd); + } + } + let (al, ah) = a.split(); + let (bl, bh) = b.split(); + al.relaxed_narrow(bl).combine(ah.relaxed_narrow(bh)) +} + +// The intrinsic has exactly the half-wise layout required by pack, including +// when called from the AVX-512 backend. +fearless_simd::kernel!( + #[inline(always)] + fn pack_avx2(simd: Avx2, a: __m256i, b: __m256i) -> __m256i { + _mm256_packs_epi32(a, b) + } +); + +// Tecnically not restricted to AVX-512 but only faster there +#[inline(always)] +fn pack_avx512(a: i32x8, b: i32x8) -> i16x16 { + // Select the low 16 bits in [a0..a3, b0..b3, a4..a7, b4..b7] order. + let indices = [ + 0, 1, 4, 5, 8, 9, 12, 13, 32, 33, 36, 37, 40, 41, 44, 45, 16, 17, 20, 21, 24, 25, 28, 29, + 48, 49, 52, 53, 56, 57, 60, 61, + ]; + #[cfg(target_endian = "big")] + let indices = indices.map(|i| i + 2); + a.concat_swizzle_dyn(b, indices).bitcast() +} + +#[inline(always)] +fn swap_halves(a: i16x16) -> i16x16 { + let (low, high) = a.split(); + high.combine(low) +} + +#[inline(always)] +fn column_pair(a: i16x16) -> i16x16 { + // Input: [first_top, second_top, first_bottom, second_bottom]. + // Each group holds four i16 values. Join the top and bottom of each column. + let halves = if REVERSED { [1, 3, 0, 2] } else { [0, 2, 1, 3] }; + a.swizzle_dyn(core::array::from_fn::<_, 32, _>(|byte| { + (halves[byte / 8] * 8 + byte % 8) as u8 + })) +} + +#[inline(always)] +fn transpose(v: [i16x16; 4]) -> [i16x16; 4] { + // Input pairs rows (0,4), (1,5), (2,6), (3,7). + let (a, b) = unpack16(v[0], v[1]); + let (c, d) = unpack16(v[2], v[3]); + let (a, c) = unpack32(a, c); + let (b, d) = unpack32(b, d); + // Output pairs columns (1,0), (3,2), (4,5), (6,7). + [ + column_pair::<_, true>(a), + column_pair::<_, true>(c), + column_pair::<_, false>(b), + column_pair::<_, false>(d), + ] +} + +#[inline(always)] +fn coefficients(simd: S, low: [i16; 2], high: [i16; 2]) -> i16x16 { + i16x16::from_fn(simd, |i| if i < 8 { low[i % 2] } else { high[i % 2] }) +} + +#[inline(always)] +fn descale(low: i32x8, high: i32x8) -> i16x16 { + let shift = if FIRST { 11 } else { 15 }; + let rounding = i32x8::splat(low.simd, 1 << (shift - 1)); + pack((low + rounding) >> shift, (high + rounding) >> shift) +} + +#[inline(always)] +fn pass(v: [i16x16; 4]) -> [i16x16; 4] { + let simd = v[0].simd; + let diff07 = v[0] - v[3]; // tmp6_7 + let sum01 = swap_halves(v[0] + v[3]); // tmp0_1 + let sum23 = v[1] + v[2]; // tmp3_2 + let diff23 = v[1] - v[2]; // tmp4_5 + let even_sum = sum01 + sum23; // tmp10_11 + let even_diff = sum01 - sum23; // tmp13_12 + let signs = i16x16::from_fn(simd, |i| if i < 8 { 1 } else { -1 }); + let even = swap_halves(even_sum) + even_sum * signs; + let data04 = if FIRST { + even << 2 + } else { + // Unlike the original AVX2 constant, round EVERY i16 lane. + (even + i16x16::splat(simd, 2)) >> 2 + }; + + // Distribute the shared 4433 product, so each output is one dot product: + // data2 = tmp13*(4433+6270) + tmp12*4433 + // data6 = tmp12*(4433-15137) + tmp13*4433 + let c26 = coefficients(simd, [4433 + 6270, 4433], [4433 - 15137, 4433]); + let (a, b) = unpack16(even_diff, swap_halves(even_diff)); + let data26 = descale::<_, FIRST>(a.pairwise_dot_product(c26), b.pairwise_dot_product(c26)); + + // Combine z5 into z3 and z4 before multiplication. + let z34 = diff23 + diff07; + let (a, b) = unpack16(z34, swap_halves(z34)); + let c34 = coefficients(simd, [9633 - 16069, 9633], [9633 - 3196, 9633]); + let zlow = a.pairwise_dot_product(c34); + let zhigh = b.pairwise_dot_product(c34); + + // Similarly combine z1/z2 into the four remaining odd products. + let c75 = coefficients(simd, [2446 - 7373, -7373], [16819 - 20995, -20995]); + let (a, b) = unpack16(diff23, swap_halves(diff07)); + let data75 = descale::<_, FIRST>( + a.pairwise_dot_product(c75) + zlow, + b.pairwise_dot_product(c75) + zhigh, + ); + let c31 = coefficients(simd, [25172 - 20995, -20995], [12299 - 7373, -7373]); + let (a, b) = unpack16(diff07, swap_halves(diff23)); + let data31 = descale::<_, FIRST>( + a.pairwise_dot_product(c31) + zlow, + b.pairwise_dot_product(c31) + zhigh, + ); + [data04, data31, data26, data75] +} + +#[inline(always)] +fn transform(simd: S, block: &mut AlignedBlock) { + let data = &mut block.data; + let (r0, r1) = i16x16::from_slice(simd, &data[..16]).split(); + let (r2, r3) = i16x16::from_slice(simd, &data[16..32]).split(); + let (r4, r5) = i16x16::from_slice(simd, &data[32..48]).split(); + let (r6, r7) = i16x16::from_slice(simd, &data[48..]).split(); + let rows = [ + r0.combine(r4), + r1.combine(r5), + r2.combine(r6), + r3.combine(r7), + ]; + let [a, b, c, d] = pass::<_, true>(transpose(rows)); + let (b0, b1) = b.split(); + let (d0, d1) = d.split(); + let columns = [a, b1.combine(d1), c, b0.combine(d0)]; + let [a, b, c, d] = pass::<_, false>(transpose(columns)); + let (a0, a1) = a.split(); + let (b0, b1) = b.split(); + let (c0, c1) = c.split(); + let (d0, d1) = d.split(); + a0.combine(b1).store_slice(&mut data[..16]); + c0.combine(b0).store_slice(&mut data[16..32]); + a1.combine(d1).store_slice(&mut data[32..48]); + c1.combine(d0).store_slice(&mut data[48..]); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::fdct::fdct_scalar; + use alloc::{vec, vec::Vec}; + + fn levels() -> Vec { + let detected = Level::try_detect().unwrap_or_else(Level::baseline); + let mut levels = vec![Level::baseline()]; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if let Some(s) = detected.as_sse2() { + levels.push(s.level()); + } + if let Some(s) = detected.as_sse4_2() { + levels.push(s.level()); + } + if let Some(s) = detected.as_avx2() { + levels.push(s.level()); + } + } + levels.dedup_by_key(|level| core::mem::discriminant(level)); + levels + } + + #[inline(always)] + fn check_layout(simd: S) { + let a = i16x16::from_fn(simd, |i| i as i16); + let b = a + i16x16::splat(simd, 100); + let (low, high) = unpack16(a, b); + assert_eq!( + <[i16; 16]>::from(low), + [ + 0, 100, 1, 101, 2, 102, 3, 103, 8, 108, 9, 109, 10, 110, 11, 111 + ] + ); + assert_eq!( + <[i16; 16]>::from(high), + [ + 4, 104, 5, 105, 6, 106, 7, 107, 12, 112, 13, 113, 14, 114, 15, 115 + ] + ); + let (low, high) = unpack32(a, b); + assert_eq!( + <[i16; 16]>::from(low), + [ + 0, 1, 100, 101, 2, 3, 102, 103, 8, 9, 108, 109, 10, 11, 110, 111 + ] + ); + assert_eq!( + <[i16; 16]>::from(high), + [ + 4, 5, 104, 105, 6, 7, 106, 107, 12, 13, 112, 113, 14, 15, 114, 115 + ] + ); + let a = i32x8::simd_from(simd, [-8192, -4096, -32768, -1, 0, 32767, 4096, 8192]); + let b = i32x8::from_fn(simd, |i| 100 + i as i32); + assert_eq!( + <[i16; 16]>::from(pack(a, b)), + [ + -8192, -4096, -32768, -1, 100, 101, 102, 103, 0, 32767, 4096, 8192, 104, 105, 106, + 107 + ] + ); + + let rows = core::array::from_fn(|r| { + i16x16::from_fn(simd, |i| ((r + (i / 8) * 4) * 8 + i % 8) as i16) + }); + let result = transpose(rows); + for (v, columns) in result.into_iter().zip([[1, 0], [3, 2], [4, 5], [6, 7]]) { + let expected = core::array::from_fn(|i| ((i % 8) * 8 + columns[i / 8]) as i16); + assert_eq!(<[i16; 16]>::from(v), expected); + } + } + + #[test] + fn lane_layout_and_narrowing() { + for level in levels() { + dispatch!(level, simd => check_layout(simd)); + } + } + + #[inline(always)] + fn check_pairwise_dot_product(simd: S) { + let inputs = [ + ([i16::MIN; 16], [i16::MIN; 16]), + ( + core::array::from_fn(|i| (i as i16 - 8) * 4095), + core::array::from_fn(|i| if i % 2 == 0 { i16::MIN } else { i16::MAX }), + ), + ( + core::array::from_fn(|i| i as i16 - 8), + core::array::from_fn(|i| 15 - i as i16), + ), + ]; + for (a, b) in inputs { + let expected: [i32; 8] = core::array::from_fn(|i| { + (i32::from(a[2 * i]) * i32::from(b[2 * i])) + .wrapping_add(i32::from(a[2 * i + 1]) * i32::from(b[2 * i + 1])) + }); + let a = i16x16::simd_from(simd, a); + let b = i16x16::simd_from(simd, b); + assert_eq!(<[i32; 8]>::from(a.pairwise_dot_product(b)), expected); + } + } + + #[test] + fn adjacent_pair_multiply_add() { + for level in levels() { + dispatch!(level, simd => check_pairwise_dot_product(simd)); + } + } + + fn random_block(state: &mut u64) -> [i16; 64] { + core::array::from_fn(|_| { + *state ^= *state << 13; + *state ^= *state >> 7; + *state ^= *state << 17; + (*state & 255) as i16 - 128 + }) + } + + #[inline(always)] + fn compare(simd: S, input: [i16; 64]) { + let mut actual = AlignedBlock::new(input); + let mut expected = actual; + fdct_scalar(&mut expected); + transform(simd, &mut actual); + assert_eq!( + actual.data, + expected.data, + "level: {:?}, input: {:?}", + simd.level(), + input + ); + } + + #[inline(always)] + fn check_blocks(simd: S) { + for value in [-128, -1, 0, 1, 127] { + compare(simd, [value; 64]); + } + for i in 0..64 { + for value in [-128, 1, 127] { + let mut input = [0; 64]; + input[i] = value; + compare(simd, input); + } + } + for axis in [1, 8, 9] { + compare( + simd, + core::array::from_fn(|i| if (i / axis) % 2 == 0 { -128 } else { 127 }), + ); + } + compare(simd, crate::fdct::tests::INPUT1); + compare(simd, crate::fdct::tests::INPUT2); + let mut state = 12345; + for _ in 0..10_000 { + compare(simd, random_block(&mut state)); + } + } + + #[test] + fn matches_scalar_on_every_backend() { + for level in levels() { + dispatch!(level, simd => check_blocks(simd)); + } + } + + #[test] + fn rounds_odd_columns_in_rows_zero_and_four() { + let input = random_block(&mut 12345); + for level in levels() { + let mut block = AlignedBlock::new(input); + dispatch!(level, simd => transform(simd, &mut block)); + // The original AVX2 path gives -99, -1334 and -1228 here. + assert_eq!( + (block.data[1], block.data[33], block.data[37]), + (-98, -1333, -1227) + ); + } + } +} diff --git a/src/simd/mod.rs b/src/simd/mod.rs new file mode 100644 index 0000000..06c13b6 --- /dev/null +++ b/src/simd/mod.rs @@ -0,0 +1,5 @@ +mod fdct; +mod ycbcr; + +pub use fdct::fdct; +pub use ycbcr::*; diff --git a/src/simd/ycbcr.rs b/src/simd/ycbcr.rs new file mode 100644 index 0000000..5c815cf --- /dev/null +++ b/src/simd/ycbcr.rs @@ -0,0 +1,267 @@ +//! Portable RGB to YCbCr conversion, using the same fixed-point arithmetic as AVX2. + +use alloc::vec::Vec; +use fearless_simd::{Level, dispatch, i32x8, prelude::*, u8x16, u32x8}; +#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))] +use fearless_simd::{i32x16, u8x64, u32x16}; + +use crate::{ImageBuffer, JpegColorType, rgb_to_ycbcr}; + +fn level() -> Level { + Level::try_detect().unwrap_or_else(Level::baseline) +} + +#[inline(always)] +fn load(simd: S, data: &[u8]) -> i32x8 { + // Two loads cover exactly eight pixels, overlapping by eight bytes for RGB. + // Shuffling within 128-bit blocks avoids AVX2 cross-lane byte permutations. + let low = u8x16::from_slice(simd, &data[..16]); + let high = u8x16::from_slice(simd, &data[8 * N - 16..]); + let pixels = low.combine(high); + let indices = core::array::from_fn::<_, 32, _>(|i| { + let offset = if i < 16 { 0 } else { 16 - 4 * N }; + (offset + (i % 16 / 4) * N + OFFSET) as u8 + }); + // Repeat each selected byte across a u32, then mask to zero-extend it. + // This works on either endianness and lets LLVM fold the mask into PSHUFB. + let channel: i32x8 = pixels.swizzle_dyn_within_blocks(indices).bitcast(); + channel & 255 +} + +#[inline(always)] +fn pack(data: i32x8) -> [u8; 8] { + // Rounded Y/Cb/Cr are all in 0..=255. Keep narrowing in SIMD: extracting + // lanes and casting them individually generates scalar shifts and inserts. + let data: u32x8 = (data >> 16).bitcast(); + let (low, high) = data.split(); + let words = low.relaxed_narrow(high); + let bytes = words.relaxed_narrow(words); + <[u8; 16]>::from(bytes)[..8].try_into().unwrap() +} + +// Process sixteen pixels using AVX-512 wide vectors or groups of NEON vectors. +#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))] +#[inline(always)] +fn load16(simd: S, data: &[u8]) -> i32x16 { + // RGB has only 48 bytes. Copy exactly those bytes and leave the rest zero; + // never read past the chunk, including at the end of the image. LLVM keeps + // this in registers (a 32-byte load plus a 16-byte load on x86). + let mut padded = [0u8; 64]; + padded[..16 * N].copy_from_slice(&data[..16 * N]); + let pixels = u8x64::from_slice(simd, &padded); + if N == 4 { + // RGBA/BGRA already occupy one u32 per pixel. + let words: i32x16 = pixels.bitcast(); + let byte = if cfg!(target_endian = "little") { + OFFSET + } else { + 3 - OFFSET + }; + return (words >> (byte * 8) as u32) & 255; + } + // Selecting a zero padding byte for the upper three bytes also widens + // each color channel to i32 (one VPERMB per channel on AVX-512). + let indices = core::array::from_fn::<_, 64, _>(|i| { + let low_byte = if cfg!(target_endian = "little") { 0 } else { 3 }; + if i % 4 == low_byte { + ((i / 4) * N + OFFSET) as u8 + } else { + 63 + } + }); + pixels.swizzle_dyn(indices).bitcast() +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))] +#[inline(always)] +fn pack16(data: i32x16) -> [u8; 16] { + let data: u32x16 = (data >> 16).bitcast(); + let (low, high) = data.split(); + let words = low.relaxed_narrow(high); + let (low, high) = words.split(); + low.relaxed_narrow(high).into() +} + +// Inline into dispatch!'s target-feature context, as in the portable FDCT. +#[inline(always)] +fn convert( + simd: S, + line: &[u8], + buffers: &mut [Vec; 4], +) { + let [ys, cbs, crs, _] = buffers; + let width = line.len() / N; + ys.reserve(width); + cbs.reserve(width); + crs.reserve(width); + + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + let use_16 = simd.level().as_avx512().is_some(); + #[cfg(target_arch = "aarch64")] + let use_16 = simd.level().as_neon().is_some(); + #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64"))] + let line = if use_16 { + let mut chunks = line.chunks_exact(16 * N); + for data in &mut chunks { + let r = load16::<_, N, R>(simd, data); + let g = load16::<_, N, G>(simd, data); + let b = load16::<_, N, B>(simd, data); + let y = r * 19595 + g * 38470 + b * 7471 + 0x7FFF; + let cb = r * -11059 - g * 21709 + b * 32768 + ((128 << 16) + 0x7FFF); + let cr = r * 32768 - g * 27439 - b * 5329 + ((128 << 16) + 0x7FFF); + ys.extend_from_slice(&pack16(y)); + cbs.extend_from_slice(&pack16(cb)); + crs.extend_from_slice(&pack16(cr)); + } + chunks.remainder() + } else { + line + }; + let mut chunks = line.chunks_exact(8 * N); + for data in &mut chunks { + let r = load::<_, N, R>(simd, data); + let g = load::<_, N, G>(simd, data); + let b = load::<_, N, B>(simd, data); + let y = r * 19595 + g * 38470 + b * 7471 + 0x7FFF; + let cb = r * -11059 - g * 21709 + b * 32768 + ((128 << 16) + 0x7FFF); + let cr = r * 32768 - g * 27439 - b * 5329 + ((128 << 16) + 0x7FFF); + ys.extend_from_slice(&pack(y)); + cbs.extend_from_slice(&pack(cb)); + crs.extend_from_slice(&pack(cr)); + } + for data in chunks.remainder().chunks_exact(N) { + let (y, cb, cr) = rgb_to_ycbcr(data[R], data[G], data[B]); + ys.push(y); + cbs.push(cb); + crs.push(cr); + } +} + +macro_rules! ycbcr_image { + ($name:ident, $n:expr, $r:expr, $g:expr, $b:expr) => { + pub struct $name<'a>(pub &'a [u8], pub u16, pub u16); + + impl ImageBuffer for $name<'_> { + fn get_jpeg_color_type(&self) -> JpegColorType { + JpegColorType::Ycbcr + } + + fn width(&self) -> u16 { + self.1 + } + + fn height(&self) -> u16 { + self.2 + } + + fn fill_buffers(&self, y: u16, buffers: &mut [Vec; 4]) { + let width = usize::from(self.1) * $n; + let start = usize::from(y) * width; + let line = &self.0[start..start + width]; + dispatch!(level(), simd => convert::<_, $n, $r, $g, $b>(simd, line, buffers)); + } + } + }; +} + +ycbcr_image!(RgbImageSimd, 3, 0, 1, 2); +ycbcr_image!(RgbaImageSimd, 4, 0, 1, 2); +ycbcr_image!(BgrImageSimd, 3, 2, 1, 0); +ycbcr_image!(BgraImageSimd, 4, 2, 1, 0); + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + fn levels() -> Vec { + let detected = level(); + let mut levels = vec![Level::baseline()]; + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + if let Some(s) = detected.as_sse2() { + levels.push(s.level()); + } + if let Some(s) = detected.as_sse4_2() { + levels.push(s.level()); + } + if let Some(s) = detected.as_avx2() { + levels.push(s.level()); + } + } + levels.push(detected); + levels.dedup_by_key(|level| core::mem::discriminant(level)); + levels + } + + fn check_format( + make_image: impl Fn(&[u8], u16, u16, u16, &mut [Vec; 4]), + ) { + let mut state = 42u64; + for width in (0..=33).chain([127, 128, 129, 515]) { + // Deliberately unaligned input, distinct rows and arbitrary alpha values. + let data: Vec = (0..1 + width * N * 3) + .map(|_| { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1); + (state >> 32) as u8 + }) + .collect(); + let data = &data[1..]; + let initial = [vec![7, 8], vec![9], vec![], vec![42, 43]]; + let mut expected = initial.clone(); + for pixel in data.chunks_exact(N) { + let (y, cb, cr) = rgb_to_ycbcr(pixel[R], pixel[G], pixel[B]); + expected[0].push(y); + expected[1].push(cb); + expected[2].push(cr); + } + for level in levels() { + let mut actual = initial.clone(); + for row in 0..3 { + let line = &data[row * width * N..(row + 1) * width * N]; + dispatch!(level, simd => convert::<_, N, R, G, B>(simd, line, &mut actual)); + } + assert_eq!(actual, expected, "width {width}, level {level:?}"); + } + let mut actual = initial; + for row in 0..3 { + make_image(data, width as u16, 3, row, &mut actual); + } + assert_eq!(actual, expected, "dispatched image, width {width}"); + } + } + + #[test] + fn formats_rows_tails_and_append() { + check_format::<3, 0, 1, 2>(|d, w, h, y, out| RgbImageSimd(d, w, h).fill_buffers(y, out)); + check_format::<4, 0, 1, 2>(|d, w, h, y, out| RgbaImageSimd(d, w, h).fill_buffers(y, out)); + check_format::<3, 2, 1, 0>(|d, w, h, y, out| BgrImageSimd(d, w, h).fill_buffers(y, out)); + check_format::<4, 2, 1, 0>(|d, w, h, y, out| BgraImageSimd(d, w, h).fill_buffers(y, out)); + } + + #[test] + fn every_rgb_matches_scalar() { + // All 2^24 colors cover fixed-point rounding boundaries and output extrema. + let mut data = vec![0; 256 * 256 * 3]; + let mut expected: [Vec; 4] = core::array::from_fn(|_| Vec::new()); + let mut actual = expected.clone(); + for level in levels() { + for r in 0..=255u8 { + for (i, pixel) in data.chunks_exact_mut(3).enumerate() { + pixel.copy_from_slice(&[r, (i >> 8) as u8, i as u8]); + } + for buf in expected.iter_mut().chain(actual.iter_mut()) { + buf.clear(); + } + for pixel in data.chunks_exact(3) { + let (y, cb, cr) = rgb_to_ycbcr(pixel[0], pixel[1], pixel[2]); + expected[0].push(y); + expected[1].push(cb); + expected[2].push(cr); + } + dispatch!(level, simd => convert::<_, 3, 0, 1, 2>(simd, &data, &mut actual)); + assert_eq!(actual, expected, "r {r}, level {level:?}"); + } + } + } +}