From 7450f54535af6f7a4539f0a14b0f50fc4df0c7fa Mon Sep 17 00:00:00 2001 From: Nixon MAGESE Date: Fri, 30 Oct 2026 09:19:14 +0000 Subject: [PATCH] Replace the libjpeg-derived forward DCT so the crate is MIT OR Apache-2.0 The forward DCT (scalar, `wide` and AVX2) was ported from libjpeg, which is why the crate carries the IJG license next to MIT/Apache-2.0 (#15, #34, #37). This replaces all three with an implementation written from the transform's definition in ITU-T T.81 (A.3.3), and drops IJG from the crate's license. - One separable integer algorithm: a vertical then a horizontal 8-point pass, each an even half over x(n) + x(7-n) and a 4x4 odd half over x(n) - x(7-n), with constants round(2^13 * sqrt(2) * cos(m*pi/16)) and 3 extra fraction bits between the passes. Every intermediate fits in an i32. - The scalar, `wide` and AVX2 versions round at the same points and produce identical coefficients (tested). The output keeps the 8*F(u,v) scale the quantization tables expect. Accuracy against the exact transform over 50,000 blocks (a quarter at the sample extremes): worst error 0.937 (was 1.334); coefficients that are not the nearest integer 7.36% (was 13.66%). A 512x512 test image encodes with PSNR within 0.002 dB and size within 0.08% at qualities 50, 75 and 90. Speed is unchanged or better. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 2 +- LICENSE-IJG | 69 ------ src/avx2/fdct.rs | 617 ++++++++++++---------------------------------- src/fdct.rs | 621 ++++++++++++++++++----------------------------- 4 files changed, 391 insertions(+), 918 deletions(-) delete mode 100644 LICENSE-IJG diff --git a/Cargo.toml b/Cargo.toml index 070a725..df4f899 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "jpeg-encoder" version = "0.8.0" authors = ["Volker Ströbel "] edition = "2024" -license = "(MIT OR Apache-2.0) AND IJG" +license = "MIT OR Apache-2.0" description = "JPEG encoder" categories = ["multimedia::images"] keywords = ["jpg", "jpeg", "encoder", "image"] diff --git a/LICENSE-IJG b/LICENSE-IJG deleted file mode 100644 index a39a4aa..0000000 --- a/LICENSE-IJG +++ /dev/null @@ -1,69 +0,0 @@ -jpeg-encoder IJG License -======================== - -The jpeg-encoder crate declares license "(MIT OR Apache-2.0) AND IJG". -The published crate includes MIT and Apache license files, but it does not -currently include a top-level IJG license file. This Chromium-local file -documents the IJG terms for the IJG-derived portions of jpeg-encoder until the -crate publishes the missing license file upstream. - -The IJG-derived portions include, at least: - -- src/fdct.rs, which is ported from mozjpeg to Rust and states that it was part - of the Independent JPEG Group's software. -- src/avx2/fdct.rs, which is ported from mozjpeg / jfdctint-avx2.asm to Rust - and states that it is based on the x86 SIMD extension for the IJG JPEG - library. - -In the IJG terms below, "this software" refers to the IJG-derived portions of -jpeg-encoder listed above, not to the jpeg-encoder crate as a whole. The rest -of jpeg-encoder remains covered by the crate's MIT OR Apache-2.0 terms. - -Conditions of distribution and use -================================== - -In plain English: - -1. We don't promise that this software works. (But if you find any bugs, - please let us know!) -2. You can use this software for whatever you want. You don't have to pay us. -3. You may not pretend that you wrote this software. If you use it in a - program, you must acknowledge somewhere in your documentation that - you've used the IJG code. - -In legalese: - -The authors make NO WARRANTY or representation, either express or implied, -with respect to this software, its quality, accuracy, merchantability, or -fitness for a particular purpose. This software is provided "AS IS", and you, -its user, assume the entire risk as to its quality and accuracy. - -This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. -All Rights Reserved except as specified below. - -Permission is hereby granted to use, copy, modify, and distribute this -software (or portions thereof) for any purpose, without fee, subject to these -conditions: -(1) If any part of the source code for this software is distributed, then this -README file must be included, with this copyright and no-warranty notice -unaltered; and any additions, deletions, or changes to the original files -must be clearly indicated in accompanying documentation. -(2) If only executable code is distributed, then the accompanying -documentation must state that "this software is based in part on the work of -the Independent JPEG Group". -(3) Permission for use of this software is granted only if the user accepts -full responsibility for any undesirable consequences; the authors accept -NO LIABILITY for damages of any kind. - -These conditions apply to any software derived from or based on the IJG code, -not just to the unmodified library. If you use our work, you ought to -acknowledge us. - -Permission is NOT granted for the use of any IJG author's name or company name -in advertising or publicity relating to this software or products derived from -it. This software may be referred to only as "the Independent JPEG Group's -software". - -We specifically permit and encourage the use of this software as the basis of -commercial products, provided that all warranty or liability claims are -assumed by the product vendor. diff --git a/src/avx2/fdct.rs b/src/avx2/fdct.rs index c14f9be..128fe18 100644 --- a/src/avx2/fdct.rs +++ b/src/avx2/fdct.rs @@ -1,507 +1,194 @@ -/* - * Ported from mozjpeg / jfdctint-avx2.asm to rust - * 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. - */ +//! The forward DCT of [`crate::fdct`], eight lanes at a time with AVX2. +//! +//! Each vector holds one row of the block, so the vertical pass transforms +//! all eight columns at once. A transpose lets the horizontal pass do the +//! same for the rows, and a second one restores the layout. The integer +//! operations and rounding points are the scalar version's, so the +//! coefficients are identical. #[cfg(target_arch = "x86")] use core::arch::x86::{ - __m256i, _mm256_add_epi16, _mm256_add_epi32, _mm256_loadu_si256, _mm256_madd_epi16, - _mm256_packs_epi32, _mm256_permute2x128_si256, _mm256_permute4x64_epi64, _mm256_set_epi16, - _mm256_set_epi32, _mm256_set1_epi16, _mm256_sign_epi16, _mm256_slli_epi16, _mm256_srai_epi16, - _mm256_srai_epi32, _mm256_storeu_si256, _mm256_sub_epi16, _mm256_unpackhi_epi16, - _mm256_unpackhi_epi32, _mm256_unpacklo_epi16, _mm256_unpacklo_epi32, + __m128i, __m256i, _mm_load_si128, _mm256_add_epi32, _mm256_cvtepi16_epi32, _mm256_mullo_epi32, + _mm256_packs_epi32, _mm256_permute2x128_si256, _mm256_permute4x64_epi64, _mm256_set1_epi32, + _mm256_setzero_si256, _mm256_slli_epi32, _mm256_srai_epi32, _mm256_store_si256, + _mm256_sub_epi32, _mm256_unpackhi_epi32, _mm256_unpackhi_epi64, _mm256_unpacklo_epi32, + _mm256_unpacklo_epi64, }; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::{ - __m256i, _mm256_add_epi16, _mm256_add_epi32, _mm256_loadu_si256, _mm256_madd_epi16, - _mm256_packs_epi32, _mm256_permute2x128_si256, _mm256_permute4x64_epi64, _mm256_set_epi16, - _mm256_set_epi32, _mm256_set1_epi16, _mm256_sign_epi16, _mm256_slli_epi16, _mm256_srai_epi16, - _mm256_srai_epi32, _mm256_storeu_si256, _mm256_sub_epi16, _mm256_unpackhi_epi16, - _mm256_unpackhi_epi32, _mm256_unpacklo_epi16, _mm256_unpacklo_epi32, + __m128i, __m256i, _mm_load_si128, _mm256_add_epi32, _mm256_cvtepi16_epi32, _mm256_mullo_epi32, + _mm256_packs_epi32, _mm256_permute2x128_si256, _mm256_permute4x64_epi64, _mm256_set1_epi32, + _mm256_setzero_si256, _mm256_slli_epi32, _mm256_srai_epi32, _mm256_store_si256, + _mm256_sub_epi32, _mm256_unpackhi_epi32, _mm256_unpackhi_epi64, _mm256_unpacklo_epi32, + _mm256_unpacklo_epi64, }; use crate::encoder::AlignedBlock; +use crate::fdct::{C1, C2, C3, C5, C6, C7, CONST_BITS, PASS1_BITS}; -const CONST_BITS: i32 = 13; -const PASS1_BITS: i32 = 2; +const CB: i32 = CONST_BITS as i32; +const P1: i32 = PASS1_BITS as i32; -// FIX(0.298631336) -const F_0_298: i16 = 2446; -// FIX(0.390180644) -const F_0_390: i16 = 3196; -// FIX(0.541196100) -const F_0_541: i16 = 4433; -// FIX(0.765366865) -const F_0_765: i16 = 6270; -//FIX(0.899976223) -const F_0_899: i16 = 7373; -//FIX(1.175875602) -const F_1_175: i16 = 9633; -//FIX(1.501321110) -const F_1_501: i16 = 12299; -//FIX(1.847759065) -const F_1_847: i16 = 15137; -//FIX(1.961570560) -const F_1_961: i16 = 16069; -//FIX(2.053119869) -const F_2_053: i16 = 16819; -//FIX(2.562915447) -const F_2_562: i16 = 20995; -//FIX(3.072711026) -const F_3_072: i16 = 25172; - -const DESCALE_P1: i32 = CONST_BITS - PASS1_BITS; -const DESCALE_P2: i32 = CONST_BITS + PASS1_BITS; - -#[inline(always)] pub fn fdct_avx2(data: &mut AlignedBlock) { - unsafe { - fdct_avx2_internal(data); - } + // SAFETY: the encoder takes the AVX2 path only after detecting AVX2. + unsafe { fdct_avx2_internal(data) } } #[target_feature(enable = "avx2")] fn fdct_avx2_internal(data: &mut AlignedBlock) { - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PW_F130_F054_MF130_F054() -> __m256i { - _mm256_set_epi16( - F_0_541, - F_0_541 - F_1_847, - F_0_541, - F_0_541 - F_1_847, - F_0_541, - F_0_541 - F_1_847, - F_0_541, - F_0_541 - F_1_847, - F_0_541, - F_0_541 + F_0_765, - F_0_541, - F_0_541 + F_0_765, - F_0_541, - F_0_541 + F_0_765, - F_0_541, - F_0_541 + F_0_765, - ) - } - - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PW_MF078_F117_F078_F117() -> __m256i { - _mm256_set_epi16( - F_1_175, - F_1_175 - F_0_390, - F_1_175, - F_1_175 - F_0_390, - F_1_175, - F_1_175 - F_0_390, - F_1_175, - F_1_175 - F_0_390, - F_1_175, - F_1_175 - F_1_961, - F_1_175, - F_1_175 - F_1_961, - F_1_175, - F_1_175 - F_1_961, - F_1_175, - F_1_175 - F_1_961, - ) - } - - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PW_MF060_MF089_MF050_MF256() -> __m256i { - _mm256_set_epi16( - -F_2_562, - F_2_053 - F_2_562, - -F_2_562, - F_2_053 - F_2_562, - -F_2_562, - F_2_053 - F_2_562, - -F_2_562, - F_2_053 - F_2_562, - -F_0_899, - F_0_298 - F_0_899, - -F_0_899, - F_0_298 - F_0_899, - -F_0_899, - F_0_298 - F_0_899, - -F_0_899, - F_0_298 - F_0_899, - ) - } - - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PW_F050_MF256_F060_MF089() -> __m256i { - _mm256_set_epi16( - -F_0_899, - F_1_501 - F_0_899, - -F_0_899, - F_1_501 - F_0_899, - -F_0_899, - F_1_501 - F_0_899, - -F_0_899, - F_1_501 - F_0_899, - -F_2_562, - F_3_072 - F_2_562, - -F_2_562, - F_3_072 - F_2_562, - -F_2_562, - F_3_072 - F_2_562, - -F_2_562, - F_3_072 - F_2_562, - ) - } - - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PD_DESCALE_P(first_pass: bool) -> __m256i { - if first_pass { - _mm256_set_epi32( - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - 1 << (DESCALE_P1 - 1), - ) - } else { - _mm256_set_epi32( - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - 1 << (DESCALE_P2 - 1), - ) - } + let mut rows = [_mm256_setzero_si256(); 8]; + for (y, row) in rows.iter_mut().enumerate() { + // SAFETY: the block is 32-byte aligned, so each 16-byte row is 16-byte aligned. + let samples = unsafe { _mm_load_si128(data.data.as_ptr().add(y * 8) as *const __m128i) }; + *row = _mm256_cvtepi16_epi32(samples); } - #[target_feature(enable = "avx2")] - #[allow(non_snake_case)] - #[inline] - fn PW_DESCALE_P2X() -> __m256i { - // The rounding offset is added to 16-bit lanes, including odd lanes. - _mm256_set1_epi16(1 << (PASS1_BITS - 1)) - } - - // In-place 8x8x16-bit matrix transpose using AVX2 instructions - #[target_feature(enable = "avx2")] - #[inline] - fn do_transpose( - i1: __m256i, - i2: __m256i, - i3: __m256i, - i4: __m256i, - ) -> (__m256i, __m256i, __m256i, __m256i) { - //i1=(00 01 02 03 04 05 06 07 40 41 42 43 44 45 46 47) - //i2=(10 11 12 13 14 15 16 17 50 51 52 53 54 55 56 57) - //i3=(20 21 22 23 24 25 26 27 60 61 62 63 64 65 66 67) - //i4=(30 31 32 33 34 35 36 37 70 71 72 73 74 75 76 77) - - let t5 = _mm256_unpacklo_epi16(i1, i2); - let t6 = _mm256_unpackhi_epi16(i1, i2); - let t7 = _mm256_unpacklo_epi16(i3, i4); - let t8 = _mm256_unpackhi_epi16(i3, i4); + let vertical = pass::(&rows); + let horizontal = pass::(&transpose(&vertical)); + let out = transpose(&horizontal); - // transpose coefficients(phase 1) - // t1=(00 10 01 11 02 12 03 13 40 50 41 51 42 52 43 53) - // t2=(04 14 05 15 06 16 07 17 44 54 45 55 46 56 47 57) - // t3=(20 30 21 31 22 32 23 33 60 70 61 71 62 72 63 73) - // t4=(24 34 25 35 26 36 27 37 64 74 65 75 66 76 67 77) - - let t1 = _mm256_unpacklo_epi32(t5, t7); - let t2 = _mm256_unpackhi_epi32(t5, t7); - let t3 = _mm256_unpacklo_epi32(t6, t8); - let t4 = _mm256_unpackhi_epi32(t6, t8); - - // transpose coefficients(phase 2) - // t5=(00 10 20 30 01 11 21 31 40 50 60 70 41 51 61 71) - // t6=(02 12 22 32 03 13 23 33 42 52 62 72 43 53 63 73) - // t7=(04 14 24 34 05 15 25 35 44 54 64 74 45 55 65 75) - // t8=(06 16 26 36 07 17 27 37 46 56 66 76 47 57 67 77) - - ( - _mm256_permute4x64_epi64(t1, 0x8D), - _mm256_permute4x64_epi64(t2, 0x8D), - _mm256_permute4x64_epi64(t3, 0xD8), - _mm256_permute4x64_epi64(t4, 0xD8), - ) + for v in (0..8).step_by(2) { + // `packs` interleaves the two rows by 128-bit halves; put them back in order. + let packed = + _mm256_permute4x64_epi64::<0b11_01_10_00>(_mm256_packs_epi32(out[v], out[v + 1])); + // SAFETY: two rows of i16 are 32 bytes, and the block is 32-byte aligned. + unsafe { _mm256_store_si256(data.data.as_mut_ptr().add(v * 8) as *mut __m256i, packed) }; } +} - // In-place 8x8x16-bit accurate integer forward DCT using AVX2 instructions - #[target_feature(enable = "avx2")] - #[inline] - fn do_dct( - first_pass: bool, - i1: __m256i, - i2: __m256i, - i3: __m256i, - i4: __m256i, - ) -> (__m256i, __m256i, __m256i, __m256i) { - let t5 = _mm256_sub_epi16(i1, i4); // data1_0 - data6_7 = tmp6_7 - let t6 = _mm256_add_epi16(i1, i4); // data1_0 + data6_7 = tmp1_0 - let t7 = _mm256_add_epi16(i2, i3); // data3_2 + data4_5 = tmp3_2 - let t8 = _mm256_sub_epi16(i2, i3); // data3_2 - data4_5 = tmp4_5 - - // Even part - - let t6 = _mm256_permute2x128_si256(t6, t6, 0x01); // t6=tmp0_1 - let t1 = _mm256_add_epi16(t6, t7); // t1 = tmp0_1 + tmp3_2 = tmp10_11 - let t6 = _mm256_sub_epi16(t6, t7); // t6 = tmp0_1 - tmp3_2 = tmp13_12 - - let t7 = _mm256_permute2x128_si256(t1, t1, 0x01); // t7 = tmp11_10 - let t1 = _mm256_sign_epi16( - t1, - _mm256_set_epi16(-1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1), - ); // tmp10_neg11 - - let t7 = _mm256_add_epi16(t7, t1); // t7 = (tmp10 + tmp11)_(tmp10 - tmp11) - - let t1 = if first_pass { - _mm256_slli_epi16(t7, PASS1_BITS) - } else { - let t7 = _mm256_add_epi16(t7, PW_DESCALE_P2X()); - _mm256_srai_epi16(t7, PASS1_BITS) - }; - - // (Original) - // z1 = (tmp12 + tmp13) * 0.541196100; - // data2 = z1 + tmp13 * 0.765366865; - // data6 = z1 + tmp12 * -1.847759065; - // - // (This implementation) - // data2 = tmp13 * (0.541196100 + 0.765366865) + tmp12 * 0.541196100; - // data6 = tmp13 * 0.541196100 + tmp12 * (0.541196100 - 1.847759065); - - let t7 = _mm256_permute2x128_si256(t6, t6, 0x01); // t7 = tmp12_13 - let t2 = _mm256_unpacklo_epi16(t6, t7); - let t6 = _mm256_unpackhi_epi16(t6, t7); - - let t2 = _mm256_madd_epi16(t2, PW_F130_F054_MF130_F054()); // t2 = data2_6L - let t6 = _mm256_madd_epi16(t6, PW_F130_F054_MF130_F054()); // t6 = data2_6H - - let t2 = _mm256_add_epi32(t2, PD_DESCALE_P(first_pass)); - let t6 = _mm256_add_epi32(t6, PD_DESCALE_P(first_pass)); - - let t2 = if first_pass { - _mm256_srai_epi32(t2, DESCALE_P1) - } else { - _mm256_srai_epi32(t2, DESCALE_P2) - }; - let t6 = if first_pass { - _mm256_srai_epi32(t6, DESCALE_P1) - } else { - _mm256_srai_epi32(t6, DESCALE_P2) - }; - - let t3 = _mm256_packs_epi32(t2, t6); // t6 = data2_6 - - // Odd part - - let t7 = _mm256_add_epi16(t8, t5); // t7 = tmp4_5 + tmp6_7 = z3_4 - - // (Original) - // z5 = (z3 + z4) * 1.175875602; - // z3 = z3 * -1.961570560; - // z4 = z4 * -0.390180644; - // z3 += z5; - // z4 += z5; - // - // (This implementation) - // z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602; - // z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644); - - let t2 = _mm256_permute2x128_si256(t7, t7, 0x01); // t2 = z4_3 - let t6 = _mm256_unpacklo_epi16(t7, t2); - let t7 = _mm256_unpackhi_epi16(t7, t2); - - let t6 = _mm256_madd_epi16(t6, PW_MF078_F117_F078_F117()); // t6 = z3_4L - let t7 = _mm256_madd_epi16(t7, PW_MF078_F117_F078_F117()); // t7 = z3_4H - - // (Original) - // z1 = tmp4 + tmp7; - // z2 = tmp5 + tmp6; - // tmp4 = tmp4 * 0.298631336; - // tmp5 = tmp5 * 2.053119869; - // tmp6 = tmp6 * 3.072711026; - // tmp7 = tmp7 * 1.501321110; - // z1 = z1 * -0.899976223; - // z2 = z2 * -2.562915447; - // data7 = tmp4 + z1 + z3; - // data5 = tmp5 + z2 + z4; - // data3 = tmp6 + z2 + z3; - // data1 = tmp7 + z1 + z4; - // - // (This implementation) - // tmp4 = tmp4 * (0.298631336 - 0.899976223) + tmp7 * -0.899976223; - // tmp5 = tmp5 * (2.053119869 - 2.562915447) + tmp6 * -2.562915447; - // tmp6 = tmp5 * -2.562915447 + tmp6 * (3.072711026 - 2.562915447); - // tmp7 = tmp4 * -0.899976223 + tmp7 * (1.501321110 - 0.899976223); - // data7 = tmp4 + z3; - // data5 = tmp5 + z4; - // data3 = tmp6 + z3; - // data1 = tmp7 + z4; - - let t4 = _mm256_permute2x128_si256(t5, t5, 0x01); // t4 = tmp7_6 - let t2 = _mm256_unpacklo_epi16(t8, t4); - let t4 = _mm256_unpackhi_epi16(t8, t4); - - let t2 = _mm256_madd_epi16(t2, PW_MF060_MF089_MF050_MF256()); //t2 = tmp4_5L - let t4 = _mm256_madd_epi16(t4, PW_MF060_MF089_MF050_MF256()); // t4 = tmp4_5H - - let t2 = _mm256_add_epi32(t2, t6); // t2 = data7_5L - let t4 = _mm256_add_epi32(t4, t7); // t4 = data7_5H - - let t2 = _mm256_add_epi32(t2, PD_DESCALE_P(first_pass)); - let t4 = _mm256_add_epi32(t4, PD_DESCALE_P(first_pass)); - - let t2 = if first_pass { - _mm256_srai_epi32(t2, DESCALE_P1) - } else { - _mm256_srai_epi32(t2, DESCALE_P2) - }; - let t4 = if first_pass { - _mm256_srai_epi32(t4, DESCALE_P1) - } else { - _mm256_srai_epi32(t4, DESCALE_P2) - }; - - let t4 = _mm256_packs_epi32(t2, t4); // t4 = data7_5 - - let t2 = _mm256_permute2x128_si256(t8, t8, 0x01); // t2 = tmp5_4 - - let t8 = _mm256_unpacklo_epi16(t5, t2); - let t5 = _mm256_unpackhi_epi16(t5, t2); - - let t8 = _mm256_madd_epi16(t8, PW_F050_MF256_F060_MF089()); // t8 = tmp6_7L - let t5 = _mm256_madd_epi16(t5, PW_F050_MF256_F060_MF089()); // t5 = tmp6_7H - - let t8 = _mm256_add_epi32(t8, t6); // t8 = data3_1L - let t5 = _mm256_add_epi32(t5, t7); // t5 = data3_1H - - let t8 = _mm256_add_epi32(t8, PD_DESCALE_P(first_pass)); - let t5 = _mm256_add_epi32(t5, PD_DESCALE_P(first_pass)); - - let t8 = if first_pass { - _mm256_srai_epi32(t8, DESCALE_P1) - } else { - _mm256_srai_epi32(t8, DESCALE_P2) - }; - let t5 = if first_pass { - _mm256_srai_epi32(t5, DESCALE_P1) - } else { - _mm256_srai_epi32(t5, DESCALE_P2) - }; - - let t2 = _mm256_packs_epi32(t8, t5); // t2 = data3_1 - - (t1, t2, t3, t4) - } - - let data = &mut data.data; - - let ymm4 = avx_load(&data[0..16]); - let ymm5 = avx_load(&data[16..32]); - let ymm6 = avx_load(&data[32..48]); - let ymm7 = avx_load(&data[48..64]); - - // ---- Pass 1: process rows. - // ymm4=(00 01 02 03 04 05 06 07 10 11 12 13 14 15 16 17) - // ymm5=(20 21 22 23 24 25 26 27 30 31 32 33 34 35 36 37) - // ymm6=(40 41 42 43 44 45 46 47 50 51 52 53 54 55 56 57) - // ymm7=(60 61 62 63 64 65 66 67 70 71 72 73 74 75 76 77) - - let ymm0 = _mm256_permute2x128_si256(ymm4, ymm6, 0x20); - let ymm1 = _mm256_permute2x128_si256(ymm4, ymm6, 0x31); - let ymm2 = _mm256_permute2x128_si256(ymm5, ymm7, 0x20); - let ymm3 = _mm256_permute2x128_si256(ymm5, ymm7, 0x31); - - // ymm0=(00 01 02 03 04 05 06 07 40 41 42 43 44 45 46 47) - // ymm1=(10 11 12 13 14 15 16 17 50 51 52 53 54 55 56 57) - // ymm2=(20 21 22 23 24 25 26 27 60 61 62 63 64 65 66 67) - // ymm3=(30 31 32 33 34 35 36 37 70 71 72 73 74 75 76 77) - - let (ymm0, ymm1, ymm2, ymm3) = do_transpose(ymm0, ymm1, ymm2, ymm3); - let (ymm0, ymm1, ymm2, ymm3) = do_dct(true, ymm0, ymm1, ymm2, ymm3); - - // ---- Pass 2: process columns. - - let ymm4 = _mm256_permute2x128_si256(ymm1, ymm3, 0x20); // ymm4=data3_7 - let ymm1 = _mm256_permute2x128_si256(ymm1, ymm3, 0x31); // ymm1=data1_5 - - let (ymm0, ymm1, ymm2, ymm4) = do_transpose(ymm0, ymm1, ymm2, ymm4); - let (ymm0, ymm1, ymm2, ymm4) = do_dct(false, ymm0, ymm1, ymm2, ymm4); - - let ymm3 = _mm256_permute2x128_si256(ymm0, ymm1, 0x30); // ymm3=data0_1 - let ymm5 = _mm256_permute2x128_si256(ymm2, ymm1, 0x20); // ymm5=data2_3 - let ymm6 = _mm256_permute2x128_si256(ymm0, ymm4, 0x31); // ymm6=data4_5 - let ymm7 = _mm256_permute2x128_si256(ymm2, ymm4, 0x21); // ymm7=data6_7 - - avx_store(ymm3, &mut data[0..16]); - avx_store(ymm5, &mut data[16..32]); - avx_store(ymm6, &mut data[32..48]); - avx_store(ymm7, &mut data[48..64]); +#[inline] +#[target_feature(enable = "avx2")] +fn times(value: __m256i, constant: i32) -> __m256i { + _mm256_mullo_epi32(value, _mm256_set1_epi32(constant)) } -/// Safe wrapper for an unaligned AVX load +/// Divide by `2^BITS`, rounding halves up. +#[inline] #[target_feature(enable = "avx2")] +fn descale(value: __m256i) -> __m256i { + _mm256_srai_epi32::(_mm256_add_epi32(value, _mm256_set1_epi32(1 << (BITS - 1)))) +} + #[inline] -fn avx_load(input: &[i16]) -> __m256i { - assert!(input.len() == 16); - assert!(core::mem::size_of::<[i16; 16]>() == core::mem::size_of::<__m256i>()); - // SAFETY: we've checked sizes above. The load is unaligned, so no alignment requirements. - unsafe { _mm256_loadu_si256(input.as_ptr() as *const __m256i) } +#[target_feature(enable = "avx2")] +fn sum(terms: [__m256i; 4]) -> __m256i { + _mm256_add_epi32( + _mm256_add_epi32(terms[0], terms[1]), + _mm256_add_epi32(terms[2], terms[3]), + ) } -/// Safe wrapper for an unaligned AVX store +/// One 8-point pass on eight lanes: the vertical one (`LAST` false) keeps +/// `PASS1_BITS` fraction bits, the horizontal one drops them. +#[inline] #[target_feature(enable = "avx2")] +fn pass(x: &[__m256i; 8]) -> [__m256i; 8] { + let s0 = _mm256_add_epi32(x[0], x[7]); + let s1 = _mm256_add_epi32(x[1], x[6]); + let s2 = _mm256_add_epi32(x[2], x[5]); + let s3 = _mm256_add_epi32(x[3], x[4]); + let d0 = _mm256_sub_epi32(x[0], x[7]); + let d1 = _mm256_sub_epi32(x[1], x[6]); + let d2 = _mm256_sub_epi32(x[2], x[5]); + let d3 = _mm256_sub_epi32(x[3], x[4]); + + let e0 = _mm256_add_epi32(s0, s3); + let e1 = _mm256_add_epi32(s1, s2); + let f0 = _mm256_sub_epi32(s0, s3); + let f1 = _mm256_sub_epi32(s1, s2); + + let plain = [_mm256_add_epi32(e0, e1), _mm256_sub_epi32(e0, e1)]; + let products = [ + sum([times(d0, C1), times(d1, C3), times(d2, C5), times(d3, C7)]), + _mm256_add_epi32(times(f0, C2), times(f1, C6)), + sum([ + times(d0, C3), + times(d1, -C7), + times(d2, -C1), + times(d3, -C5), + ]), + sum([times(d0, C5), times(d1, -C1), times(d2, C7), times(d3, C3)]), + _mm256_sub_epi32(times(f0, C6), times(f1, C2)), + sum([times(d0, C7), times(d1, -C5), times(d2, C3), times(d3, -C1)]), + ]; + + if LAST { + [ + descale::(plain[0]), + descale::<{ CB + P1 }>(products[0]), + descale::<{ CB + P1 }>(products[1]), + descale::<{ CB + P1 }>(products[2]), + descale::(plain[1]), + descale::<{ CB + P1 }>(products[3]), + descale::<{ CB + P1 }>(products[4]), + descale::<{ CB + P1 }>(products[5]), + ] + } else { + [ + _mm256_slli_epi32::(plain[0]), + descale::<{ CB - P1 }>(products[0]), + descale::<{ CB - P1 }>(products[1]), + descale::<{ CB - P1 }>(products[2]), + _mm256_slli_epi32::(plain[1]), + descale::<{ CB - P1 }>(products[3]), + descale::<{ CB - P1 }>(products[4]), + descale::<{ CB - P1 }>(products[5]), + ] + } +} + +/// Swap the rows and columns of an 8×8 matrix of `i32`. #[inline] -fn avx_store(input: __m256i, output: &mut [i16]) { - assert!(output.len() == 16); - assert!(core::mem::size_of::<[i16; 16]>() == core::mem::size_of::<__m256i>()); - // SAFETY: we've checked sizes above. The load is unaligned, so no alignment requirements. - unsafe { _mm256_storeu_si256(output.as_mut_ptr() as *mut __m256i, input) } +#[target_feature(enable = "avx2")] +fn transpose(m: &[__m256i; 8]) -> [__m256i; 8] { + // Pairs, then quads, within each 128-bit half; then swap the halves. + let a0 = _mm256_unpacklo_epi32(m[0], m[1]); + let a1 = _mm256_unpackhi_epi32(m[0], m[1]); + let a2 = _mm256_unpacklo_epi32(m[2], m[3]); + let a3 = _mm256_unpackhi_epi32(m[2], m[3]); + let a4 = _mm256_unpacklo_epi32(m[4], m[5]); + let a5 = _mm256_unpackhi_epi32(m[4], m[5]); + let a6 = _mm256_unpacklo_epi32(m[6], m[7]); + let a7 = _mm256_unpackhi_epi32(m[6], m[7]); + + let b0 = _mm256_unpacklo_epi64(a0, a2); + let b1 = _mm256_unpackhi_epi64(a0, a2); + let b2 = _mm256_unpacklo_epi64(a1, a3); + let b3 = _mm256_unpackhi_epi64(a1, a3); + let b4 = _mm256_unpacklo_epi64(a4, a6); + let b5 = _mm256_unpackhi_epi64(a4, a6); + let b6 = _mm256_unpacklo_epi64(a5, a7); + let b7 = _mm256_unpackhi_epi64(a5, a7); + + [ + _mm256_permute2x128_si256::<0x20>(b0, b4), + _mm256_permute2x128_si256::<0x20>(b1, b5), + _mm256_permute2x128_si256::<0x20>(b2, b6), + _mm256_permute2x128_si256::<0x20>(b3, b7), + _mm256_permute2x128_si256::<0x31>(b0, b4), + _mm256_permute2x128_si256::<0x31>(b1, b5), + _mm256_permute2x128_si256::<0x31>(b2, b6), + _mm256_permute2x128_si256::<0x31>(b3, b7), + ] } #[cfg(test)] mod tests { use super::*; + use crate::fdct::{fdct_scalar, tests::blocks}; #[test] - fn test_fdct_avx2_rounding_matches_scalar() { + fn the_avx2_transform_matches_the_scalar_one() { if !std::is_x86_feature_detected!("avx2") { return; } - - // This block exposed missing rounding in odd columns of output rows 0 and 4. - let input = [ - -103, -27, 49, -104, 110, 67, 94, -37, 71, 14, 105, -112, 84, -89, -17, -35, 109, 98, - 89, 48, -119, 45, 104, -57, 67, 88, 57, 28, -87, -125, 123, 96, -71, -33, 1, -12, 52, - -47, 11, 88, 11, 98, -73, 25, -126, -40, 98, -99, -5, -51, -21, 125, -30, 110, 29, -18, - -70, 96, -119, -99, 77, 94, 21, 18, - ]; - let mut expected = AlignedBlock::new(input); - crate::fdct::fdct_scalar(&mut expected); - - let mut actual = AlignedBlock::new(input); - fdct_avx2(&mut actual); - - assert_eq!(actual.data, expected.data); + for samples in blocks() { + let mut scalar = AlignedBlock::new(samples); + let mut avx2 = AlignedBlock::new(samples); + fdct_scalar(&mut scalar); + fdct_avx2(&mut avx2); + assert_eq!(scalar.data, avx2.data, "{samples:?}"); + } } } diff --git a/src/fdct.rs b/src/fdct.rs index 3997bf7..4937897 100644 --- a/src/fdct.rs +++ b/src/fdct.rs @@ -1,423 +1,278 @@ -/* - * Ported from mozjpeg to rust - * - * This file was part of the Independent JPEG Group's software: - * Copyright (C) 1991-1996, Thomas G. Lane. - * libjpeg-turbo Modifications: - * Copyright (C) 2015, 2020, D. R. Commander. - * - * Conditions of distribution and use: - * In plain English: - * - * 1. We don't promise that this software works. (But if you find any bugs, - * please let us know!) - * 2. You can use this software for whatever you want. You don't have to pay us. - * 3. You may not pretend that you wrote this software. If you use it in a - * program, you must acknowledge somewhere in your documentation that - * you've used the IJG code. - * - * In legalese: - * - * The authors make NO WARRANTY or representation, either express or implied, - * with respect to this software, its quality, accuracy, merchantability, or - * fitness for a particular purpose. This software is provided "AS IS", and you, - * its user, assume the entire risk as to its quality and accuracy. - * - * This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding. - * All Rights Reserved except as specified below. - * - * Permission is hereby granted to use, copy, modify, and distribute this - * software (or portions thereof) for any purpose, without fee, subject to these - * conditions: - * (1) If any part of the source code for this software is distributed, then this - * README file must be included, with this copyright and no-warranty notice - * unaltered; and any additions, deletions, or changes to the original files - * must be clearly indicated in accompanying documentation. - * (2) If only executable code is distributed, then the accompanying - * documentation must state that "this software is based in part on the work of - * the Independent JPEG Group". - * (3) Permission for use of this software is granted only if the user accepts - * full responsibility for any undesirable consequences; the authors accept - * NO LIABILITY for damages of any kind. - * - * These conditions apply to any software derived from or based on the IJG code, - * not just to the unmodified library. If you use our work, you ought to - * acknowledge us. - * - * Permission is NOT granted for the use of any IJG author's name or company name - * in advertising or publicity relating to this software or products derived from - * it. This software may be referred to only as "the Independent JPEG Group's - * software". - * - * We specifically permit and encourage the use of this software as the basis of - * commercial products, provided that all warranty or liability claims are - * assumed by the product vendor. - * - * This file contains a slower but more accurate integer implementation of the - * forward DCT (Discrete Cosine Transform). - * - * A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT - * on each column. Direct algorithms are also available, but they are - * much more complex and seem not to be any faster when reduced to code. - * - * This implementation is based on an algorithm described in - * C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT - * Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics, - * Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991. - * The primary algorithm described there uses 11 multiplies and 29 adds. - * We use their alternate method with 12 multiplies and 32 adds. - * The advantage of this method is that no data path contains more than one - * multiplication; this allows a very simple and accurate implementation in - * scaled fixed-point arithmetic, with a minimal number of shifts. - */ +//! Forward discrete cosine transform of one 8×8 block. +//! +//! An implementation of the transform as the JPEG standard defines it +//! (ITU-T T.81, A.3.3): +//! +//! ```text +//! F(u,v) = 1/4 C(u) C(v) Σx Σy f(x,y) cos((2x+1)uπ/16) cos((2y+1)vπ/16) +//! ``` +//! +//! with `C(0) = 1/√2` and `C(k) = 1` otherwise. The input holds the +//! level-shifted samples, `f(x,y)` at `data[y * 8 + x]`. The quantization +//! tables carry a factor of 8 (see `quantization.rs`), so the output is +//! `8·F(u,v)`, at `data[v * 8 + u]`. +//! +//! The transform is separable: a vertical 8-point pass over the columns, then +//! a horizontal one over the rows. With the factor of 8 shared between them, +//! each pass computes +//! +//! ```text +//! X(k) = Σn x(n) · √2 C(k) cos((2n+1)kπ/16) +//! ``` +//! +//! as an even half over the sums `s(n) = x(n) + x(7-n)` (outputs 0, 2, 4 and 6) +//! and an odd half over the differences `d(n) = x(n) - x(7-n)` (outputs 1, 3, +//! 5 and 7). Outputs 0 and 4 need no multiplication; the others multiply by +//! `√2 cos(mπ/16)`, held as integers scaled by `2^CONST_BITS`. The vertical +//! pass keeps `PASS1_BITS` extra fraction bits, which the horizontal pass +//! drops with rounding. Every intermediate fits in an `i32`. +//! +//! The scalar, `wide` and AVX2 versions round at the same points, so they +//! produce identical coefficients. use crate::encoder::AlignedBlock; +use core::ops::{Add, Sub}; + +pub(crate) const CONST_BITS: u32 = 13; +pub(crate) const PASS1_BITS: u32 = 3; + +// `round(2^CONST_BITS · √2 · cos(mπ/16))` for m = 1, 2, 3, 5, 6 and 7 +// (`the_constants_follow_from_the_definition` recomputes them). +pub(crate) const C1: i32 = 11363; +pub(crate) const C2: i32 = 10703; +pub(crate) const C3: i32 = 9633; +pub(crate) const C5: i32 = 6436; +pub(crate) const C6: i32 = 4433; +pub(crate) const C7: i32 = 2260; + +/// Integer lanes the passes run on: one value, or one row of eight. +pub(crate) trait Lane: Copy + Add + Sub { + fn times(self, constant: i32) -> Self; + fn shift_left(self, bits: u32) -> Self; + /// Divide by `2^bits`, rounding halves up. + fn descale(self, bits: u32) -> Self; +} -const CONST_BITS: i32 = 13; - -#[cfg(not(feature = "use_wide"))] -pub use fdct_scalar as fdct; - -#[cfg(any(test, not(feature = "use_wide")))] -#[allow(clippy::erasing_op)] -#[allow(clippy::identity_op)] -pub fn fdct_scalar(data: &mut AlignedBlock) { - const PASS1_BITS: i32 = 2; - - const FIX_0_298631336: i32 = 2446; - const FIX_0_390180644: i32 = 3196; - const FIX_0_541196100: i32 = 4433; - const FIX_0_765366865: i32 = 6270; - const FIX_0_899976223: i32 = 7373; - const FIX_1_175875602: i32 = 9633; - const FIX_1_501321110: i32 = 12299; - const FIX_1_847759065: i32 = 15137; - const FIX_1_961570560: i32 = 16069; - const FIX_2_053119869: i32 = 16819; - const FIX_2_562915447: i32 = 20995; - const FIX_3_072711026: i32 = 25172; - - const DCT_SIZE: usize = 8; - +impl Lane for i32 { #[inline(always)] - fn descale(x: i32, n: i32) -> i32 { - // right shift with rounding - (x + (1 << (n - 1))) >> n + fn times(self, constant: i32) -> Self { + self * constant } #[inline(always)] - fn into_el(v: i32) -> i16 { - v as i16 + fn shift_left(self, bits: u32) -> Self { + self << bits } - 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 mut data2 = [0i32; 64]; - - for y in 0..8 { - let offset = y * 8; - - let tmp0 = i32::from(data[offset + 0]) + i32::from(data[offset + 7]); - let tmp7 = i32::from(data[offset + 0]) - i32::from(data[offset + 7]); - let tmp1 = i32::from(data[offset + 1]) + i32::from(data[offset + 6]); - let tmp6 = i32::from(data[offset + 1]) - i32::from(data[offset + 6]); - let tmp2 = i32::from(data[offset + 2]) + i32::from(data[offset + 5]); - let tmp5 = i32::from(data[offset + 2]) - i32::from(data[offset + 5]); - let tmp3 = i32::from(data[offset + 3]) + i32::from(data[offset + 4]); - let tmp4 = i32::from(data[offset + 3]) - i32::from(data[offset + 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; - - data2[offset + 0] = (tmp10 + tmp11) << PASS1_BITS; - data2[offset + 4] = (tmp10 - tmp11) << PASS1_BITS; - - let z1 = (tmp12 + tmp13) * FIX_0_541196100; - data2[offset + 2] = descale(z1 + (tmp13 * FIX_0_765366865), CONST_BITS - PASS1_BITS); - data2[offset + 6] = descale(z1 + (tmp12 * -FIX_1_847759065), CONST_BITS - PASS1_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) * FIX_1_175875602; /* sqrt(2) * c3 */ - - let tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ - let tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ - let tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ - let tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ - let z1 = z1 * -FIX_0_899976223; /* sqrt(2) * ( c7-c3) */ - let z2 = z2 * -FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ - let z3 = z3 * -FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ - let z4 = z4 * -FIX_0_390180644; /* sqrt(2) * ( c5-c3) */ - - let z3 = z3 + z5; - let z4 = z4 + z5; - - data2[offset + 7] = descale(tmp4 + z1 + z3, CONST_BITS - PASS1_BITS); - data2[offset + 5] = descale(tmp5 + z2 + z4, CONST_BITS - PASS1_BITS); - data2[offset + 3] = descale(tmp6 + z2 + z3, CONST_BITS - PASS1_BITS); - data2[offset + 1] = descale(tmp7 + z1 + z4, CONST_BITS - PASS1_BITS); + #[inline(always)] + fn descale(self, bits: u32) -> Self { + (self + (1 << (bits - 1))) >> bits } +} - /* Pass 2: process columns. - * We remove the PASS1_BITS scaling, but leave the results scaled up - * by an overall factor of 8. - */ - - for x in 0..8 { - let tmp0 = data2[DCT_SIZE * 0 + x] + data2[DCT_SIZE * 7 + x]; - let tmp7 = data2[DCT_SIZE * 0 + x] - data2[DCT_SIZE * 7 + x]; - let tmp1 = data2[DCT_SIZE * 1 + x] + data2[DCT_SIZE * 6 + x]; - let tmp6 = data2[DCT_SIZE * 1 + x] - data2[DCT_SIZE * 6 + x]; - let tmp2 = data2[DCT_SIZE * 2 + x] + data2[DCT_SIZE * 5 + x]; - let tmp5 = data2[DCT_SIZE * 2 + x] - data2[DCT_SIZE * 5 + x]; - let tmp3 = data2[DCT_SIZE * 3 + x] + data2[DCT_SIZE * 4 + x]; - let tmp4 = data2[DCT_SIZE * 3 + x] - data2[DCT_SIZE * 4 + x]; - - /* 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; - - data[DCT_SIZE * 0 + x] = into_el(descale(tmp10 + tmp11, PASS1_BITS)); - data[DCT_SIZE * 4 + x] = into_el(descale(tmp10 - tmp11, PASS1_BITS)); - - let z1 = (tmp12 + tmp13) * FIX_0_541196100; - data[DCT_SIZE * 2 + x] = into_el(descale( - z1 + tmp13 * FIX_0_765366865, - CONST_BITS + PASS1_BITS, - )); - data[DCT_SIZE * 6 + x] = into_el(descale( - z1 + tmp12 * -FIX_1_847759065, - CONST_BITS + PASS1_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. - */ +/// One 8-point pass before scaling: outputs 0 and 4 as plain sums, the +/// other six as products scaled by `2^CONST_BITS`. +#[inline(always)] +pub(crate) fn butterfly(x: &[L; 8]) -> [L; 8] { + let s0 = x[0] + x[7]; + let s1 = x[1] + x[6]; + let s2 = x[2] + x[5]; + let s3 = x[3] + x[4]; + let d0 = x[0] - x[7]; + let d1 = x[1] - x[6]; + let d2 = x[2] - x[5]; + let d3 = x[3] - x[4]; + + let e0 = s0 + s3; + let e1 = s1 + s2; + let f0 = s0 - s3; + let f1 = s1 - s2; + + [ + e0 + e1, + d0.times(C1) + d1.times(C3) + d2.times(C5) + d3.times(C7), + f0.times(C2) + f1.times(C6), + d0.times(C3) - d1.times(C7) - d2.times(C1) - d3.times(C5), + e0 - e1, + d0.times(C5) - d1.times(C1) + d2.times(C7) + d3.times(C3), + f0.times(C6) - f1.times(C2), + d0.times(C7) - d1.times(C5) + d2.times(C3) - d3.times(C1), + ] +} - let z1 = tmp4 + tmp7; - let z2 = tmp5 + tmp6; - let z3 = tmp4 + tmp6; - let z4 = tmp5 + tmp7; - let z5 = (z3 + z4) * FIX_1_175875602; /* sqrt(2) * c3 */ +/// The vertical pass: keep `PASS1_BITS` fraction bits. +#[inline(always)] +pub(crate) fn vertical(x: &[L; 8]) -> [L; 8] { + let raw = butterfly(x); + core::array::from_fn(|k| { + if k % 4 == 0 { + raw[k].shift_left(PASS1_BITS) + } else { + raw[k].descale(CONST_BITS - PASS1_BITS) + } + }) +} - let tmp4 = tmp4 * FIX_0_298631336; /* sqrt(2) * (-c1+c3+c5-c7) */ - let tmp5 = tmp5 * FIX_2_053119869; /* sqrt(2) * ( c1+c3-c5+c7) */ - let tmp6 = tmp6 * FIX_3_072711026; /* sqrt(2) * ( c1+c3+c5-c7) */ - let tmp7 = tmp7 * FIX_1_501321110; /* sqrt(2) * ( c1+c3-c5-c7) */ - let z1 = z1 * -FIX_0_899976223; /* sqrt(2) * ( c7-c3) */ - let z2 = z2 * -FIX_2_562915447; /* sqrt(2) * (-c1-c3) */ - let z3 = z3 * -FIX_1_961570560; /* sqrt(2) * (-c3-c5) */ - let z4 = z4 * -FIX_0_390180644; /* sqrt(2) * ( c5-c3) */ +/// The horizontal pass: drop every fraction bit. +#[inline(always)] +pub(crate) fn horizontal(x: &[L; 8]) -> [L; 8] { + let raw = butterfly(x); + core::array::from_fn(|k| { + if k % 4 == 0 { + raw[k].descale(PASS1_BITS) + } else { + raw[k].descale(CONST_BITS + PASS1_BITS) + } + }) +} - let z3 = z3 + z5; - let z4 = z4 + z5; +#[cfg(not(feature = "use_wide"))] +pub use fdct_scalar as fdct; - data[DCT_SIZE * 7 + x] = into_el(descale(tmp4 + z1 + z3, CONST_BITS + PASS1_BITS)); - data[DCT_SIZE * 5 + x] = into_el(descale(tmp5 + z2 + z4, CONST_BITS + PASS1_BITS)); - data[DCT_SIZE * 3 + x] = into_el(descale(tmp6 + z2 + z3, CONST_BITS + PASS1_BITS)); - data[DCT_SIZE * 1 + x] = into_el(descale(tmp7 + z1 + z4, CONST_BITS + PASS1_BITS)); +#[cfg(any(test, not(feature = "use_wide")))] +pub fn fdct_scalar(data: &mut AlignedBlock) { + let mut columns = [[0i32; 8]; 8]; + for (x, column) in columns.iter_mut().enumerate() { + let samples: [i32; 8] = core::array::from_fn(|y| i32::from(data.data[y * 8 + x])); + *column = vertical(&samples); + } + for (v, out) in data.data.chunks_exact_mut(8).enumerate() { + let row: [i32; 8] = core::array::from_fn(|x| columns[x][v]); + for (coefficient, value) in out.iter_mut().zip(horizontal(&row)) { + *coefficient = value as i16; + } } } -/// 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; - +impl Lane for wide::i32x8 { #[inline(always)] - fn descale_w(x: i32x8, n: i32) -> i16x8 { - // right shift with rounding - i16x8::from_i32x8_saturate((x + (1 << (n - 1))) >> n) + fn times(self, constant: i32) -> Self { + self * wide::i32x8::splat(constant) } #[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". - */ + fn shift_left(self, bits: u32) -> Self { + self << bits + } - let tmp10 = tmp0 + tmp3; - let tmp13 = tmp0 - tmp3; - let tmp11 = tmp1 + tmp2; - let tmp12 = tmp1 - tmp2; + #[inline(always)] + fn descale(self, bits: u32) -> Self { + (self + wide::i32x8::splat(1 << (bits - 1))) >> bits + } +} - let data_0; - let data_4; +#[cfg(feature = "use_wide")] +fn transpose(rows: [wide::i32x8; 8]) -> [wide::i32x8; 8] { + let rows = rows.map(wide::i32x8::to_array); + core::array::from_fn(|i| wide::i32x8::new(core::array::from_fn(|j| rows[j][i]))) +} - 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); +#[cfg(feature = "use_wide")] +pub fn fdct(data: &mut AlignedBlock) { + use wide::i32x8; + + // Each vector is a row: the vertical pass runs on all eight columns at once. + let rows: [i32x8; 8] = core::array::from_fn(|y| { + i32x8::new(core::array::from_fn(|x| i32::from(data.data[y * 8 + x]))) + }); + let vertical = vertical(&rows); + let horizontal = horizontal(&transpose(vertical)); + for (v, row) in transpose(horizontal).into_iter().enumerate() { + for (u, value) in row.to_array().into_iter().enumerate() { + data.data[v * 8 + u] = value as i16; } - - 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); - - *data = cast(pass2); } #[cfg(test)] -mod tests { - - // Inputs and outputs are taken from libjpegs jpeg_fdct_islow for a typical image +pub(crate) mod tests { + extern crate std; use super::*; + use core::f64::consts::{FRAC_1_SQRT_2, PI, SQRT_2}; + use std::vec::Vec; + + /// `8·F(u,v)` straight from the definition, in `f64`. + pub(crate) fn reference(samples: &[i16; 64]) -> [f64; 64] { + let basis = |k: usize, n: usize| ((2 * n + 1) as f64 * k as f64 * PI / 16.0).cos(); + let weight = |k: usize| if k == 0 { FRAC_1_SQRT_2 } else { 1.0 }; + core::array::from_fn(|i| { + let (v, u) = (i / 8, i % 8); + let mut sum = 0.0; + for y in 0..8 { + for x in 0..8 { + sum += f64::from(samples[y * 8 + x]) * basis(u, x) * basis(v, y); + } + } + 8.0 * 0.25 * weight(u) * weight(v) * sum + }) + } - 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, - -79, -78, -80, -79, -78, -78, -81, -80, -78, -76, - ]; - - const OUTPUT1: [i16; 64] = [ - -4786, -66, 2, -18, 12, 12, 5, -7, 223, -37, -8, 21, 8, 5, -4, 6, 60, 6, -10, 5, 0, -2, -1, - 5, 21, 21, -15, 12, -2, -7, 1, 0, -2, -5, 16, -15, 0, 5, -4, -8, 0, -7, -4, 6, 7, -4, 5, 4, - 3, 0, 1, -5, 0, -1, 4, 1, -5, 7, 0, -3, -6, 1, 1, -4, - ]; - - 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, - -45, -42, -44, -15, -20, -44, - ]; + /// Blocks at the extremes of the sample range, then pseudo-random ones. + pub(crate) fn blocks() -> Vec<[i16; 64]> { + let mut blocks = Vec::new(); + for (low, high) in [(-128, -128), (127, 127), (-128, 127), (127, -128)] { + blocks.push(core::array::from_fn(|i| { + if (i / 8 + i % 8) % 2 == 0 { low } else { high } + })); + blocks.push(core::array::from_fn( + |i| if i % 2 == 0 { low } else { high }, + )); + blocks.push(core::array::from_fn(|i| { + if (i / 8) % 2 == 0 { low } else { high } + })); + } + blocks.push(core::array::from_fn(|i| (i as i16) * 4 - 128)); + let mut state = 0x2545_f491_4f6c_dd1d_u64; + for round in 0..20_000 { + blocks.push(core::array::from_fn(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + let bits = (state >> 32) as i16; + if round % 4 == 0 { + if bits & 1 == 0 { -128 } else { 127 } + } else { + (bits & 0xff) - 128 + } + })); + } + blocks + } - const OUTPUT2: [i16; 64] = [ - -1420, 717, 187, 910, -244, 579, 222, -191, 461, 487, -497, -29, -220, 179, 63, -95, 213, - 414, -235, -187, -108, 74, -73, -70, -63, 311, 13, -290, 17, -38, -180, -47, -254, 201, - 116, -247, 102, -109, -185, -36, -310, 107, 73, -91, 126, -121, -99, -37, -253, 43, -15, - 53, 101, -91, -3, -37, -136, 12, -44, 81, 53, -45, 31, -24, - ]; + #[test] + fn the_constants_follow_from_the_definition() { + for (m, constant) in [(1, C1), (2, C2), (3, C3), (5, C5), (6, C6), (7, C7)] { + let exact = f64::from(1u32 << CONST_BITS) * SQRT_2 * (f64::from(m) * PI / 16.0).cos(); + assert_eq!(constant, exact.round() as i32, "m = {m}"); + } + } #[test] - pub fn test_fdct_libjpeg() { - let mut i1 = AlignedBlock::new(INPUT1.clone()); - fdct(&mut i1); - assert_eq!(i1.data, OUTPUT1); + fn the_transform_is_the_definition_within_one() { + for samples in blocks() { + let expected = reference(&samples); + let mut block = AlignedBlock::new(samples); + fdct_scalar(&mut block); + for (i, (&got, want)) in block.data.iter().zip(expected).enumerate() { + assert!( + (f64::from(got) - want).abs() <= 1.0, + "coefficient {i} of {samples:?}: {got} against {want}" + ); + } + } + } - let mut i2 = AlignedBlock::new(INPUT2.clone()); - fdct(&mut i2); - assert_eq!(i2.data, OUTPUT2); + #[cfg(feature = "use_wide")] + #[test] + fn the_wide_transform_matches_the_scalar_one() { + for samples in blocks() { + let mut scalar = AlignedBlock::new(samples); + let mut wide = AlignedBlock::new(samples); + fdct_scalar(&mut scalar); + fdct(&mut wide); + assert_eq!(scalar.data, wide.data, "{samples:?}"); + } } }