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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
 * // Copyright (c) Radzivon Bartoshyk 9/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.
 */

//! Predictor and weighted-predictor preset cost estimation.

use super::super::entropy::{EntropyOfHistFn, selected_entropy_of_hist_fn};
#[cfg(test)]
use super::predictor_neighbors;
use super::row_kernels::{self, Rows, Sample};
use super::{
    PREDICTOR_GRADIENT, PREDICTOR_LEFT, PREDICTOR_SELECT, PREDICTOR_TOP, PREDICTOR_ZERO,
    SLOW_PREDICTORS, fixed_predictor, visit_predictor_row,
};
use crate::coder_scratch::CoderScratch;
use crate::encode_image::AlphaPlane;
use crate::entropy::pack_signed;
use crate::image::Image3Si;
use crate::thread_pool::ThreadPool;
use crate::weighted_predictor::{WpNeighbors, WpParams, WpState};

/// Side of the corner crops `wp_sample_cost` scores.
const WP_SAMPLE_CROP: usize = 128;

/// The coordinates along one axis that `wp_sample_cost` reads, in order: a
/// packed plane of them holds the same crops.
fn wp_sample_coords(len: usize) -> impl Iterator<Item = usize> {
    let crop = len.min(WP_SAMPLE_CROP);
    let tail = if len > crop { len - crop..len } else { 0..0 };
    (0..crop).chain(tail)
}

pub(super) fn wp_sample_cost<'a, T: Copy + 'a>(
    get_row: impl Fn(usize) -> &'a [T],
    width: usize,
    height: usize,
    params: WpParams,
) -> (u64, usize)
where
    i64: From<T>,
{
    let cw = width.min(WP_SAMPLE_CROP);
    let ch = height.min(WP_SAMPLE_CROP);
    if cw == 0 || ch == 0 {
        return (0, 0);
    }
    let xs = if width > cw { [0, width - cw] } else { [0, 0] };
    let ys = if height > ch {
        [0, height - ch]
    } else {
        [0, 0]
    };
    let nx = 1 + usize::from(xs[1] != xs[0]);
    let ny = 1 + usize::from(ys[1] != ys[0]);
    let mut cost = 0u64;
    let mut wp = WpState::with_params(cw, params);
    for &y0 in &ys[..ny] {
        for &x0 in &xs[..nx] {
            wp.reset(cw, params);
            let mut north = &get_row(y0)[x0..x0 + cw];
            let mut north_north = north;
            for y in 0..ch {
                let current = &get_row(y0 + y)[x0..x0 + cw];
                let row = wp.row_offsets(y);
                visit_predictor_row(current, north, north_north, y == 0, |x, value, n| {
                    let prediction = wp.predict_and_update(
                        value,
                        x,
                        row,
                        WpNeighbors {
                            north: n.top,
                            west: n.left,
                            north_east: n.top_right,
                            north_west: n.top_left,
                            north_north: n.top_top,
                        },
                    );
                    cost += wp_residual_cost((value - prediction) as i32);
                });
                north_north = north;
                north = current;
            }
        }
    }
    (cost, nx * ny * cw * ch)
}

#[inline]
fn wp_residual_cost(residual: i32) -> u64 {
    let packed = pack_signed(residual);
    let (_, extra_bits, _) = crate::entropy::uint_encode(packed);
    let magnitude_bits = 32 - packed.saturating_add(1).leading_zeros();
    u64::from(extra_bits + magnitude_bits)
}

pub(super) fn wp_constant_sample_cost(value: i32, width: usize, height: usize) -> (u64, usize) {
    if width == 0 || height == 0 {
        return (0, 0);
    }
    debug_assert!(value >= 0);
    let crop_count =
        (1 + usize::from(width > WP_SAMPLE_CROP)) * (1 + usize::from(height > WP_SAMPLE_CROP));
    let samples = wp_sample_coords(width).count() * wp_sample_coords(height).count();
    // Each crop starts from zero. For a nonnegative constant, the first
    // sample leaves a nonpositive WP error. Every later prediction clamps to
    // its equal neighbors, with zero residual and zero WP error.
    let cost = samples as u64 + crop_count as u64 * (wp_residual_cost(value) - 1);
    (cost, samples)
}

/// `ycocg` holds YCoCg planes (or one gray plane) and the color channels are
/// scored under `rct`: only the sampled corners are transformed.
pub(in crate::lossless) fn choose_wp_params(
    ycocg: &Image3Si,
    rct: u32,
    alpha: Option<&AlphaPlane>,
    alpha_constant: Option<i32>,
    num_color: usize,
    header_count: usize,
    pool: &ThreadPool,
    scratch: &mut CoderScratch,
) -> WpParams {
    let width = ycocg.xsize();
    let height = ycocg.ysize();
    let nb_chans = num_color + usize::from(alpha.is_some());
    let total_values = width.saturating_mul(height).saturating_mul(nb_chans);
    let alpha_constant_cost = alpha_constant
        .filter(|&value| value >= 0)
        .map(|value| wp_constant_sample_cost(value, width, height));
    let packed_width = wp_sample_coords(width).count();
    let packed_height = wp_sample_coords(height).count();
    let corners = (num_color == 3 && rct != 6).then(|| {
        let mut planes = std::array::from_fn(|_| vec![0; packed_width * packed_height]);
        let [a, b, c] = &mut planes;
        let [p0, p1, p2] = [0, 1, 2].map(|c| ycocg.plane_data(c));
        let transform = crate::lossless::selected_rct_row_fn();
        let crop = width.min(WP_SAMPLE_CROP);
        let tail = if width > crop {
            width - crop..width
        } else {
            0..0
        };
        for (row, y) in wp_sample_coords(height).enumerate() {
            let mut offset = row * packed_width;
            for xs in [0..crop, tail.clone()] {
                let len = xs.len();
                let start = y * width + xs.start;
                transform(
                    [p0, p1, p2].map(|p| &p[start..start + len]),
                    rct,
                    [
                        &mut a[offset..offset + len],
                        &mut b[offset..offset + len],
                        &mut c[offset..offset + len],
                    ],
                );
                offset += len;
            }
        }
        planes
    });
    let scores = pool.steal_map(scratch, WpParams::PRESETS.len(), |preset, _scratch| {
        let params = WpParams::PRESETS[preset];
        let mut sample_cost = 0u64;
        let mut samples = 0usize;
        for channel in 0..num_color {
            let (cost, count) = match &corners {
                Some(planes) => {
                    let plane = &planes[channel];
                    wp_sample_cost(
                        |y| &plane[y * packed_width..][..packed_width],
                        packed_width,
                        packed_height,
                        params,
                    )
                }
                None => {
                    let plane = ycocg.plane_data(channel);
                    wp_sample_cost(|y| &plane[y * width..][..width], width, height, params)
                }
            };
            sample_cost += cost;
            samples += count;
        }
        if let Some(alpha) = alpha {
            let (cost, count) = alpha_constant_cost.unwrap_or_else(|| match alpha {
                AlphaPlane::U8(data) => {
                    wp_sample_cost(|y| &data[y * width..][..width], width, height, params)
                }
                AlphaPlane::U16 { data, .. } => {
                    wp_sample_cost(|y| &data[y * width..][..width], width, height, params)
                }
                AlphaPlane::F32(data) => {
                    wp_sample_cost(|y| &data[y * width..][..width], width, height, params)
                }
            });
            sample_cost += cost;
            samples += count;
        }
        let scaled = sample_cost as f64 * total_values as f64 / samples.max(1) as f64;
        // A non-default header costs 51 additional bits per modular group.
        scaled
            + if preset == 0 {
                0.0
            } else {
                (51 * header_count) as f64
            }
    });
    let best = scores
        .iter()
        .enumerate()
        .min_by(|a, b| a.1.total_cmp(b.1))
        .map_or(0, |(index, _)| index);
    WpParams::PRESETS[best]
}

/// Aggregated residual costs across independently predicted modular crops.
#[derive(Default)]
pub(crate) struct SqueezePredictorCost {
    pub(in crate::lossless) costs: PredictorCosts,
}

impl SqueezePredictorCost {
    pub(crate) fn with_zero() -> Self {
        let mut c = Self::default();
        c.costs.collect_zero = true;
        c
    }

    pub(crate) fn safe_predictor(&self) -> u32 {
        self.costs.best_safe_predictor()
    }

    /// Add one independently predicted modular crop. Weighted prediction state
    /// resets here because the decoder resets it for every modular sub-image.
    #[cfg(test)]
    pub(crate) fn add_crop(
        &mut self,
        get: impl Fn(usize, usize) -> i32,
        w: usize,
        h: usize,
        use_wp: bool,
    ) {
        if w == 0 || h == 0 {
            return;
        }
        let disabled = !use_wp;
        let mut wp = WpState::new(w);
        for y in 0..h {
            for x in 0..w {
                let value = get(x, y) as i64;
                let neighbors = predictor_neighbors(&get, x, y, w);
                let weighted = if disabled {
                    0
                } else {
                    wp.predict(
                        x,
                        y,
                        neighbors.top,
                        neighbors.left,
                        neighbors.top_right,
                        neighbors.top_left,
                        neighbors.top_top,
                    )
                };
                self.costs.add(value, neighbors, weighted);
                if !disabled {
                    wp.update(value, x, y);
                }
            }
        }
    }

    pub(in crate::lossless) fn predictor(&self, use_wp: bool) -> u32 {
        self.costs.best_predictor(use_wp)
    }

    pub(crate) fn add_rows<'a, T: Sample + 'a>(
        &mut self,
        get_row: impl Fn(usize) -> &'a [T],
        w: usize,
        h: usize,
        use_wp: bool,
    ) where
        i64: From<T>,
    {
        self.add_rows_shared::<_, true>(&get_row, w, h, use_wp, WpParams::DEFAULT);
    }

    // Getter dispatch is once per row, outside the specialized pixel loops.
    pub(super) fn add_rows_shared<'a, T: Sample + 'a, const FLAT_SHORTCUT: bool>(
        &mut self,
        get_row: &dyn Fn(usize) -> &'a [T],
        w: usize,
        h: usize,
        use_wp: bool,
        wp_params: WpParams,
    ) where
        i64: From<T>,
    {
        if w == 0 || h == 0 {
            return;
        }
        let kernels = row_kernels::selected();
        let mut wp = use_wp.then(|| WpState::with_params(w, wp_params));
        let (mut north, mut north_north) = (None, None);
        for y in 0..h {
            let current = get_row(y);
            let rows = Rows {
                current,
                north,
                north_north,
            };
            if let Some(wp) = &mut wp {
                let row = wp.row_offsets(y);
                super::visit_predictor_row(
                    current,
                    north.unwrap_or(current),
                    north_north.or(north).unwrap_or(current),
                    y == 0,
                    |x, value, n| {
                        let neighbors = WpNeighbors {
                            north: n.top,
                            west: n.left,
                            north_east: n.top_right,
                            north_west: n.top_left,
                            north_north: n.top_top,
                        };
                        let weighted = if FLAT_SHORTCUT {
                            wp.predict_and_update_flat(value, x, row, neighbors)
                        } else {
                            wp.predict_and_update(value, x, row, neighbors)
                        };
                        add_symbol(
                            &mut self.costs.histograms[0],
                            pack_signed((value - weighted) as i32),
                        );
                    },
                );
            }
            T::costs(
                kernels,
                rows,
                &mut self.costs.histograms,
                self.costs.collect_zero.then_some(&mut self.costs.zero_hist),
                wp.is_none(),
            );
            self.costs.total += w as u64;
            north_north = north;
            north = Some(current);
        }
    }
}

#[inline]
pub(super) fn add_symbol(hist: &mut Vec<u64>, symbol: u32) {
    let symbol = symbol as usize;
    if hist.len() <= symbol {
        hist.resize(symbol + 1, 0);
    }
    hist[symbol] += 1;
}

pub(in crate::lossless) struct PredictorCosts {
    pub(super) entropy_of_hist: EntropyOfHistFn,
    pub(super) histograms: [Vec<u64>; SLOW_PREDICTORS.len()],
    /// Residual histogram for the Zero predictor (the raw values). Collected
    /// only when `collect_zero` is set (the lossy-modular path); the lossless
    /// callers skip the extra bump.
    pub(super) zero_hist: Vec<u64>,
    pub(super) collect_zero: bool,
    pub(super) total: u64,
}

impl Default for PredictorCosts {
    fn default() -> Self {
        Self {
            entropy_of_hist: selected_entropy_of_hist_fn(),
            histograms: Default::default(),
            zero_hist: Vec::new(),
            collect_zero: false,
            total: 0,
        }
    }
}

impl PredictorCosts {
    /// Merge independently predicted crops before evaluating entropy costs.
    pub(crate) fn merge(&mut self, other: &Self) {
        debug_assert_eq!(self.collect_zero, other.collect_zero);
        for (dest, src) in self.histograms.iter_mut().zip(&other.histograms) {
            if dest.len() < src.len() {
                dest.resize(src.len(), 0);
            }
            for (dest, &src) in dest.iter_mut().zip(src) {
                *dest += src;
            }
        }
        if self.zero_hist.len() < other.zero_hist.len() {
            self.zero_hist.resize(other.zero_hist.len(), 0);
        }
        for (dest, &src) in self.zero_hist.iter_mut().zip(&other.zero_hist) {
            *dest += src;
        }
        self.total += other.total;
    }

    #[inline]
    #[cfg(test)]
    pub(super) fn add(&mut self, value: i64, neighbors: super::PredictorNeighbors, weighted: i64) {
        for (candidate, &pred_id) in SLOW_PREDICTORS.iter().enumerate() {
            let pred = super::predictor_value(pred_id, neighbors, weighted);
            let symbol = pack_signed((value - pred) as i32) as usize;
            let hist = &mut self.histograms[candidate];
            if hist.len() <= symbol {
                hist.resize(symbol + 1, 0);
            }
            hist[symbol] += 1;
        }
        if self.collect_zero {
            let symbol = pack_signed(value as i32) as usize;
            if self.zero_hist.len() <= symbol {
                self.zero_hist.resize(symbol + 1, 0);
            }
            self.zero_hist[symbol] += 1;
        }
        self.total += 1;
    }

    /// Best predictor among Zero and the scale-equivariant subset — the only
    /// predictors a channel coded at 1/q scale with a leaf multiplier can use.
    pub(super) fn best_safe_predictor(&self) -> u32 {
        let entropy_of_hist = self.entropy_of_hist;
        debug_assert!(self.collect_zero);
        let mut best_id = PREDICTOR_ZERO;
        let mut best_bits = entropy_of_hist(&self.zero_hist, self.total);
        for (candidate, &pred_id) in SLOW_PREDICTORS.iter().enumerate() {
            if !matches!(
                pred_id,
                PREDICTOR_GRADIENT | PREDICTOR_SELECT | PREDICTOR_LEFT | PREDICTOR_TOP
            ) {
                continue;
            }
            let bits = entropy_of_hist(&self.histograms[candidate], self.total);
            if bits < best_bits {
                best_bits = bits;
                best_id = pred_id;
            }
        }
        best_id
    }

    pub(super) fn best_predictor(&self, use_wp: bool) -> u32 {
        let entropy_of_hist = self.entropy_of_hist;
        // Without WP the Weighted candidate (index 0) is skipped.
        let first = usize::from(!use_wp);
        let mut best_id = SLOW_PREDICTORS[first];
        let mut best_bits = entropy_of_hist(&self.histograms[first], self.total);
        for (candidate, &pred_id) in SLOW_PREDICTORS.iter().enumerate().skip(first + 1) {
            let bits = entropy_of_hist(&self.histograms[candidate], self.total);
            if bits < best_bits {
                best_bits = bits;
                best_id = pred_id;
            }
        }
        best_id
    }
}

/// Evaluate all Slow-mode predictors in one traversal and choose the lowest
/// order-0 residual entropy. Weighted remains the deterministic tie-breaker.
#[cfg(test)]
pub(crate) fn choose_predictor_for_plane(
    get: impl Fn(usize, usize) -> i32,
    w: usize,
    h: usize,
    use_wp: bool,
) -> u32 {
    choose_predictor_for_plane_with_wp(get, w, h, WpParams::DEFAULT, use_wp)
}

pub(crate) fn choose_predictor_for_rows<'a, T: Sample + 'a>(
    get_row: impl Fn(usize) -> &'a [T],
    w: usize,
    h: usize,
    use_wp: bool,
) -> u32
where
    i64: From<T>,
{
    if w == 0 || h == 0 {
        return fixed_predictor(use_wp);
    }
    let mut costs = SqueezePredictorCost::default();
    costs.add_rows(get_row, w, h, use_wp);
    costs.predictor(use_wp)
}

#[cfg(test)]
pub(super) fn choose_predictor_for_plane_with_wp(
    get: impl Fn(usize, usize) -> i32,
    w: usize,
    h: usize,
    wp_params: WpParams,
    use_wp: bool,
) -> u32 {
    if w == 0 || h == 0 {
        return fixed_predictor(use_wp);
    }
    let disabled = !use_wp;
    let mut wp = WpState::with_params(w, wp_params);
    let mut costs = PredictorCosts::default();
    for gy in 0..h {
        for gx in 0..w {
            let value = get(gx, gy) as i64;
            let neighbors = predictor_neighbors(&get, gx, gy, w);
            let weighted = if disabled {
                0
            } else {
                wp.predict(
                    gx,
                    gy,
                    neighbors.top,
                    neighbors.left,
                    neighbors.top_right,
                    neighbors.top_left,
                    neighbors.top_top,
                )
            };
            costs.add(value, neighbors, weighted);
            if !disabled {
                wp.update(value, gx, gy);
            }
        }
    }
    costs.best_predictor(use_wp)
}

pub(in crate::lossless) fn choose_predictors_with_wp(
    linear: &Image3Si,
    alpha: Option<&AlphaPlane>,
    xsize: usize,
    ysize: usize,
    num_color: usize,
    pool: &ThreadPool,
    scratch: &mut CoderScratch,
    wp_params: WpParams,
    use_wp: bool,
) -> [u32; 4] {
    let mut preds = [fixed_predictor(use_wp); 4];
    let num_channels = num_color + usize::from(alpha.is_some());
    let selected = pool.steal_map(scratch, num_channels, |chan, _scratch| {
        let mut costs = SqueezePredictorCost::default();
        if chan < num_color {
            let pd = linear.plane_data(chan);
            costs.add_rows_shared::<_, false>(
                &|y| &pd[y * xsize..][..xsize],
                xsize,
                ysize,
                use_wp,
                wp_params,
            )
        } else {
            let a = alpha.expect("alpha channel must exist");
            match a {
                AlphaPlane::U8(data) => costs.add_rows_shared::<_, false>(
                    &|y| &data[y * xsize..][..xsize],
                    xsize,
                    ysize,
                    use_wp,
                    wp_params,
                ),
                AlphaPlane::U16 { data, .. } => costs.add_rows_shared::<_, false>(
                    &|y| &data[y * xsize..][..xsize],
                    xsize,
                    ysize,
                    use_wp,
                    wp_params,
                ),
                AlphaPlane::F32(data) => costs.add_rows_shared::<_, false>(
                    &|y| &data[y * xsize..][..xsize],
                    xsize,
                    ysize,
                    use_wp,
                    wp_params,
                ),
            }
        }
        costs.predictor(use_wp)
    });
    preds[..num_color].copy_from_slice(&selected[..num_color]);
    if alpha.is_some() {
        preds[3] = selected[num_color];
    }
    preds
}