oximg 0.9.0

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
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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,
        ..Params::default()
    };
    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,
        &Params::default(),
        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,
        &Params::default(),
        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,
        &Params::default(),
        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,
            &Params::default(),
            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,
            &Params::default(),
            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,
            &Params::default(),
            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,
        ..Params::default()
    };
    let mut s = Scratch::default();
    if let Ok(dec) = Decompress::new_mem(cut) {
        let _ = decode_resize(
            &mut s,
            dec,
            320,
            320,
            &Params::default(),
            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);
}

/// Deterministic 4-component JPEG source: plain CMYK (Adobe APP14
/// transform 0) or YCCK (transform 2). The scanlines are written in
/// libjpeg's stored convention, which is Adobe-inverted (0 = full
/// ink, 255 = no ink).
fn make_cmyk_jpeg(w: usize, h: usize, ycck: bool) -> Vec<u8> {
    let mut px = Vec::with_capacity(w * h * 4);
    for y in 0..h {
        for x in 0..w {
            // Smooth gradients survive DCT quantization better than
            // noise, keeping pixel-level assertions meaningful.
            px.push((x * 255 / w.max(1)) as u8);
            px.push((y * 255 / h.max(1)) as u8);
            px.push(((x + y) * 255 / (w + h)) as u8);
            px.push(255 - (y * 128 / h.max(1)) as u8);
        }
    }
    let mut comp = Compress::new(ColorSpace::JCS_CMYK);
    if ycck {
        comp.set_color_space(ColorSpace::JCS_YCCK);
    }
    comp.set_size(w, h);
    comp.set_quality(95.0);
    let mut started = comp.start_compress(Vec::new()).unwrap();
    started.write_scanlines(&px).unwrap();
    started.finish().unwrap()
}

/// CMYK and YCCK sources decode to RGB via the naive composite
/// (`r = c'·k'/255` on the stored Adobe-inverted samples). The
/// reference applies the same formula to the raw CMYK planes decoded
/// by libjpeg itself, pinning oximg's plumbing (YCCK normalization,
/// in-place 4→3 compaction, the exact-size resize join)
/// byte-for-byte; independent third-party ground truth lives in
/// tests/formats_cmyk.rs against committed djpeg references.
#[test]
fn cmyk_and_ycck_sources_decode_to_naive_rgb() {
    for ycck in [false, true] {
        let jpeg = make_cmyk_jpeg(64, 48, ycck);
        let (rgb, w, h) = decode_and_resize(&jpeg, 64, 48, 1).unwrap();
        assert_eq!((w, h), (64, 48), "ycck={ycck}");
        let dec = Decompress::new_mem(&jpeg).unwrap();
        assert_eq!(
            dec.color_space(),
            if ycck {
                ColorSpace::JCS_YCCK
            } else {
                ColorSpace::JCS_CMYK
            }
        );
        let mut started = dec.to_colorspace(ColorSpace::JCS_CMYK).unwrap();
        let planes: Vec<u8> = started.read_scanlines().unwrap();
        started.finish().unwrap();
        let want: Vec<u8> = planes
            .chunks_exact(4)
            .flat_map(|px| {
                let k = px[3] as u32;
                [0, 1, 2].map(|c| ((px[c] as u32 * k + 127) / 255) as u8)
            })
            .collect();
        assert_eq!(rgb, want, "ycck={ycck}");
    }
}

/// Byte-compare a CMYK decode through the pipeline against the same
/// shared machinery fed a reference decode: raw planes from libjpeg
/// (same DCT scale the pipeline picks) + the naive composite +
/// `resize_pixels_to` at the same `parallel`. Same backend on both
/// sides, so the expectation is exact.
fn assert_cmyk_matches_reference(jpeg: &[u8], box_px: u32, parallel: usize) {
    let (got, w, h) = decode_and_resize(jpeg, box_px, box_px, parallel).unwrap();

    let mut dec = Decompress::new_mem(jpeg).unwrap();
    let (src_w, src_h) = dec.size();
    dec.scale(dct_scale_num(src_w, src_h, w, h, dct_margin()));
    let mut started = dec.to_colorspace(ColorSpace::JCS_CMYK).unwrap();
    let (dec_w, dec_h) = (started.width(), started.height());
    let planes: Vec<u8> = started.read_scanlines().unwrap();
    started.finish().unwrap();
    let mut s = Scratch::default();
    let chunk = scratch_u8(&mut s.chunk8, dec_w * dec_h * 3);
    for (d, px) in chunk.chunks_exact_mut(3).zip(planes.chunks_exact(4)) {
        let k = px[3] as u32;
        for (c, &v) in px[..3].iter().enumerate() {
            d[c] = ((v as u32 * k + 127) / 255) as u8;
        }
    }
    let p = Params {
        parallel,
        ..Params::default()
    };
    resize_pixels_to(&mut s, 3, dec_w, dec_h, w, h, &p).unwrap();
    assert_eq!(
        got,
        &s.out8[..w * h * 3],
        "box={box_px} parallel={parallel} decode={dec_w}x{dec_h} out={w}x{h}"
    );
}

/// A CMYK decode that engages DCT shrink-on-load (num < 8 — the
/// full-size fixture comparisons never do) must byte-match the
/// reference-fed machinery: pins chunk8 sizing, the in-place 4→3
/// compaction, and the resize join at scaled dims.
#[test]
fn cmyk_dct_scaled_decode_matches_reference() {
    // 256x192 in a 64x64 box → fit 64x48; the 1.7 margin wants
    // ≥109x82 → num=4, a 128x96 scaled decode ahead of the resize.
    assert_eq!(dct_scale_num(256, 192, 64, 48, 1.7), 4);
    assert_cmyk_matches_reference(&make_cmyk_jpeg(256, 192, true), 64, 1);
}

/// The band-parallel arm of the CMYK resize join, pinned the same
/// way. (parallel=1 and parallel>1 legitimately take different
/// resize backends — bytes are stable per config, not across
/// OXIMG_PAR values — so the reference runs at the same parallel.)
#[test]
fn cmyk_band_parallel_matches_reference() {
    let jpeg = make_cmyk_jpeg(97, 61, true);
    let (_, w, h) = decode_and_resize(&jpeg, 48, 48, 2).unwrap();
    assert_eq!((w, h), (48, 30));
    assert_cmyk_matches_reference(&jpeg, 48, 2);
}

#[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);
}

/// Issue #14: the output format's dimension ceiling is one more
/// constraint on the same fit box. WebP caps a side at 16383, so a
/// tall source must come back scaled to fit — the largest WebP that
/// keeps the source's shape — instead of failing at the encoder.
#[test]
fn webp_output_is_clamped_to_the_format_ceiling() {
    let webp = |max_w: u32, max_h: u32| {
        let p = Params {
            max_width: max_w,
            max_height: max_h,
            output: Some(ImageFormat::Webp),
            ..Params::default()
        };
        let c = clamp_to_format(&p, ImageFormat::Webp);
        (c.max_width, c.max_height)
    };
    // The reporter's case: width=1920 on a 2000x19708 source. The box
    // tightens, and fit_dims then lands on the imgproxy answer.
    assert_eq!(webp(1920, u32::MAX), (1920, 16383));
    assert_eq!(fit_dims(2000, 19708, 1920, 16383), (1663, 16383));
    // An unconstrained request on a tall source: both axes capped.
    assert_eq!(webp(u32::MAX, u32::MAX), (16383, 16383));
    assert_eq!(fit_dims(2000, 19708, 16383, 16383), (1663, 16383));
    // Boxes already inside the ceiling are untouched, and sources
    // inside it never move.
    assert_eq!(webp(800, 600), (800, 600));
    assert_eq!(fit_dims(300, 200, 16383, 16383), (300, 200));
    // Exactly at the limit stays at the limit (the cap is inclusive).
    assert_eq!(fit_dims(2000, 16383, 16383, 16383), (2000, 16383));

    // Only WebP has a ceiling worth enforcing: the same tall request
    // in another format keeps its full box.
    for target in [ImageFormat::Jpeg, ImageFormat::Png] {
        let p = Params {
            max_width: 1920,
            max_height: u32::MAX,
            output: Some(target),
            ..Params::default()
        };
        let c = clamp_to_format(&p, target);
        assert_eq!(
            (c.max_width, c.max_height),
            (1920, u32::MAX),
            "{target:?} must not be clamped"
        );
    }
}

/// Issue #17's core claim in arithmetic: at equal pixel counts the
/// decode cost varies by more than an order of magnitude, so a pixel
/// cap cannot bound memory while a byte estimate can. The shapes and
/// the measured peaks come from the field validation on the issue.
#[test]
fn decode_cost_separates_what_pixel_counts_cannot() {
    let mib = |b: u64| b as f64 / (1024.0 * 1024.0);
    let p = &Params::default();

    // Baseline JPEG, 3980x59828 (238 MP) at width=1920, whose WebP
    // output clamps to 16383 tall: streaming, so only the output side
    // is resident. Measured peak 92 MiB.
    let baseline = DecodeCost::streaming().with_output(1090, 16383, 3);
    let ratio = mib(baseline.bytes()) / 92.0;
    assert!(
        (1.0..3.0).contains(&ratio),
        "baseline JPEG: {:.0} MiB vs 92 measured ({ratio:.2}x)",
        mib(baseline.bytes())
    );

    // RGB PNG, 2250x26115 (58.8 MP) at width=1920 (output clamped to
    // 16383 tall): full frame, plus the linear-light u16 copy, plus the
    // output side. Measured peak 592 MiB — the case the first attempt
    // under-estimated 3.5x, which is the dangerous direction.
    let png = DecodeCost::full_frame(2250, 26115, 3, p)
        .with_output(1411, 16383, 3)
        .with_compressed(12 << 20);
    let ratio = mib(png.bytes()) / 592.0;
    assert!(
        (1.0..2.0).contains(&ratio),
        "PNG: {:.0} MiB vs 592 measured ({ratio:.2}x)",
        mib(png.bytes())
    );

    // Progressive CMYK 4:4:4, ~150 MP at width=1920: four-channel
    // staging at the shrink-on-load size, plus coefficient arrays no
    // output size reduces. Measured peak 1231 MiB.
    let num = dct_scale_num(12247, 12247, 1920, 1920, 1.7) as usize;
    let (dw, dh) = ((12247 * num).div_ceil(8), (12247 * num).div_ceil(8));
    let prog = DecodeCost::full_frame(dw, dh, 4, p)
        .with_output(1920, 1920, 4)
        .with_progressive_coefficients(12247, 12247, 4);
    let ratio = mib(prog.bytes()) / 1231.0;
    assert!(
        (1.0..2.5).contains(&ratio),
        "progressive CMYK: {:.0} MiB vs 1231 measured ({ratio:.2}x)",
        mib(prog.bytes())
    );

    // Every estimate must sit *above* its measured peak: under-
    // estimating is what gets a container OOM-killed while the cap
    // reports itself satisfied.
    for (name, est, peak) in [
        ("baseline", baseline.bytes(), 92.0),
        ("png", png.bytes(), 592.0),
        ("progressive", prog.bytes(), 1231.0),
    ] {
        assert!(mib(est) >= peak, "{name} under-estimates its peak");
    }

    // The progressive term is output-independent: a smaller output
    // barely helps, which is why pixel- and output-based reasoning
    // both fail on those sources.
    let smaller = DecodeCost::full_frame(dw / 2, dh / 2, 4, p)
        .with_output(480, 480, 4)
        .with_progressive_coefficients(12247, 12247, 4);
    assert!(
        smaller.bytes() > prog.bytes() / 2,
        "progressive cost does not scale with the output"
    );

    // And the spread the issue is about: cost per *source* pixel across
    // these shapes spans an order of magnitude.
    let per_px = |c: &DecodeCost, src_px: f64| c.bytes() as f64 / src_px;
    let cheap = per_px(&baseline, 238e6);
    let dear = per_px(&prog, 150e6);
    assert!(
        dear / cheap > 10.0,
        "spread across shapes: {cheap:.3} vs {dear:.3} B per source pixel"
    );
}

/// Issue #22: a caller-held source buffer is resident for the whole
/// decode, so the in-memory entry point must count it in the estimate
/// — the streaming-JPEG path otherwise carries no compressed term at
/// all, and a buffered remote source would be under-counted by exactly
/// its own size (the direction that gets a container OOM-killed).
/// The streaming entry points must keep counting zero.
#[test]
fn caller_held_source_counts_in_the_decode_estimate() {
    let jpeg = make_test_jpeg(320, 240, false);
    let p = Params {
        max_width: 100,
        max_height: 100,
        ..Params::default()
    };

    process(&jpeg, &p).unwrap();
    let (cost, _) = LAST_COST.get().expect("a decode just ran");
    assert_eq!(
        cost.compressed_bytes,
        jpeg.len() as u64,
        "process(&bytes) must count the caller's buffer"
    );

    let dir = std::env::temp_dir().join(format!("oximg-held-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("held.jpg");
    std::fs::write(&path, &jpeg).unwrap();
    process_path(&path, &p).unwrap();
    let (cost, _) = LAST_COST.get().expect("a decode just ran");
    assert_eq!(
        cost.compressed_bytes, 0,
        "the streaming path holds no source buffer"
    );
    let _ = std::fs::remove_dir_all(&dir);

    // A buffered format counts both copies: srcbuf and the caller's.
    let png = {
        let (out, fmt) = process(
            &jpeg,
            &Params {
                output: Some(ImageFormat::Png),
                ..Params::default()
            },
        )
        .unwrap();
        assert_eq!(fmt, ImageFormat::Png);
        out
    };
    process(&png, &p).unwrap();
    let (cost, _) = LAST_COST.get().expect("a decode just ran");
    assert_eq!(
        cost.compressed_bytes,
        2 * png.len() as u64,
        "a buffered format holds the source twice: srcbuf + the caller's copy"
    );
}

/// `larger_fit` is what keeps the output-side estimate conservative
/// before a source's orientation is known (issue #17 review): it must
/// return whichever of the two candidate fits covers more pixels, with
/// the axes back in stored order.
#[test]
fn larger_fit_covers_the_swapped_orientation() {
    let box_ = |w: u32, h: u32| Params {
        max_width: w,
        max_height: h,
        ..Params::default()
    };
    // The review's shape: 4000x1000 under a width-only box. Upright it
    // fits to 1920x480; presented as 1000x4000 by orientation 6 it fits
    // to 1000x4000 — four times the pixels, and what must be counted.
    assert_eq!(
        super::formats::larger_fit(4000, 1000, &box_(1920, u32::MAX)),
        (4000, 1000)
    );
    // The mirror case: the unoriented fit is already the larger one.
    assert_eq!(
        super::formats::larger_fit(1000, 4000, &box_(1920, u32::MAX)),
        (1000, 4000)
    );
    // A symmetric box makes both candidates equal, so the stored
    // orientation is returned unchanged.
    assert_eq!(
        super::formats::larger_fit(4000, 1000, &box_(500, 500)),
        (500, 125)
    );
    // Sources inside the box are never enlarged either way.
    assert_eq!(
        super::formats::larger_fit(300, 200, &box_(1920, u32::MAX)),
        (300, 200)
    );
}