jixel 0.5.13

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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/*
 * // Copyright (c) Radzivon Bartoshyk 6/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.
 */

#[cfg(target_arch = "x86")]
use std::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;

#[inline]
#[target_feature(enable = "sse4.1")]
pub(crate) fn hsum(v: __m128) -> f32 {
    let shuf = _mm_movehdup_ps(v); // [1,1,3,3]
    let sums = _mm_add_ps(v, shuf);
    let shuf2 = _mm_movehl_ps(shuf, sums);
    let sums = _mm_add_ss(sums, shuf2);
    _mm_cvtss_f32(sums)
}

/// SSE4.1 implementation of `sse_and_rate_scalar`.
///
/// # Safety
/// Caller must ensure `sse4.1` is available. All slice accesses are
/// bounds-validated against `width*height`.
#[inline]
#[target_feature(enable = "sse4.1")]
pub(super) fn sse_dequantized_level_f32(q: __m128, bias: crate::group::DequantBias) -> __m128 {
    let sign_mask = _mm_set1_ps(-0.0);
    let absq = _mm_andnot_ps(sign_mask, q);
    // q - 0.145/q (q == 0 lanes produce non-finite values, masked out below).
    let big = _mm_sub_ps(q, _mm_div_ps(_mm_set1_ps(bias.numerator), q));
    let sign = _mm_and_ps(sign_mask, q);
    let one = _mm_or_ps(sign, _mm_set1_ps(bias.one));
    let use_big = _mm_cmpge_ps(absq, _mm_set1_ps(1.125));
    let dq = _mm_blendv_ps(one, big, use_big);
    let nz = _mm_cmpgt_ps(absq, _mm_setzero_ps());
    _mm_and_ps(dq, nz)
}

#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "sse4.1")]
pub(crate) fn sse_and_rate_sse<const BIASED: bool>(
    coeff: &[f32],
    inv_matrix: &[f32],
    q_scaled: f32,
    bias: crate::group::DequantBias,
    width: usize,
    height: usize,
    half: usize,
    cx: usize,
    cy: usize,
    _rate_log2_lut: &crate::inflated_cost::RateLog2Lut,
    thr: &[f32; 4],
    scan_pos: &[u32],
) -> (f32, usize, f32, u32) {
    sse_and_rate_sse_impl::<BIASED, false>(
        coeff,
        inv_matrix,
        q_scaled,
        bias,
        width,
        height,
        half,
        cx,
        cy,
        _rate_log2_lut,
        thr,
        scan_pos,
        &mut [],
    )
}

#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "sse4.1")]
pub(crate) fn sse_and_rate_sse_impl<const BIASED: bool, const SAVE_LEVELS: bool>(
    coeff: &[f32],
    inv_matrix: &[f32],
    q_scaled: f32,
    bias: crate::group::DequantBias,
    width: usize,
    height: usize,
    half: usize,
    cx: usize,
    cy: usize,
    _rate_log2_lut: &crate::inflated_cost::RateLog2Lut,
    thr: &[f32; 4],
    scan_pos: &[u32],
    levels: &mut [i32],
) -> (f32, usize, f32, u32) {
    let n = width * height;
    assert!(coeff.len() >= n && inv_matrix.len() >= n);
    assert!(if SAVE_LEVELS {
        levels.len() >= n
    } else {
        scan_pos.len() >= n
    });
    debug_assert!(width.is_multiple_of(4) && half.is_multiple_of(4));

    let qs = _mm_set1_ps(q_scaled);
    let mut sse_acc = _mm_setzero_ps();
    let mut mag_acc = _mm_setzero_ps();
    let mut nonzero_acc = _mm_setzero_si128();
    let mut scan_acc = _mm_setzero_si128();

    let zero = _mm_setzero_ps();
    let sign_mask = _mm_set1_ps(-0.0);

    let lane_ids = _mm_setr_epi32(0, 1, 2, 3);
    let izero = _mm_setzero_si128();
    let all_active_i = _mm_cmpeq_epi32(izero, izero);

    // round-to-nearest-even via SSE4.1

    for (y, (coeffs, inv_matrix)) in coeff
        .chunks_exact(width)
        .zip(inv_matrix.chunks_exact(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, (coeff4, inv4)) in coeffs
            .as_chunks::<4>()
            .0
            .iter()
            .zip(inv_matrix.as_chunks::<4>().0.iter())
            .enumerate()
        {
            let x = x0 * 4;

            let threshold = if x >= half { thr_hi } else { thr_lo };
            let thrv = _mm_set1_ps(threshold);

            let cv = unsafe { _mm_loadu_ps(coeff4.as_ptr()) };
            let mv = unsafe { _mm_loadu_ps(inv4.as_ptr()) };

            // a = inv_matrix * q_scaled * coeff
            let a = _mm_mul_ps(_mm_mul_ps(mv, qs), cv);
            let absa = _mm_andnot_ps(sign_mask, a);

            // keep = |a| >= threshold
            let keep = _mm_cmpge_ps(absa, thrv);

            // Ties away from zero, as the scalar kernel and the coding quantizer.
            let rounded = super::inflated_cost::round_ties_away(a);
            let q = _mm_and_ps(rounded, keep);

            let d = if BIASED {
                _mm_sub_ps(a, sse_dequantized_level_f32(q, bias))
            } else {
                _mm_sub_ps(a, q)
            };
            let d2 = _mm_mul_ps(d, d);

            // Active mask: keep lanes where !(y < cy && x + lane < cx).
            let active_i = if y < cy && x < cx {
                let lane_x = _mm_add_epi32(_mm_set1_epi32(x as i32), lane_ids);
                let cxv = _mm_set1_epi32(cx as i32);

                // llf = cx > lane_x  <=> lane_x < cx
                let llf = _mm_cmpgt_epi32(cxv, lane_x);

                // active = !llf
                _mm_andnot_si128(llf, all_active_i)
            } else {
                all_active_i
            };

            let active = _mm_castsi128_ps(active_i);

            // SSE: zero LLF lanes.
            let d2 = _mm_and_ps(d2, active);
            sse_acc = _mm_add_ps(sse_acc, d2);

            // Rate mask: active && abs(q) > 0.
            let absq = _mm_andnot_ps(sign_mask, q);
            let nz = _mm_cmpgt_ps(absq, zero);
            let rate_mask = _mm_and_ps(nz, active);

            // Comparison masks contain -1 for each nonzero lane.
            nonzero_acc = _mm_sub_epi32(nonzero_acc, _mm_castps_si128(rate_mask));

            if SAVE_LEVELS {
                let truncated = _mm_round_ps::<{ _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC }>(a);
                let frac = _mm_sub_ps(a, truncated);
                let ge_half = _mm_cmpge_ps(_mm_andnot_ps(sign_mask, frac), _mm_set1_ps(0.5));
                let signed_one = _mm_or_ps(_mm_set1_ps(1.0), _mm_and_ps(a, sign_mask));
                let quantized =
                    _mm_cvttps_epi32(_mm_add_ps(truncated, _mm_and_ps(signed_one, ge_half)));
                let quantized =
                    _mm_and_si128(quantized, _mm_and_si128(_mm_castps_si128(keep), active_i));
                unsafe {
                    _mm_storeu_si128(levels.as_mut_ptr().add(y * width + x).cast(), quantized)
                };
            }

            if !SAVE_LEVELS && _mm_movemask_ps(rate_mask) != 0 {
                let ratev = sse_log2p1_f32(absq);
                mag_acc = _mm_add_ps(mag_acc, _mm_and_ps(ratev, rate_mask));
                // Scan position of the nonzeros (masked lanes drop to zero,
                // which is neutral: LLF slots are never nonzero here).
                let sv = unsafe {
                    _mm_loadu_si128(scan_pos.as_ptr().add(y * width + x) as *const __m128i)
                };
                scan_acc = _mm_max_epu32(scan_acc, _mm_and_si128(sv, _mm_castps_si128(rate_mask)));
            }
        }
    }

    let nonzero = _mm_hadd_epi32(nonzero_acc, nonzero_acc);
    let nonzero = _mm_hadd_epi32(nonzero, nonzero);
    let nzeros = _mm_cvtsi128_si32(nonzero) as usize;

    (hsum(sse_acc), nzeros, hsum(mag_acc), hmax_u32(scan_acc))
}

// Original scalar population count, retained as an exact test oracle.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "sse4.1")]
pub(crate) fn sse_and_rate_sse_impl_reference<const BIASED: bool, const SAVE_LEVELS: bool>(
    coeff: &[f32],
    inv_matrix: &[f32],
    q_scaled: f32,
    bias: crate::group::DequantBias,
    width: usize,
    height: usize,
    half: usize,
    cx: usize,
    cy: usize,
    _rate_log2_lut: &crate::inflated_cost::RateLog2Lut,
    thr: &[f32; 4],
    scan_pos: &[u32],
    levels: &mut [i32],
) -> (f32, usize, f32, u32) {
    let n = width * height;
    assert!(coeff.len() >= n && inv_matrix.len() >= n);
    assert!(if SAVE_LEVELS {
        levels.len() >= n
    } else {
        scan_pos.len() >= n
    });
    debug_assert!(width.is_multiple_of(4) && half.is_multiple_of(4));

    let qs = _mm_set1_ps(q_scaled);
    let mut sse_acc = _mm_setzero_ps();
    let mut mag_acc = _mm_setzero_ps();
    let mut nzeros = 0usize;
    let mut scan_acc = _mm_setzero_si128();

    let zero = _mm_setzero_ps();
    let sign_mask = _mm_set1_ps(-0.0);

    let lane_ids = _mm_setr_epi32(0, 1, 2, 3);
    let izero = _mm_setzero_si128();
    let all_active_i = _mm_cmpeq_epi32(izero, izero);

    // round-to-nearest-even via SSE4.1

    for (y, (coeffs, inv_matrix)) in coeff
        .chunks_exact(width)
        .zip(inv_matrix.chunks_exact(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, (coeff4, inv4)) in coeffs
            .as_chunks::<4>()
            .0
            .iter()
            .zip(inv_matrix.as_chunks::<4>().0.iter())
            .enumerate()
        {
            let x = x0 * 4;

            let threshold = if x >= half { thr_hi } else { thr_lo };
            let thrv = _mm_set1_ps(threshold);

            let cv = unsafe { _mm_loadu_ps(coeff4.as_ptr()) };
            let mv = unsafe { _mm_loadu_ps(inv4.as_ptr()) };

            // a = inv_matrix * q_scaled * coeff
            let a = _mm_mul_ps(_mm_mul_ps(mv, qs), cv);
            let absa = _mm_andnot_ps(sign_mask, a);

            // keep = |a| >= threshold
            let keep = _mm_cmpge_ps(absa, thrv);

            // Ties away from zero, as the scalar kernel and the coding quantizer.
            let rounded = super::inflated_cost::round_ties_away(a);
            let q = _mm_and_ps(rounded, keep);

            let d = if BIASED {
                _mm_sub_ps(a, sse_dequantized_level_f32(q, bias))
            } else {
                _mm_sub_ps(a, q)
            };
            let d2 = _mm_mul_ps(d, d);

            // Active mask: keep lanes where !(y < cy && x + lane < cx).
            let active_i = if y < cy && x < cx {
                let lane_x = _mm_add_epi32(_mm_set1_epi32(x as i32), lane_ids);
                let cxv = _mm_set1_epi32(cx as i32);

                // llf = cx > lane_x  <=> lane_x < cx
                let llf = _mm_cmpgt_epi32(cxv, lane_x);

                // active = !llf
                _mm_andnot_si128(llf, all_active_i)
            } else {
                all_active_i
            };

            let active = _mm_castsi128_ps(active_i);

            // SSE: zero LLF lanes.
            let d2 = _mm_and_ps(d2, active);
            sse_acc = _mm_add_ps(sse_acc, d2);

            // Rate mask: active && abs(q) > 0.
            let absq = _mm_andnot_ps(sign_mask, q);
            let nz = _mm_cmpgt_ps(absq, zero);
            let rate_mask = _mm_and_ps(nz, active);

            let rate_bits = _mm_movemask_ps(rate_mask);
            nzeros += rate_bits.count_ones() as usize;

            if SAVE_LEVELS {
                let truncated = _mm_round_ps::<{ _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC }>(a);
                let frac = _mm_sub_ps(a, truncated);
                let ge_half = _mm_cmpge_ps(_mm_andnot_ps(sign_mask, frac), _mm_set1_ps(0.5));
                let signed_one = _mm_or_ps(_mm_set1_ps(1.0), _mm_and_ps(a, sign_mask));
                let quantized =
                    _mm_cvttps_epi32(_mm_add_ps(truncated, _mm_and_ps(signed_one, ge_half)));
                let quantized =
                    _mm_and_si128(quantized, _mm_and_si128(_mm_castps_si128(keep), active_i));
                unsafe {
                    _mm_storeu_si128(levels.as_mut_ptr().add(y * width + x).cast(), quantized)
                };
            }

            if !SAVE_LEVELS && rate_bits != 0 {
                let ratev = sse_log2p1_f32(absq);
                mag_acc = _mm_add_ps(mag_acc, _mm_and_ps(ratev, rate_mask));
                // Scan position of the nonzeros (masked lanes drop to zero,
                // which is neutral: LLF slots are never nonzero here).
                let sv = unsafe {
                    _mm_loadu_si128(scan_pos.as_ptr().add(y * width + x) as *const __m128i)
                };
                scan_acc = _mm_max_epu32(scan_acc, _mm_and_si128(sv, _mm_castps_si128(rate_mask)));
            }
        }
    }

    (hsum(sse_acc), nzeros, hsum(mag_acc), hmax_u32(scan_acc))
}

#[inline]
pub(crate) const fn _mm_shuffle(z: u32, y: u32, x: u32, w: u32) -> i32 {
    ((z << 6) | (y << 4) | (x << 2) | w) as i32
}

#[inline]
#[target_feature(enable = "sse4.1")]
fn hmax_u32(v: __m128i) -> u32 {
    // swap the two 64-bit halves: [a,b,c,d] -> [c,d,a,b]
    let t1 = _mm_shuffle_epi32::<{ _mm_shuffle(1, 0, 3, 2) }>(v);
    let m1 = _mm_max_epu32(v, t1);

    // swap adjacent 32-bit lanes: [x,y,x,y] -> [y,x,y,x]
    let t2 = _mm_shuffle_epi32::<{ _mm_shuffle(2, 3, 0, 1) }>(m1);
    let m2 = _mm_max_epu32(m1, t2);

    _mm_cvtsi128_si32(m2) as u32
}

#[inline]
#[target_feature(enable = "sse4.1")]
pub(super) fn sse_log2p1_f32(x: __m128) -> __m128 {
    // y = 1 + x
    let y = _mm_add_ps(x, _mm_set1_ps(1.0));

    // Decompose y = m * 2^e, m in [1, 2).
    let bits = _mm_castps_si128(y);

    let exp_u = _mm_srli_epi32(bits, 23);
    let exp_i = _mm_sub_epi32(exp_u, _mm_set1_epi32(127));
    let e = _mm_cvtepi32_ps(exp_i);

    let mant_bits = _mm_or_si128(
        _mm_and_si128(bits, _mm_set1_epi32(0x007f_ffff)),
        _mm_set1_epi32(0x3f80_0000),
    );
    let m = _mm_castsi128_ps(mant_bits);

    let t = _mm_sub_ps(m, _mm_set1_ps(1.0));

    // Generated by tools/log2p1.sollya.
    let c0 = _mm_set1_ps(1.4426934719085693359375);
    let c1 = _mm_set1_ps(-0.721179187297821044921875);
    let c2 = _mm_set1_ps(0.477900087833404541015625);
    let c3 = _mm_set1_ps(-0.340080082416534423828125);
    let c4 = _mm_set1_ps(0.21719777584075927734375);
    let c5 = _mm_set1_ps(-9.749893844127655029296875e-2);
    let c6 = _mm_set1_ps(2.096841670572757720947265625e-2);

    let mut p = c6;
    p = _mm_add_ps(c5, _mm_mul_ps(t, p));
    p = _mm_add_ps(c4, _mm_mul_ps(t, p));
    p = _mm_add_ps(c3, _mm_mul_ps(t, p));
    p = _mm_add_ps(c2, _mm_mul_ps(t, p));
    p = _mm_add_ps(c1, _mm_mul_ps(t, p));
    p = _mm_add_ps(c0, _mm_mul_ps(t, p));

    let log2_m = _mm_mul_ps(t, p);

    _mm_add_ps(e, log2_m)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sse_and_rate_sse_vs_reference() {
        if !std::is_x86_feature_detected!("sse4.1") {
            return;
        }
        crate::inflated_cost::assert_sse_and_rate_matches_reference(
            sse_and_rate_sse::<false>,
            false,
        );
        crate::inflated_cost::assert_sse_and_rate_matches_reference(sse_and_rate_sse::<true>, true);
    }

    #[test]
    fn test_log2p1() {
        if !std::is_x86_feature_detected!("sse4.1") {
            return;
        }
        unsafe {
            for i in 0..5000 {
                let q1 = ((i as f32 / 5000.) + 1.).log2();
                let q2 = f32::from_bits(_mm_extract_ps::<0>(sse_log2p1_f32(_mm_set1_ps(
                    i as f32 / 5000.,
                ))) as u32);
                assert!((q1 - q2).abs() < 1e-5, "q1 {} q2 {}", q1, q2);
            }
        }
    }
}

#[cfg(test)]
mod lane_count_tests {
    use super::*;

    #[test]
    fn lane_counts_preserve_original_rate_distortion_and_coding_levels() {
        if !std::is_x86_feature_detected!("sse4.1") {
            return;
        }
        for (original, optimized) in [
            (
                sse_and_rate_sse_impl_reference::<false, false>
                    as crate::inflated_cost::SseAndQuantizeFn,
                sse_and_rate_sse_impl::<false, false> as crate::inflated_cost::SseAndQuantizeFn,
            ),
            (
                sse_and_rate_sse_impl_reference::<false, true>
                    as crate::inflated_cost::SseAndQuantizeFn,
                sse_and_rate_sse_impl::<false, true> as crate::inflated_cost::SseAndQuantizeFn,
            ),
            (
                sse_and_rate_sse_impl_reference::<true, false>
                    as crate::inflated_cost::SseAndQuantizeFn,
                sse_and_rate_sse_impl::<true, false> as crate::inflated_cost::SseAndQuantizeFn,
            ),
            (
                sse_and_rate_sse_impl_reference::<true, true>
                    as crate::inflated_cost::SseAndQuantizeFn,
                sse_and_rate_sse_impl::<true, true> as crate::inflated_cost::SseAndQuantizeFn,
            ),
        ] {
            crate::inflated_cost::assert_coefficient_kernel_preserves_original(original, optimized);
        }
    }
}