jixel 0.2.26

JPEG XL encoder
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
 * // Copyright (c) Radzivon Bartoshyk 7/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use std::arch::x86_64::*;

#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "avx2")]
pub(crate) fn quantize_block_ac_avx2(
    block_in: &[f32],
    c: usize,
    qm: &[f32],
    quant: i32,
    scale: f32,
    qm_multiplier: f32,
    distance: f32,
    xsize: usize,
    ysize: usize,
    block_out: &mut [i32],
) {
    let width = xsize * 8;
    let height = ysize * 8;
    let n = width * height;

    debug_assert_eq!(qm.len(), n);
    debug_assert!(block_in.len() >= n, "block_in too small");
    debug_assert!(block_out.len() >= n, "block_out too small");
    debug_assert!(width.is_multiple_of(8));

    let qm = &qm[..n];
    let block_in = &block_in[..n];
    let block_out = &mut block_out[..n];

    let thr = crate::group::quantize_ac_thresholds_scaled(c, xsize, ysize, distance, qm_multiplier);
    let q_scaled = crate::group::quantize_ac_q_scaled(quant, scale, qm_multiplier);

    let half = width / 2;
    let qs = _mm256_set1_ps(q_scaled);
    let sign = _mm256_set1_ps(-0.0);
    let zero_i = _mm256_setzero_si256();
    let lane_ids = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);

    for (y, ((qm_row, in_row), out_row)) in qm
        .chunks_exact(width)
        .zip(block_in.chunks_exact(width))
        .zip(block_out.chunks_exact_mut(width))
        .take(height)
        .enumerate()
    {
        let yfix = if y >= height / 2 { 2 } else { 0 };
        let thr_lo = thr[yfix];
        let thr_hi = thr[yfix + 1];

        for (x0, ((qm8, in8), out8)) in qm_row
            .as_chunks::<8>()
            .0
            .iter()
            .zip(in_row.as_chunks::<8>().0.iter())
            .zip(out_row.as_chunks_mut::<8>().0.iter_mut())
            .enumerate()
        {
            let x = x0 * 8;
            let thr_v = if x + 8 <= half {
                _mm256_set1_ps(thr_lo)
            } else if x >= half {
                _mm256_set1_ps(thr_hi)
            } else {
                // Width 8 is the only current shape where one AVX vector crosses
                // the low/high threshold boundary (half = 4).
                let lane_x = _mm256_add_epi32(_mm256_set1_epi32(x as i32), lane_ids);
                let hi = _mm256_cmpgt_epi32(lane_x, _mm256_set1_epi32(half as i32 - 1));
                _mm256_blendv_ps(
                    _mm256_set1_ps(thr_lo),
                    _mm256_set1_ps(thr_hi),
                    _mm256_castsi256_ps(hi),
                )
            };

            let qmv = unsafe { _mm256_loadu_ps(qm8.as_ptr()) };
            let inv = unsafe { _mm256_loadu_ps(in8.as_ptr()) };
            let val = _mm256_mul_ps(_mm256_mul_ps(qmv, qs), inv);
            let abs = _mm256_andnot_ps(sign, val);
            let keep = _mm256_cmp_ps::<_CMP_GE_OQ>(abs, thr_v);
            let truncated = _mm256_round_ps::<{ _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC }>(val);
            let frac = _mm256_sub_ps(val, truncated);
            let abs_frac = _mm256_andnot_ps(sign, frac);
            let ge_half = _mm256_cmp_ps::<_CMP_GE_OQ>(abs_frac, _mm256_set1_ps(0.5));
            let signed_one = _mm256_or_ps(_mm256_set1_ps(1.0), _mm256_and_ps(val, sign));
            let q =
                _mm256_cvttps_epi32(_mm256_add_ps(truncated, _mm256_and_ps(signed_one, ge_half)));
            let q = _mm256_blendv_epi8(zero_i, q, _mm256_castps_si256(keep));
            unsafe { _mm256_storeu_si256(out8.as_mut_ptr().cast::<__m256i>(), q) };
        }
    }
}

#[inline]
#[target_feature(enable = "avx2")]
fn round_ties_away_i32x8(value: __m256) -> __m256i {
    let sign = _mm256_set1_ps(-0.0);
    let truncated = _mm256_round_ps::<{ _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC }>(value);
    let fraction = _mm256_sub_ps(value, truncated);
    let at_least_half =
        _mm256_cmp_ps::<_CMP_GE_OQ>(_mm256_andnot_ps(sign, fraction), _mm256_set1_ps(0.5));
    let signed_one = _mm256_or_ps(_mm256_set1_ps(1.0), _mm256_and_ps(value, sign));
    let rounded = _mm256_add_ps(truncated, _mm256_and_ps(signed_one, at_least_half));
    let quantized = _mm256_cvttps_epi32(rounded);
    let positive_overflow = _mm256_cmp_ps::<_CMP_GE_OQ>(rounded, _mm256_set1_ps(2_147_483_648.0));
    let quantized = _mm256_blendv_epi8(
        quantized,
        _mm256_set1_epi32(i32::MAX),
        _mm256_castps_si256(positive_overflow),
    );
    let nan = _mm256_cmp_ps::<_CMP_UNORD_Q>(value, value);
    _mm256_blendv_epi8(quantized, _mm256_setzero_si256(), _mm256_castps_si256(nan))
}

#[inline]
#[target_feature(enable = "avx2")]
fn store_quant_field_x8(dest: &mut [u8; 8], value: __m256) {
    let rounded = round_ties_away_i32x8(value);
    let clamped = _mm256_min_epi32(
        _mm256_max_epi32(rounded, _mm256_set1_epi32(1)),
        _mm256_set1_epi32(255),
    );
    let nan = _mm256_cmp_ps::<_CMP_UNORD_Q>(value, value);
    let clamped = _mm256_blendv_epi8(clamped, _mm256_setzero_si256(), _mm256_castps_si256(nan));
    let packed16 = _mm_packus_epi32(
        _mm256_castsi256_si128(clamped),
        _mm256_extracti128_si256::<1>(clamped),
    );
    let packed8 = _mm_packus_epi16(packed16, packed16);
    unsafe { _mm_storeu_si64(dest.as_mut_ptr().cast(), packed8) }
}

#[inline]
#[target_feature(enable = "avx2")]
fn apply_quant_field_gain_x8(dest: &mut [u8; 8], gain: __m256) {
    let bytes = unsafe { _mm_loadu_si64(dest.as_ptr().cast()) };
    let value = _mm256_mul_ps(_mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes)), gain);
    store_quant_field_x8(dest, value);
}

#[target_feature(enable = "avx2")]
pub(crate) fn apply_quant_field_gain_avx2(
    image: &mut crate::image::ImageB,
    x0: usize,
    y0: usize,
    width: usize,
    height: usize,
    gain: f32,
) {
    let gain = _mm256_set1_ps(gain);
    for y in y0..y0 + height {
        let values = &mut image.row_mut(y)[x0..x0 + width];
        let (values8, tail) = values.as_chunks_mut::<8>();
        for values in values8 {
            apply_quant_field_gain_x8(values, gain);
        }
        if !tail.is_empty() {
            let mut values = [0u8; 8];
            values[..tail.len()].copy_from_slice(tail);
            apply_quant_field_gain_x8(&mut values, gain);
            tail.copy_from_slice(&values[..tail.len()]);
        }
    }
}

#[inline]
#[target_feature(enable = "avx2,fma")]
fn apply_structure_aq_x8(
    corrections: &[f32; 8],
    dest: &mut [u8; 8],
    scale: __m256,
    center: __m256,
) {
    let correction = unsafe { _mm256_loadu_ps(corrections.as_ptr()) };
    let delta = _mm256_mul_ps(_mm256_sub_ps(correction, center), scale);
    let clamped = _mm256_max_ps(
        _mm256_min_ps(delta, _mm256_set1_ps(0.22)),
        _mm256_set1_ps(-0.18),
    );
    let valid = _mm256_cmp_ps::<_CMP_ORD_Q>(delta, delta);
    let delta = _mm256_blendv_ps(delta, clamped, valid);
    let gain = super::adaptive_quant::fast_exp2_x8(delta);
    let bytes = _mm_cvtsi64_si128(i64::from_ne_bytes(*dest));
    let values = _mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(bytes));
    store_quant_field_x8(dest, _mm256_mul_ps(values, gain));
}

#[target_feature(enable = "avx2,fma")]
pub(crate) fn apply_structure_aq_avx2(
    corrections: &[f32],
    field: &mut crate::image::ImageB,
    amount: f32,
    center: f32,
    inv_stddev: f32,
) {
    let values = field.as_mut_slice();
    debug_assert_eq!(corrections.len(), values.len());
    let (corrections8, correction_tail) = corrections.as_chunks::<8>();
    let (values8, value_tail) = values.as_chunks_mut::<8>();
    let scale = _mm256_set1_ps(-amount * inv_stddev);
    let center_vector = _mm256_set1_ps(center);
    for (corrections, values) in corrections8.iter().zip(values8) {
        apply_structure_aq_x8(corrections, values, scale, center_vector);
    }
    if !correction_tail.is_empty() {
        let mut corrections = [center; 8];
        corrections[..correction_tail.len()].copy_from_slice(correction_tail);
        let mut values = [0u8; 8];
        values[..value_tail.len()].copy_from_slice(value_tail);
        apply_structure_aq_x8(&corrections, &mut values, scale, center_vector);
        value_tail.copy_from_slice(&values[..value_tail.len()]);
    }
}

#[inline]
#[target_feature(enable = "avx2")]
fn store_i16x8(output: &mut [i16; 8], value: __m256i) {
    let packed = _mm_packs_epi32(
        _mm256_castsi256_si128(value),
        _mm256_extracti128_si256::<1>(value),
    );
    unsafe { _mm_storeu_si128(output.as_mut_ptr().cast(), packed) };
}

#[inline]
#[target_feature(enable = "avx2")]
fn quantize_dc_value_x8(input: __m256, scale: __m256) -> __m256i {
    round_ties_away_i32x8(_mm256_mul_ps(input, scale))
}

#[inline]
#[target_feature(enable = "avx2,fma")]
fn quantize_dc_cfl_value_x8(
    input: __m256,
    y_quant: __m128i,
    scale: __m256,
    negative_cfl: __m256,
) -> __m256i {
    let y = _mm256_cvtepi32_ps(_mm256_cvtepi16_epi32(y_quant));
    let correction = _mm256_mul_ps(y, negative_cfl);
    let value = _mm256_fmadd_ps(input, scale, correction);
    round_ties_away_i32x8(value)
}

#[target_feature(enable = "avx2")]
pub(crate) fn quantize_dc_avx2(input: &[f32], scale: f32, output: &mut [i16]) {
    debug_assert_eq!(input.len(), output.len());
    let (input8, input_tail) = input.as_chunks::<8>();
    let (output8, output_tail) = output.as_chunks_mut::<8>();
    let scale = _mm256_set1_ps(scale);

    for (source, target) in input8.iter().zip(output8) {
        let value = unsafe { _mm256_loadu_ps(source.as_ptr()) };
        store_i16x8(target, quantize_dc_value_x8(value, scale));
    }

    if !input_tail.is_empty() {
        let mut source = [0.0; 8];
        source[..input_tail.len()].copy_from_slice(input_tail);
        let value = unsafe { _mm256_loadu_ps(source.as_ptr()) };
        let mut target = [0i16; 8];
        store_i16x8(&mut target, quantize_dc_value_x8(value, scale));
        output_tail.copy_from_slice(&target[..input_tail.len()]);
    }
}

#[target_feature(enable = "avx2,fma")]
pub(crate) fn quantize_dc_cfl_avx2(
    input: &[f32],
    y_quant: &[i16],
    scale: f32,
    cfl: f32,
    output: &mut [i16],
) {
    debug_assert_eq!(input.len(), y_quant.len());
    debug_assert_eq!(input.len(), output.len());
    let (input8, input_tail) = input.as_chunks::<8>();
    let (y8, y_tail) = y_quant.as_chunks::<8>();
    let (output8, output_tail) = output.as_chunks_mut::<8>();
    let scale = _mm256_set1_ps(scale);
    let negative_cfl = _mm256_set1_ps(-cfl);

    for ((source, y), target) in input8.iter().zip(y8).zip(output8) {
        let value = unsafe { _mm256_loadu_ps(source.as_ptr()) };
        let y = unsafe { _mm_loadu_si128(y.as_ptr().cast()) };
        store_i16x8(
            target,
            quantize_dc_cfl_value_x8(value, y, scale, negative_cfl),
        );
    }

    if !input_tail.is_empty() {
        let mut source = [0.0; 8];
        source[..input_tail.len()].copy_from_slice(input_tail);
        let mut y = [0i16; 8];
        y[..y_tail.len()].copy_from_slice(y_tail);
        let value = unsafe { _mm256_loadu_ps(source.as_ptr()) };
        let y = unsafe { _mm_loadu_si128(y.as_ptr().cast()) };
        let mut target = [0i16; 8];
        store_i16x8(
            &mut target,
            quantize_dc_cfl_value_x8(value, y, scale, negative_cfl),
        );
        output_tail.copy_from_slice(&target[..input_tail.len()]);
    }
}

#[cfg(test)]
mod tests {
    use crate::group::quantize_block_ac_scalar;

    #[test]
    fn quantize_block_ac_avx2_matches_scalar() {
        // Values straddling every rounding and deadzone boundary, including
        // exact halves where ties-to-even and ties-away disagree.
        static EDGES: [f32; 20] = [
            0.0, 0.49, 0.5, 0.51, 0.58, 0.75, 0.99, 1.0, 1.01, 1.49, 1.5, 1.51, 1.99, 2.0, 2.5,
            3.5, -0.5, -0.75, -1.5, -2.5,
        ];
        let mut state = 0x5eed_4321_u64;
        let mut next = || {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1);
            ((state >> 33) as f32 / (1u32 << 31) as f32) - 0.5
        };
        for &(xsize, ysize) in &[
            (1usize, 1usize),
            (1, 2),
            (2, 1),
            (2, 2),
            (2, 4),
            (4, 2),
            (4, 4),
        ] {
            let n = xsize * 8 * ysize * 8;
            for c in 0..3 {
                for &distance in &[0.5f32, 1.0, 2.5, 4.0] {
                    for &quant in &[1i32, 3, 11] {
                        let qm: Vec<f32> = (0..n).map(|i| 0.3 + 0.01 * (i % 17) as f32).collect();
                        // Half crafted edge values (scaled so the product lands
                        // on the boundary), half random.
                        let block: Vec<f32> = (0..n)
                            .map(|i| {
                                if i % 2 == 0 {
                                    let e = EDGES[(i / 2) % EDGES.len()];
                                    e / (qm[i] * quant as f32)
                                } else {
                                    next() * 8.0
                                }
                            })
                            .collect();
                        let mut want = vec![0i32; n];
                        let mut got = vec![0i32; n];
                        quantize_block_ac_scalar(
                            &block, c, &qm, quant, 1.0, 1.0, distance, xsize, ysize, &mut want,
                        );
                        // SAFETY: the test binary is built with +avx2.
                        unsafe {
                            super::quantize_block_ac_avx2(
                                &block, c, &qm, quant, 1.0, 1.0, distance, xsize, ysize, &mut got,
                            );
                        }
                        for i in 0..n {
                            assert_eq!(
                                got[i], want[i],
                                "mismatch at {i} (shape {xsize}x{ysize}, c={c}, d={distance}, \
                                 q={quant}): scalar {} avx2 {}, input {}",
                                want[i], got[i], block[i]
                            );
                        }
                    }
                }
            }
        }
    }
}