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
/*
 * // Copyright (c) Radzivon Bartoshyk 5/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.
 */

//! Distance-dependent quantization and decoder filter parameters.

use crate::dct::fmla;
use crate::image::Image3F;

#[derive(Clone, Copy)]
pub(crate) struct DistanceParams {
    pub(crate) distance: f32,
    pub(crate) global_scale: i32,
    pub(crate) quant_dc: i32,
    pub(crate) scale: f32,
    pub(crate) scale_dc: f32,
    pub(crate) x_qm_scale: u32,
    pub(crate) epf_iters: u32,
    pub(crate) epf_pass0_scale: Option<f32>,
    pub(crate) epf_quant_mul: Option<f32>,
    pub(crate) gab_enabled: bool,
    /// Multipliers of the default DC steps of X, Y and B.
    pub(crate) dc_step: [f32; 3],
}

pub(crate) const X_QM_REFINE_MAX_DISTANCE: f32 = 0.299;
const DC_REFINE_PEAK: f32 = 1.35;
const DC_REFINE_HOLD: f32 = 3.0;
const DC_REFINE_RELEASE: f32 = 5.0;

#[inline]
fn dc_refinement(distance: f32) -> f32 {
    if distance <= DC_REFINE_HOLD {
        DC_REFINE_PEAK
    } else if distance >= DC_REFINE_RELEASE {
        1.0
    } else {
        const RECIP_REFINE: f32 = 1.0 / (DC_REFINE_RELEASE - DC_REFINE_HOLD);
        let t = (distance - DC_REFINE_HOLD) * RECIP_REFINE;
        fmla(1.0 - DC_REFINE_PEAK, t, DC_REFINE_PEAK)
    }
}

const DCEPF_VLQ_D0: f32 = 8.0;
const DCEPF_VLQ_D1: f32 = 15.0;
const VLQ_DC_MUL: f32 = 0.7;

#[inline]
fn dcepf_vlq_t(distance: f32) -> f32 {
    ((distance - DCEPF_VLQ_D0) / (DCEPF_VLQ_D1 - DCEPF_VLQ_D0)).clamp(0.0, 1.0)
}

fn quant_dc(distance: f32) -> f32 {
    let refine = dc_refinement(distance);
    let vlq = fmla(dcepf_vlq_t(distance), VLQ_DC_MUL - 1.0, 1.0);
    let k_dc_quant_pow = 0.57f32;
    let k_dc_quant = 1.12f32;
    let k_dc_mul = 2.9f32;
    let effective = k_dc_mul * (distance / k_dc_mul).powf(k_dc_quant_pow);
    let effective = f32::clamp(effective, 0.5 * distance, distance);
    (k_dc_quant / effective).min(50.0) * refine * vlq
}

pub(crate) fn compute_distance_params(distance: f32) -> DistanceParams {
    const K_GLOBAL_SCALE_DENOM: i32 = 1 << 16;
    const K_AC_QUANT: f32 = 0.8;
    // Keep the integer quant field away from the very coarse 2/3/4 range. The
    // corresponding reduction in global scale preserves the effective AC
    // quantizer while giving AQ enough integer resolution to vary smoothly.
    const K_QUANT_FIELD_TARGET: f32 = 10.0;

    let qdc_fine = quant_dc(distance);
    let coarsen = luma_dc_coarsening(distance);
    let qdc = qdc_fine / coarsen;
    let scale = K_GLOBAL_SCALE_DENOM as f32 * K_AC_QUANT / (distance * K_QUANT_FIELD_TARGET);
    // AC and DC are signaled independently. Capping the AC scale by qdc made
    // it freeze once quant_dc() reached its high-distance cap, producing a
    // rate/quality plateau followed by a cliff when the cap finally released.
    let global_scale = i32::clamp(scale.round() as i32, 1, 1 << 15);
    let scale_f = global_scale as f32 / K_GLOBAL_SCALE_DENOM as f32;
    let qd = ((qdc / scale_f) + 0.5) as i32;
    let qd = i32::clamp(qd, 1, 1 << 16);
    let scale_dc = qd as f32 * scale_f;

    let mut x_qm_scale: u32 = 2;
    if distance >= 1.25 {
        x_qm_scale += 1;
    }
    if distance > 9.0 {
        x_qm_scale += 1;
    }
    if distance < X_QM_REFINE_MAX_DISTANCE {
        x_qm_scale += 1;
    }
    static EPF_THRESHOLDS: [f32; 2] = [0.7, 1.5];
    let mut epf_iters: u32 = 0;
    for t in EPF_THRESHOLDS {
        if distance >= t {
            epf_iters += 1;
        }
    }
    let epf_pass0_scale = epf_pass0_scale(distance);
    if epf_pass0_scale.is_some() || dcepf_vlq_t(distance) >= 0.5 {
        epf_iters = 3;
    }
    let gab_enabled = false; // measured net-negative for rate-matched SSIMU2

    DistanceParams {
        distance,
        global_scale,
        quant_dc: qd,
        scale: scale_f,
        scale_dc,
        x_qm_scale,
        epf_iters,
        epf_pass0_scale,
        epf_quant_mul: None,
        gab_enabled,
        dc_step: {
            // Chroma DC steps are relative to the luma step; keep them absolute.
            let [x, y, b] = chroma_dc_steps(qdc_fine);
            crate::color_correlation::signaled_dc_steps([x / coarsen, y, b / coarsen])
        },
    }
}

/// Luma DC step multiplier: held at its peak on the inner band and tapered
/// linearly to 1 across the outer edges.
const LUMA_DC_COARSEN: f32 = 1.15;
const LUMA_DC_COARSEN_BAND: [f32; 4] = [1.25, 1.75, 4.25, 5.0];

#[inline]
fn luma_dc_coarsening(distance: f32) -> f32 {
    let [a, b, c, e] = LUMA_DC_COARSEN_BAND;
    let t = if distance <= a || distance >= e {
        0.0
    } else if distance < b {
        (distance - a) / (b - a)
    } else if distance <= c {
        1.0
    } else {
        (e - distance) / (e - c)
    };
    fmla(t, LUMA_DC_COARSEN - 1.0, 1.0)
}

/// Multiplier of the default X DC step. The spec's X DC quantizer is far
/// finer than the X AC band it sits under; twice the step buys back 1-2% of
/// the file at better SSIMULACRA2, butteraugli and cvvdp alike.
const X_DC_STEP: f32 = 2.0;

/// Distance from which the chroma DC steps grow slower than the luma DC step.
const CHROMA_DC_GROWTH_DISTANCE: f32 = 3.5;
/// Exponents of the X and B DC step growth relative to the luma DC step's.
static CHROMA_DC_GROWTH: [f32; 2] = [0.75, 0.5];

/// DC step multipliers for X, Y and B at the luma DC quantizer `qdc`.
///
/// Past `CHROMA_DC_GROWTH_DISTANCE` the chroma steps follow only a power of
/// the luma step's growth: a flat, nearly neutral region otherwise sits
/// between two chroma DC levels, and every block rounds the same way into a
/// visible hue shift.
fn chroma_dc_steps(qdc: f32) -> [f32; 3] {
    let growth = (quant_dc(CHROMA_DC_GROWTH_DISTANCE) / qdc).max(1.0);
    [
        X_DC_STEP * growth.powf(CHROMA_DC_GROWTH[0] - 1.0),
        1.0,
        growth.powf(CHROMA_DC_GROWTH[1] - 1.0),
    ]
}

const EPF_PASS0_START_D: f32 = 2.5;
const EPF_PASS0_SCALE: f32 = 3.6;
const EPF_PASS0_SPEC_SCALE: f32 = 0.9;

fn epf_pass0_scale(distance: f32) -> Option<f32> {
    if distance < EPF_PASS0_START_D {
        return None;
    }
    let t = dcepf_vlq_t(distance);
    if t >= 0.5 {
        return None;
    }
    Some(fmla(
        2.0 * t,
        EPF_PASS0_SPEC_SCALE - EPF_PASS0_SCALE,
        EPF_PASS0_SCALE,
    ))
}

const SCREEN_CONTENT_EPF_MAX_DISTANCE: f32 = 5.0;

pub(crate) fn epf_sharpness_id(distance: f32, screen_content: bool) -> i32 {
    let t = dcepf_vlq_t(distance);
    if t >= 0.75 {
        return 1;
    } else if t >= 0.5 {
        return 2;
    } else if t >= 0.25 {
        return 3;
    }
    // Hard edges beside flat fills ring visibly; up to d=5 the strongest
    // filter wins both SSIMULACRA2 and butteraugli there at identical bytes.
    if distance < 1.4 || (screen_content && distance < SCREEN_CONTENT_EPF_MAX_DISTANCE) {
        7
    } else if distance < 1.75 {
        6
    } else if distance < 3.5 {
        5
    } else {
        4
    }
}

/// Pre-invert Gaborish so the decoder's forward pass reproduces `xyb`.
pub(crate) fn gaborize(xyb: &mut Image3F, distp: &DistanceParams) {
    if distp.gab_enabled {
        crate::gaborish::gaborish_inverse(xyb, 0.990_851_1);
    }
}

/// Largest stored DC level kept clear of the `i16` limit, with room for the
/// chroma-from-luma terms and the finer DC-step candidates.
const DC_LEVEL_LIMIT: f32 = 16_000.0;

/// Non-XYB planes hold the image's own samples, which float input may take far
/// past [0, 1]. Coarsen a plane's DC step only as far as its stored levels
/// need to stay representable.
pub(crate) fn dc_steps_in_range(base: [f32; 3], scale_dc: f32, coded: &Image3F) -> [f32; 3] {
    let peak = (0..3)
        .flat_map(|c| coded.plane_data(c).iter())
        .fold(0.0f32, |m, &v| m.max(v.abs()));
    let steps = std::array::from_fn(|c| {
        let level = peak * crate::quant_weights::INV_DC_QUANT[c] * scale_dc / base[c];
        if level > DC_LEVEL_LIMIT {
            base[c] * level / DC_LEVEL_LIMIT
        } else {
            base[c]
        }
    });
    crate::color_correlation::signaled_dc_steps(steps)
}

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

    #[test]
    fn dc_steps_match_the_signaled_dequantizer_before_quantization() {
        assert_eq!(
            crate::color_correlation::signaled_dc_steps([1.0; 3]),
            [1.0; 3]
        );
        let check = |steps: [f32; 3]| {
            let wire = crate::color_correlation::dc_step_wire(steps).unwrap();
            for c in 0..3 {
                let decoded = crate::util::f16_bits_to_f32(wire[c])
                    / (crate::quant_weights::DC_QUANT[c] * 128.0);
                assert_eq!(steps[c], decoded, "channel {c}");
            }
            assert_eq!(crate::color_correlation::signaled_dc_steps(steps), steps);
        };
        // The luma-coarsening band and the high-distance chroma growth both
        // produce values that cannot be represented directly in the header.
        for distance in [1.4, 2.0, 4.5, 6.0, 11.0, 25.0] {
            check(compute_distance_params(distance).dc_step);
        }
        let mut coded = Image3F::new(8, 8);
        assert_eq!(dc_steps_in_range([1.0; 3], 1.0, &coded), [1.0; 3]);
        for c in 0..3 {
            coded.plane_mut(c).as_mut_slice().fill(1.234_567);
        }
        check(dc_steps_in_range([1.0; 3], 100.0, &coded));
    }

    #[test]
    fn chroma_dc_steps_grow_slower_than_luma_past_the_knee() {
        for d in [0.1, 1.0, 2.0, 3.0, CHROMA_DC_GROWTH_DISTANCE] {
            let k = luma_dc_coarsening(d);
            assert_eq!(
                compute_distance_params(d).dc_step,
                crate::color_correlation::signaled_dc_steps([X_DC_STEP / k, 1.0, 1.0 / k]),
                "d={d}"
            );
        }
        // Absolute steps per channel: luma coarsens fastest, B slowest, and
        // no chroma step ever gets finer as the distance grows.
        let absolute = |d: f32| {
            let p = compute_distance_params(d);
            std::array::from_fn::<f32, 3, _>(|c| p.dc_step[c] / p.scale_dc)
        };
        let mut prev = absolute(CHROMA_DC_GROWTH_DISTANCE);
        for d in [4.0, 5.0, 6.0, 8.0, 11.0, 15.0, 25.0] {
            let p = compute_distance_params(d);
            assert!(p.dc_step[0] < X_DC_STEP && p.dc_step[2] < 1.0, "d={d}");
            assert!(p.dc_step[0] / X_DC_STEP > p.dc_step[2], "d={d}");
            let cur = absolute(d);
            for c in [0, 2] {
                assert!(cur[c] >= prev[c] * 0.999, "chroma {c} step shrank at d={d}");
            }
            prev = cur;
        }
    }

    #[test]
    fn dc_refinement_holds_then_ramps_out_monotonically() {
        // Full refinement through the hold point, none past the release point.
        for d in [0.1, 0.5, 1.0, 2.0, DC_REFINE_HOLD] {
            assert_eq!(dc_refinement(d), DC_REFINE_PEAK);
        }
        for d in [DC_REFINE_RELEASE, 5.5, 8.0, 25.0] {
            assert_eq!(dc_refinement(d), 1.0);
        }
        // Strictly decreasing across the ramp, and continuous at both ends.
        let mid = 0.5 * (DC_REFINE_HOLD + DC_REFINE_RELEASE);
        assert!((dc_refinement(mid) - 0.5 * (DC_REFINE_PEAK + 1.0)).abs() < 1e-6);
        let mut prev = f32::INFINITY;
        for i in 0..=40 {
            let d = DC_REFINE_HOLD + (DC_REFINE_RELEASE - DC_REFINE_HOLD) * (i as f32 / 40.0);
            let v = dc_refinement(d);
            assert!(v <= prev, "refinement rose at d={d}");
            assert!((1.0..=DC_REFINE_PEAK).contains(&v));
            prev = v;
        }
    }

    #[test]
    fn luma_dc_coarsening_is_a_continuous_band() {
        let [a, b, c, e] = LUMA_DC_COARSEN_BAND;
        for d in [0.1, 1.0, a, e, 6.0, 12.0] {
            assert_eq!(luma_dc_coarsening(d), 1.0, "d={d}");
        }
        for d in [b, 2.0, 3.0, c] {
            assert_eq!(luma_dc_coarsening(d), LUMA_DC_COARSEN, "d={d}");
        }
        let mid = luma_dc_coarsening(0.5 * (a + b));
        assert!((mid - 0.5 * (1.0 + LUMA_DC_COARSEN)).abs() < 1e-6);
    }

    #[test]
    fn dc_refinement_makes_dc_finer_where_it_applies() {
        // Refining means a *larger* DC scale (finer quantization step), and it
        // must not disturb the AC quantizer, which is signaled independently.
        for d in [0.5, 1.0, 3.0] {
            let p = compute_distance_params(d);
            assert!(p.scale_dc > 0.0);
            let qdc = quant_dc(d) / luma_dc_coarsening(d);
            assert!((p.scale_dc - qdc).abs() <= 0.5 * p.scale + f32::EPSILON);
        }
        assert!(quant_dc(1.0) > quant_dc(1.0) / DC_REFINE_PEAK);
    }

    #[test]
    fn epf_third_pass_schedule() {
        // The third EPF pass at spec strength erases texture in the normal
        // bands, so it only enters weakened (custom pass-0 sigma scale) from
        // EPF_PASS0_START_D, eases toward spec strength across the first half
        // of the VLQ ramp, and hands over to the fitted spec-strength band
        // (default sigma header) at half-ramp. Guards every edge.
        for d in [0.0, 0.1, 0.5, 0.69] {
            assert_eq!(compute_distance_params(d).epf_iters, 0, "d={d}");
        }
        for d in [0.7, 1.0, 1.49] {
            assert_eq!(compute_distance_params(d).epf_iters, 1, "d={d}");
        }
        for d in [1.5, 2.0, 2.49] {
            let p = compute_distance_params(d);
            assert_eq!(p.epf_iters, 2, "d={d}");
            assert_eq!(p.epf_pass0_scale, None, "d={d}");
        }
        for d in [2.5, 4.0, 6.0, 8.0] {
            let p = compute_distance_params(d);
            assert_eq!(p.epf_iters, 3, "d={d}");
            assert_eq!(p.epf_pass0_scale, Some(EPF_PASS0_SCALE), "d={d}");
        }
        let mid = compute_distance_params(9.75).epf_pass0_scale.unwrap();
        assert!((mid - 0.5 * (EPF_PASS0_SCALE + EPF_PASS0_SPEC_SCALE)).abs() < 1e-5);
        for d in [11.5, 15.0, 25.0] {
            let p = compute_distance_params(d);
            assert_eq!(p.epf_iters, 3, "d={d}");
            assert_eq!(p.epf_pass0_scale, None, "d={d}");
        }
    }

    #[test]
    fn epf_sharpness_strengthens_in_the_coarse_band() {
        assert_eq!(epf_sharpness_id(1.39, false), 7);
        assert_eq!(epf_sharpness_id(1.4, false), 6);
        assert_eq!(epf_sharpness_id(1.74, false), 6);
        assert_eq!(epf_sharpness_id(1.75, false), 5);
        assert_eq!(epf_sharpness_id(2.75, false), 5);
        assert_eq!(epf_sharpness_id(3.49, false), 5);
        assert_eq!(epf_sharpness_id(3.5, false), 4);
        // VLQ ramp steps (quarter-points of DCEPF_VLQ_D0..D1 = 8..15).
        assert_eq!(epf_sharpness_id(9.74, false), 4);
        assert_eq!(epf_sharpness_id(9.75, false), 3);
        assert_eq!(epf_sharpness_id(11.5, false), 2);
        assert_eq!(epf_sharpness_id(13.25, false), 1);
        assert_eq!(epf_sharpness_id(25.0, false), 1);
    }

    #[test]
    fn screen_content_keeps_the_strongest_epf_below_d5() {
        use super::epf_sharpness_id;
        assert_eq!(epf_sharpness_id(1.0, true), 7);
        assert_eq!(epf_sharpness_id(2.5, true), 7);
        assert_eq!(epf_sharpness_id(4.99, true), 7);
        assert_eq!(epf_sharpness_id(5.0, true), epf_sharpness_id(5.0, false));
        assert_eq!(epf_sharpness_id(12.0, true), epf_sharpness_id(12.0, false));
    }

    #[test]
    fn quantization_keeps_coarsening_at_low_quality() {
        let d4 = compute_distance_params(4.0);
        let d45 = compute_distance_params(4.5);
        let d5 = compute_distance_params(5.0);
        assert!(d4.global_scale > d45.global_scale);
        assert!(d45.global_scale > d5.global_scale);
        for distances in [3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 12.0, 16.0].array_windows::<2>() {
            let fine = compute_distance_params(distances[0]);
            let coarse = compute_distance_params(distances[1]);
            assert!(fine.scale_dc > coarse.scale_dc, "distances={distances:?}");
        }
    }

    #[test]
    fn dc_quantization_stays_independent_of_ac_scale() {
        for distance in [0.5, 1.0, 3.5, 4.0, 4.5, 6.0] {
            let params = compute_distance_params(distance);
            let rounding_error = 0.5 * params.scale;
            let qdc = quant_dc(distance) / luma_dc_coarsening(distance);
            assert!((params.scale_dc - qdc).abs() <= rounding_error + f32::EPSILON);
        }
    }
}