oximg 0.4.3

High-performance image compression: library, CLI, and self-hostable server (PoC).
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
use super::*;

/// Deterministic RGB test frame encoded to a real JPEG source.
fn make_test_jpeg(w: usize, h: usize, gray: bool) -> Vec<u8> {
    let ch = if gray { 1 } else { 3 };
    let mut seed = 0x9E3779B9u32;
    let mut px = Vec::with_capacity(w * h * ch);
    for y in 0..h {
        for x in 0..w {
            for c in 0..ch {
                seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
                let noise = (seed >> 24) as usize;
                px.push(((x * 200 / w + y * 40 / h + c * 5 + noise / 4).min(255)) as u8);
            }
        }
    }
    let mut comp = Compress::new(if gray {
        ColorSpace::JCS_GRAYSCALE
    } else {
        ColorSpace::JCS_RGB
    });
    comp.set_size(w, h);
    comp.set_quality(90.0);
    let mut started = comp.start_compress(Vec::new()).unwrap();
    started.write_scanlines(&px).unwrap();
    started.finish().unwrap()
}

fn run_jpeg(jpeg: &[u8], fuse_quality: Option<f32>) -> Vec<u8> {
    run_jpeg_icc(jpeg, fuse_quality, None)
}

fn run_jpeg_icc(jpeg: &[u8], fuse_quality: Option<f32>, icc: Option<&[u8]>) -> Vec<u8> {
    let p = Params {
        max_width: 320,
        max_height: 320,
        quality: 80.0,
        encoder: Encoder::Jpegli,
        parallel: 1,
        output: None,
    };
    let fuse = match fuse_quality {
        Some(quality) => Fuse::Jpegli { quality },
        None => Fuse::Off,
    };
    let mut s = Scratch::default();
    let dec = Decompress::new_mem(jpeg).unwrap();
    match decode_resize(
        &mut s,
        dec,
        320,
        320,
        1,
        crate::meta::Orientation::UPRIGHT,
        fuse,
        icc,
    )
    .unwrap()
    {
        Decoded::Encoded(out) => {
            assert!(fuse_quality.is_some(), "fused output without fuse request");
            out
        }
        Decoded::Pixels { dst_w, dst_h } => {
            assert!(
                fuse_quality.is_none(),
                "fused path was requested but not taken"
            );
            encode_with_icc(&s.out8[..dst_w * dst_h * 3], dst_w, dst_h, &p, icc).unwrap()
        }
        #[cfg(feature = "avif")]
        Decoded::YuvPlanes { .. } => panic!("yuv fuse was not requested"),
        #[cfg(feature = "avif")]
        Decoded::PixelsSession { .. } => panic!("preheat fuse was not requested"),
    }
}

/// The fused jpegli encoder writes the ICC chain ahead of its
/// scanlines exactly like the serial encoder does — profiled
/// same-format JPEG keeps its bytes fuse-independent.
#[test]
fn fused_jpegli_bytes_match_serial_with_icc() {
    if !fuse_kernel_available() {
        return;
    }
    let jpeg = make_test_jpeg(799, 601, false);
    let icc: Vec<u8> = (0..70_000u32).map(|i| (i % 251) as u8).collect();
    let serial = run_jpeg_icc(&jpeg, None, Some(&icc));
    let fused = run_jpeg_icc(&jpeg, Some(80.0), Some(&icc));
    assert_eq!(serial, fused, "profiled fused/serial parity");
    // 70KB spans two APP2 chunks; both must survive intact.
    let mut chunks: Vec<(u8, Vec<u8>)> = Vec::new();
    let mut i = 2;
    while i + 4 <= fused.len() && fused[i] == 0xFF {
        let m = fused[i + 1];
        if m == 0xDA || m == 0xD9 {
            break;
        }
        let len = u16::from_be_bytes([fused[i + 2], fused[i + 3]]) as usize;
        let body = &fused[i + 4..i + 2 + len];
        if m == 0xE2 && body.starts_with(b"ICC_PROFILE\0") {
            chunks.push((body[12], body[14..].to_vec()));
        }
        i += 2 + len;
    }
    chunks.sort_by_key(|(seq, _)| *seq);
    let got: Vec<u8> = chunks.into_iter().flat_map(|(_, d)| d).collect();
    assert_eq!(got, icc, "profile reassembles from the fused output");
}

/// Resized RGB pixels via the given fuse mode (Off = the serial
/// streamed kernel path, Pixels = the cross-format fused worker).
fn run_jpeg_pixels(jpeg: &[u8], fuse: Fuse) -> Vec<u8> {
    let mut s = Scratch::default();
    let dec = Decompress::new_mem(jpeg).unwrap();
    match decode_resize(
        &mut s,
        dec,
        320,
        320,
        1,
        crate::meta::Orientation::UPRIGHT,
        fuse,
        None,
    )
    .unwrap()
    {
        Decoded::Pixels { dst_w, dst_h } => s.out8[..dst_w * dst_h * 3].to_vec(),
        Decoded::Encoded(_) => panic!("pixel run must not encode"),
        #[cfg(feature = "avif")]
        Decoded::YuvPlanes { .. } => panic!("yuv fuse was not requested"),
        #[cfg(feature = "avif")]
        Decoded::PixelsSession { .. } => panic!("preheat fuse was not requested"),
    }
}

#[cfg(feature = "avif")]
fn test_avif_params() -> crate::avif::AvifParams {
    crate::avif::AvifParams {
        quality: 55,
        alpha_quality: 55,
        ..Default::default()
    }
}

/// The fused AVIF path converts rows (and creates the encoder
/// session) during the decode overlap; its planes — and therefore
/// the encoded bytes — must match the serial path's full-frame
/// conversion of the same pixels exactly.
#[cfg(feature = "avif")]
fn run_jpeg_avif(jpeg: &[u8], yuv_fuse: bool) -> Vec<u8> {
    run_jpeg_avif_icc(jpeg, yuv_fuse, None)
}

#[cfg(feature = "avif")]
fn run_jpeg_avif_icc(jpeg: &[u8], yuv_fuse: bool, icc: Option<&[u8]>) -> Vec<u8> {
    let params = test_avif_params();
    let fuse = if yuv_fuse {
        Fuse::Yuv { params }
    } else {
        Fuse::Off
    };
    let mut s = Scratch::default();
    let dec = Decompress::new_mem(jpeg).unwrap();
    match decode_resize(
        &mut s,
        dec,
        320,
        320,
        1,
        crate::meta::Orientation::UPRIGHT,
        fuse,
        None,
    )
    .unwrap()
    {
        Decoded::Pixels { dst_w, dst_h } => {
            crate::avif::encode_avif(&s.out8[..dst_w * dst_h * 3], dst_w, dst_h, 3, &params, icc)
                .unwrap()
        }
        Decoded::YuvPlanes { session } => {
            crate::avif::encode_avif_with_session(session, &s.y16, &s.cb16, &s.cr16, icc).unwrap()
        }
        Decoded::PixelsSession { .. } => panic!("preheat fuse was not requested"),
        Decoded::Encoded(_) => panic!("avif run must not hit the jpegli fuse"),
    }
}

/// Oriented AVIF targets preheat their session on the fused
/// worker; the bytes must match the fully serial path (rotate on
/// out8, then encode_avif) exactly.
#[cfg(feature = "avif")]
#[test]
fn preheated_session_bytes_match_serial_oriented_avif() {
    if !fuse_kernel_available() {
        return;
    }
    let params = test_avif_params();
    let orientation = crate::meta::Orientation::from_rot_mirror(1, None); // 90° CCW
    let jpeg = make_test_jpeg(799, 601, false);
    let run = |fuse: Fuse| -> Vec<u8> {
        let mut s = Scratch::default();
        let dec = Decompress::new_mem(&jpeg).unwrap();
        match decode_resize(&mut s, dec, 320, 320, 1, orientation, fuse, None).unwrap() {
            Decoded::PixelsSession {
                dst_w,
                dst_h,
                session,
            } => {
                let dims = crate::meta::apply_orientation(
                    &s.out8[..dst_w * dst_h * 3],
                    dst_w,
                    dst_h,
                    3,
                    orientation,
                    &mut s.chunk8,
                );
                std::mem::swap(&mut s.out8, &mut s.chunk8);
                crate::avif::encode_avif_rgb_with_session(
                    session,
                    &s.out8[..dims.0 * dims.1 * 3],
                    dims.0,
                    dims.1,
                    None,
                )
                .unwrap()
            }
            Decoded::Pixels { dst_w, dst_h } => {
                let dims = crate::meta::apply_orientation(
                    &s.out8[..dst_w * dst_h * 3],
                    dst_w,
                    dst_h,
                    3,
                    orientation,
                    &mut s.chunk8,
                );
                std::mem::swap(&mut s.out8, &mut s.chunk8);
                crate::avif::encode_avif(
                    &s.out8[..dims.0 * dims.1 * 3],
                    dims.0,
                    dims.1,
                    3,
                    &params,
                    None,
                )
                .unwrap()
            }
            _ => panic!("unexpected decode result"),
        }
    };
    let serial = run(Fuse::Off);
    let preheated = run(Fuse::PixelsPreheat { params });
    assert_eq!(serial, preheated, "preheat must not change a byte");
}

#[cfg(feature = "avif")]
#[test]
fn fused_yuv_bytes_match_serial_avif() {
    if !fuse_kernel_available() {
        return;
    }
    // Odd dimensions exercise chunk boundaries, scalar tails, and
    // the odd-height final chroma row.
    for (w, h, gray) in [(799, 601, false), (400, 300, true), (321, 243, false)] {
        let jpeg = make_test_jpeg(w, h, gray);
        assert_eq!(
            run_jpeg_avif(&jpeg, false),
            run_jpeg_avif(&jpeg, true),
            "{w}x{h} gray={gray}"
        );
    }
    // With a profile the parity must hold too — the fused session
    // path and the one-shot path splice the identical colr.
    let jpeg = make_test_jpeg(321, 243, false);
    let icc: Vec<u8> = (0..500u32).map(|i| (i % 251) as u8).collect();
    let serial = run_jpeg_avif_icc(&jpeg, false, Some(&icc));
    let fused = run_jpeg_avif_icc(&jpeg, true, Some(&icc));
    assert_eq!(serial, fused, "profiled fused/serial parity");
    assert_eq!(crate::avif::extract_icc(&fused).as_deref(), Some(&icc[..]));
}

#[cfg(feature = "avif")]
#[test]
fn fused_yuv_survives_truncated_sources() {
    let jpeg = make_test_jpeg(799, 601, false);
    let cut = &jpeg[..jpeg.len() * 3 / 5];
    let mut s = Scratch::default();
    if let Ok(dec) = Decompress::new_mem(cut) {
        let _ = decode_resize(
            &mut s,
            dec,
            320,
            320,
            1,
            crate::meta::Orientation::UPRIGHT,
            Fuse::Yuv {
                params: test_avif_params(),
            },
            None,
        );
    }
}

#[test]
fn serial_jpeg_path_produces_valid_output() {
    let jpeg = make_test_jpeg(400, 300, false);
    let out = run_jpeg(&jpeg, None);
    assert!(out.starts_with(&[0xFF, 0xD8]), "not a JPEG");
}

fn fuse_kernel_available() -> bool {
    use crate::resize_kernel::RowKernel;
    if FuseKernel::detect() {
        true
    } else {
        eprintln!("skipping: no SIMD row kernel on this host");
        false
    }
}

/// The serial path streams rows through the same SIMD kernel the
/// fused path runs on its worker thread, so the bytes must match
/// exactly on every architecture.
#[test]
fn fused_path_bytes_match_serial_jpegli() {
    if !fuse_kernel_available() {
        return;
    }
    // Odd dimensions exercise chunk boundaries and scalar tails.
    let jpeg = make_test_jpeg(799, 601, false);
    assert_eq!(run_jpeg(&jpeg, None), run_jpeg(&jpeg, Some(80.0)));
}

#[test]
fn fused_path_is_deterministic_and_valid() {
    if !fuse_kernel_available() {
        return;
    }
    let jpeg = make_test_jpeg(799, 601, false);
    let a = run_jpeg(&jpeg, Some(80.0));
    let b = run_jpeg(&jpeg, Some(80.0));
    assert!(a.starts_with(&[0xFF, 0xD8]), "not a JPEG");
    assert_eq!(a, b, "fused output must not vary run to run");
    let (fmt, w, h) = probe(&a).unwrap();
    assert_eq!(fmt, ImageFormat::Jpeg);
    assert_eq!((w, h), (320, 241));
}

#[test]
fn fused_path_handles_grayscale_sources() {
    if !fuse_kernel_available() {
        return;
    }
    let jpeg = make_test_jpeg(400, 300, true);
    let fused = run_jpeg(&jpeg, Some(80.0));
    assert!(fused.starts_with(&[0xFF, 0xD8]), "not a JPEG");
    assert_eq!(run_jpeg(&jpeg, None), fused);
}

/// The cross-format fused worker writes the same rows the serial
/// streamed path writes inline, so out8 must match byte for byte.
#[test]
fn fused_pixels_match_serial_pixels() {
    if !fuse_kernel_available() {
        return;
    }
    // Odd dimensions exercise chunk boundaries and scalar tails.
    for (w, h, gray) in [(799, 601, false), (400, 300, true)] {
        let jpeg = make_test_jpeg(w, h, gray);
        assert_eq!(
            run_jpeg_pixels(&jpeg, Fuse::Off),
            run_jpeg_pixels(&jpeg, Fuse::Pixels),
            "{w}x{h} gray={gray}"
        );
    }
}

#[test]
fn fused_pixels_survive_truncated_sources() {
    let jpeg = make_test_jpeg(799, 601, false);
    let cut = &jpeg[..jpeg.len() * 3 / 5];
    let mut s = Scratch::default();
    if let Ok(dec) = Decompress::new_mem(cut) {
        let _ = decode_resize(
            &mut s,
            dec,
            320,
            320,
            1,
            crate::meta::Orientation::UPRIGHT,
            Fuse::Pixels,
            None,
        );
    }
}

#[test]
fn fused_path_survives_truncated_sources() {
    // Truncation mid-scan must neither hang the worker handoff nor
    // panic; libjpeg may error out or complete with fill data
    // depending on where the cut lands — both are acceptable here.
    let jpeg = make_test_jpeg(799, 601, false);
    let cut = &jpeg[..jpeg.len() * 3 / 5];
    let p = Params {
        max_width: 320,
        max_height: 320,
        quality: 80.0,
        encoder: Encoder::Jpegli,
        parallel: 1,
        output: None,
    };
    let mut s = Scratch::default();
    if let Ok(dec) = Decompress::new_mem(cut) {
        let _ = decode_resize(
            &mut s,
            dec,
            320,
            320,
            1,
            crate::meta::Orientation::UPRIGHT,
            Fuse::Jpegli { quality: p.quality },
            None,
        );
    }
}

#[test]
fn fit_dims_shrinks_proportionally() {
    assert_eq!(fit_dims(7360, 4912, 500, 500), (500, 334));
    assert_eq!(fit_dims(4912, 7360, 500, 500), (334, 500));
}

#[test]
fn fit_dims_never_enlarges() {
    assert_eq!(fit_dims(300, 200, 500, 500), (300, 200));
}

#[test]
fn band_resize_matches_single_thread() {
    // Synthetic gradient image; verify 2/3-band parallel resize is
    // byte-identical to the single-threaded output.
    let (sw, sh, dw, dh) = (317usize, 211usize, 123usize, 81usize);
    let src: Vec<u8> = (0..sw * sh * 3).map(|i| ((i * 7919) % 251) as u8).collect();
    let mut single = vec![0u8; dw * dh * 3];
    resize_bands(
        &src,
        sw,
        sh,
        &mut single,
        dw,
        dh,
        PixelType::U8x3,
        1,
        &mut None,
    )
    .unwrap();
    for threads in [2, 3] {
        let mut banded = vec![0u8; dw * dh * 3];
        resize_bands(
            &src,
            sw,
            sh,
            &mut banded,
            dw,
            dh,
            PixelType::U8x3,
            threads,
            &mut None,
        )
        .unwrap();
        assert_eq!(single, banded, "threads={threads} output differs");
    }
}

#[test]
fn luts_roundtrip_every_srgb_value() {
    // back(fwd(v)) must be the identity for all 256 sRGB values, or
    // unresized regions would shift colors through the linear path.
    let (fwd, back) = (fwd_lut(), back_lut());
    for v in 0..=255u8 {
        assert_eq!(back[fwd[v as usize] as usize], v, "value {v}");
    }
}

#[test]
fn preset_parsing_maps_and_defaults() {
    assert_eq!(Encoder::from_preset("fast"), Encoder::MozFast);
    assert_eq!(Encoder::from_preset("small"), Encoder::MozSmall);
    assert_eq!(Encoder::from_preset("jpegli"), Encoder::Jpegli);
    assert_eq!(Encoder::from_preset(""), Encoder::Jpegli);
    assert_eq!(Encoder::from_preset("bogus"), Encoder::Jpegli);
}

#[test]
fn content_types_match_formats() {
    assert_eq!(ImageFormat::Jpeg.content_type(), "image/jpeg");
    assert_eq!(ImageFormat::Png.content_type(), "image/png");
    assert_eq!(ImageFormat::Webp.content_type(), "image/webp");
    assert_eq!(ImageFormat::Avif.content_type(), "image/avif");
}

#[test]
fn sniff_detects_formats_by_magic_bytes() {
    let jpeg = *b"\xFF\xD8\xFF\xE0\x00\x10JFIF\x00\x01";
    assert_eq!(ImageFormat::sniff(&jpeg), Some(ImageFormat::Jpeg));
    let png = *b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0D";
    assert_eq!(ImageFormat::sniff(&png), Some(ImageFormat::Png));
    let webp = *b"RIFF\x00\x01\x00\x00WEBP";
    assert_eq!(ImageFormat::sniff(&webp), Some(ImageFormat::Webp));
    assert_eq!(
        ImageFormat::sniff(b"\x00\x00\x00\x1cftypavif"),
        Some(ImageFormat::Avif)
    );
    assert_eq!(ImageFormat::sniff(b"GIF89a\x00\x00\x00\x00\x00\x00"), None);
}

#[test]
fn dct_scale_picks_smallest_sufficient() {
    // 7360 * 1/8 = 920 >= 500 -> num = 1
    assert_eq!(dct_scale_num(7360, 4912, 500, 334, 1.0), 1);
    // 1000 * 4/8 = 500 >= 500, 667*4/8=334 >= 334 -> num = 4
    assert_eq!(dct_scale_num(1000, 667, 500, 334, 1.0), 4);
    // already at target size -> no scaling
    assert_eq!(dct_scale_num(500, 334, 500, 334, 1.0), 8);
}