edgefirst-codec 0.23.1

Image codec for decoding JPEG/PNG into pre-allocated EdgeFirst tensors
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

//! Integration tests: JPEG decode into Mem tensors with various configurations.

use edgefirst_codec::{
    peek_info, CodecError, DecodeOptions, ImageDecoder, ImageLoad, UnsupportedFeature,
};
use edgefirst_tensor::{PixelFormat, Tensor, TensorMemory, TensorTrait};

fn testdata(name: &str) -> Vec<u8> {
    let root = std::env::var("EDGEFIRST_TESTDATA_DIR")
        .map(std::path::PathBuf::from)
        .unwrap_or_else(|_| {
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .parent()
                .unwrap()
                .parent()
                .unwrap()
                .join("testdata")
        });
    let path = root.join(name);
    std::fs::read(&path).unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()))
}

#[test]
fn decode_zidane_rgb() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);
    assert_eq!(info.format, PixelFormat::Rgb);

    // Verify pixels are non-zero (not a blank decode)
    let map = tensor.map().unwrap();
    let pixels: &[u8] = &map;
    let nonzero = pixels[..info.width * info.height * 3]
        .iter()
        .filter(|&&v| v != 0)
        .count();
    assert!(
        nonzero > 1000,
        "expected many non-zero pixels, got {nonzero}"
    );
}

#[test]
fn decode_zidane_rgba() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgba, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgba)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);
    assert_eq!(info.format, PixelFormat::Rgba);
}

#[test]
fn decode_grey_jpeg() {
    let jpeg = testdata("grey.jpg");
    // grey.jpg is 1024×681
    let mut tensor =
        Tensor::<u8>::image(1024, 681, PixelFormat::Grey, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Grey)
                .with_exif(false),
        )
        .unwrap();
    assert!(info.width > 0 && info.height > 0);
    assert_eq!(info.format, PixelFormat::Grey);
}

#[test]
fn decode_person_rgb() {
    let jpeg = testdata("person.jpg");
    // person.jpg is a progressive JPEG — our baseline-only decoder rejects it
    let mut tensor =
        Tensor::<u8>::image(4256, 2532, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        &jpeg,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(
        result.is_err(),
        "progressive JPEG should be rejected by baseline decoder"
    );
}

#[test]
fn decode_f32_jpeg() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<f32>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);

    // Verify f32 values are in [0.0, 1.0]
    let map = tensor.map().unwrap();
    let pixels: &[f32] = &map;
    let sample_count = info.width * 3; // first row
    for &v in &pixels[..sample_count] {
        assert!((0.0..=1.0).contains(&v), "pixel value {v} out of range");
    }
}

#[test]
fn decode_capacity_error() {
    let jpeg = testdata("zidane.jpg"); // 1280×720
                                       // Allocate too small
    let mut tensor =
        Tensor::<u8>::image(100, 100, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        &jpeg,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(result.is_err());
    match result.unwrap_err() {
        edgefirst_codec::CodecError::InsufficientCapacity { image, tensor } => {
            assert_eq!(image, (1280, 720));
            assert_eq!(tensor, (100, 100));
        }
        other => panic!("expected InsufficientCapacity, got {other}"),
    }
}

#[test]
fn decode_reuse_pattern() {
    // The hot-loop reuse pattern: decode multiple different images into the same tensor
    // Allocate at max size (person.jpg is 4256×2532)
    let mut tensor =
        Tensor::<u8>::image(4256, 2532, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();

    let images = ["zidane.jpg", "giraffe.jpg", "jaguar.jpg"];
    for name in &images {
        let jpeg = testdata(name);
        let info = tensor
            .load_image(
                &mut decoder,
                &jpeg,
                &DecodeOptions::default()
                    .with_format(PixelFormat::Rgb)
                    .with_exif(false),
            )
            .unwrap();
        assert!(info.width > 0 && info.height > 0, "failed to decode {name}");
    }
}

#[test]
fn decode_jpeg_u16() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<u16>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);

    // u16 pixels should be scaled: u8 0→0, 255→65535
    let map = tensor.map().unwrap();
    let pixels: &[u16] = &map;
    let sample_count = info.width * 3;
    for &v in &pixels[..sample_count] {
        // All values should be multiples of 257 (u8 * 257 scaling)
        assert_eq!(v % 257, 0, "u16 pixel {v} is not a multiple of 257");
    }
    // Verify non-trivial content
    let nonzero = pixels[..sample_count].iter().filter(|&&v| v != 0).count();
    assert!(
        nonzero > 100,
        "expected many non-zero u16 pixels, got {nonzero}"
    );
}

#[test]
fn decode_jpeg_i8() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<i8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);

    // i8 uses XOR trick: u8 0→-128, 128→0, 255→127
    let map = tensor.map().unwrap();
    let pixels: &[i8] = &map;
    let sample_count = info.width * 3;
    // Should have a range spanning negative and positive
    let min = pixels[..sample_count].iter().copied().min().unwrap();
    let max = pixels[..sample_count].iter().copied().max().unwrap();
    assert!(min < 0, "expected negative i8 pixels, min={min}");
    assert!(max > 0, "expected positive i8 pixels, max={max}");
}

#[test]
fn decode_jpeg_i16() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<i16>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);

    // i16 uses XOR trick: u8 scale to u16 then XOR 0x8000
    let map = tensor.map().unwrap();
    let pixels: &[i16] = &map;
    let sample_count = info.width * 3;
    let min = pixels[..sample_count].iter().copied().min().unwrap();
    let max = pixels[..sample_count].iter().copied().max().unwrap();
    assert!(min < 0, "expected negative i16 pixels, min={min}");
    assert!(max > 0, "expected positive i16 pixels, max={max}");
}

#[test]
fn decode_jpeg_i8_xor_consistency() {
    // Verify that JPEG i8 decode matches manual u8→i8 XOR conversion
    let jpeg = testdata("zidane.jpg");

    let mut u8_tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut i8_tensor =
        Tensor::<i8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let opts = DecodeOptions::default()
        .with_format(PixelFormat::Rgb)
        .with_exif(false);

    u8_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();
    i8_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();

    let u8_map = u8_tensor.map().unwrap();
    let i8_map = i8_tensor.map().unwrap();
    let u8_pixels: &[u8] = &u8_map;
    let i8_pixels: &[i8] = &i8_map;

    // Check first 1000 pixels match the XOR trick
    for i in 0..1000 {
        let expected = (u8_pixels[i] ^ 0x80) as i8;
        assert_eq!(
            i8_pixels[i], expected,
            "pixel {i}: u8={}, i8={}, expected={}",
            u8_pixels[i], i8_pixels[i], expected
        );
    }
}

/// Compare our custom JPEG decoder output against the `image` crate pixel-by-pixel.
/// JPEG decoders may differ by ±1-2 LSBs due to IDCT rounding, so we allow
/// a per-pixel tolerance and compute mean absolute error (MAE).
#[test]
fn pixel_accuracy_vs_image_crate() {
    let jpeg_data = testdata("zidane.jpg");

    // Decode with our custom decoder
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg_data,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();

    // Decode with the `image` crate
    let ref_img = image::load_from_memory(&jpeg_data).unwrap().to_rgb8();
    let (ref_w, ref_h) = ref_img.dimensions();
    assert_eq!(info.width, ref_w as usize);
    assert_eq!(info.height, ref_h as usize);

    let map = tensor.map().unwrap();
    let our_pixels: &[u8] = unsafe { std::slice::from_raw_parts(map.as_ptr(), map.len()) };
    let ref_pixels = ref_img.as_raw();

    let w = info.width;
    let h = info.height;
    let stride = info.row_stride;
    let channels = 3;

    let mut max_diff: u32 = 0;
    let mut total_diff: u64 = 0;
    let mut pixel_count: u64 = 0;

    for y in 0..h {
        for x in 0..w {
            for c in 0..channels {
                let our_val = our_pixels[y * stride + x * channels + c] as i32;
                let ref_val = ref_pixels[(y * w + x) * channels + c] as i32;
                let diff = (our_val - ref_val).unsigned_abs();
                max_diff = max_diff.max(diff);
                total_diff += diff as u64;
                pixel_count += 1;
            }
        }
    }

    let mae = total_diff as f64 / pixel_count as f64;
    eprintln!("Pixel accuracy: MAE={mae:.3}, max_diff={max_diff}, pixels={pixel_count}");

    // JPEG decoders commonly differ by ±2 IDCT LSBs, amplified by color
    // conversion to ±8-12. The IEEE 1180 IDCT conformance spec allows ±1
    // peak error per coefficient; after color conversion this compounds.
    assert!(
        max_diff <= 12,
        "max pixel difference {max_diff} exceeds tolerance 12"
    );
    assert!(
        mae < 0.5,
        "mean absolute error {mae:.3} exceeds tolerance 0.5"
    );
}

/// Compare our greyscale JPEG output against the `image` crate.
#[test]
fn pixel_accuracy_grey_vs_image_crate() {
    let jpeg_data = testdata("grey.jpg");

    let mut tensor =
        Tensor::<u8>::image(1024, 681, PixelFormat::Grey, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg_data,
            &DecodeOptions::default()
                .with_format(PixelFormat::Grey)
                .with_exif(false),
        )
        .unwrap();

    let ref_img = image::load_from_memory(&jpeg_data).unwrap().to_luma8();
    let (ref_w, ref_h) = ref_img.dimensions();
    assert_eq!(info.width, ref_w as usize);
    assert_eq!(info.height, ref_h as usize);

    let map = tensor.map().unwrap();
    let our_pixels: &[u8] = unsafe { std::slice::from_raw_parts(map.as_ptr(), map.len()) };
    let ref_pixels = ref_img.as_raw();

    let w = info.width;
    let h = info.height;
    let stride = info.row_stride;

    let mut max_diff: u32 = 0;
    let mut total_diff: u64 = 0;

    for y in 0..h {
        for x in 0..w {
            let our_val = our_pixels[y * stride + x] as i32;
            let ref_val = ref_pixels[y * w + x] as i32;
            let diff = (our_val - ref_val).unsigned_abs();
            max_diff = max_diff.max(diff);
            total_diff += diff as u64;
        }
    }

    let pixel_count = (w * h) as f64;
    let mae = total_diff as f64 / pixel_count;
    eprintln!("Grey accuracy: MAE={mae:.3}, max_diff={max_diff}");

    assert!(
        max_diff <= 4,
        "max grey diff {max_diff} exceeds tolerance 4"
    );
    assert!(mae < 1.0, "grey MAE {mae:.3} exceeds tolerance 1.0");
}

/// Test decoding into an oversized tensor with stride padding.
/// The decoded image (1280×720) goes into a 1920×1080 tensor.
/// Verify padding bytes are untouched and decoded region is correct.
#[test]
fn decode_strided_oversized_tensor() {
    let jpeg = testdata("zidane.jpg");

    // Allocate larger than the image
    let mut tensor =
        Tensor::<u8>::image(1920, 1080, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();

    // Fill tensor with sentinel value
    {
        let mut map = tensor.map().unwrap();
        let bytes: &mut [u8] =
            unsafe { std::slice::from_raw_parts_mut(map.as_mut_ptr(), map.len()) };
        bytes.fill(0xAA);
    }

    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();

    assert_eq!(info.width, 1280);
    assert_eq!(info.height, 720);
    let stride = info.row_stride;

    let map = tensor.map().unwrap();
    let bytes: &[u8] = unsafe { std::slice::from_raw_parts(map.as_ptr(), map.len()) };

    // Verify decoded pixels are non-sentinel
    let decoded_row_bytes = 1280 * 3;
    for y in 0..720 {
        let row = &bytes[y * stride..y * stride + decoded_row_bytes];
        // At least some pixels should not be 0xAA
        let non_sentinel = row.iter().filter(|&&b| b != 0xAA).count();
        assert!(
            non_sentinel > 0,
            "row {y} appears to be all sentinel values"
        );
    }

    // Verify rows beyond the decoded height are untouched (sentinel)
    for y in 720..1080 {
        let row_start = y * stride;
        if row_start + decoded_row_bytes <= bytes.len() {
            let row = &bytes[row_start..row_start + decoded_row_bytes];
            assert!(
                row.iter().all(|&b| b == 0xAA),
                "row {y} should be untouched sentinel"
            );
        }
    }
}

#[test]
fn decode_truncated_jpeg() {
    let jpeg = testdata("zidane.jpg");
    let truncated = &jpeg[..100];
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        truncated,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(matches!(result, Err(CodecError::InvalidData(_))));
}

#[test]
fn decode_not_jpeg() {
    let mut bogus = testdata("zidane.png");
    bogus[..4].copy_from_slice(&[0xFF, 0xD8, 0xFF, 0xE0]);

    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        &bogus,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(matches!(result, Err(CodecError::InvalidData(_))));
}

#[test]
fn decode_empty_data() {
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        &[],
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(matches!(result, Err(CodecError::InvalidData(_))));
}

#[test]
fn decode_corrupt_markers() {
    let corrupt = [0xFF, 0xD8, 0xFF, 0x00];
    let mut tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let result = tensor.load_image(
        &mut decoder,
        &corrupt,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    );
    assert!(matches!(result, Err(CodecError::InvalidData(_))));
}

#[test]
fn decode_bgra_format() {
    let jpeg = testdata("zidane.jpg");
    let mut rgb =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut bgra =
        Tensor::<u8>::image(1280, 720, PixelFormat::Bgra, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();

    let rgb_info = rgb
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    let bgra_info = bgra
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Bgra)
                .with_exif(false),
        )
        .unwrap();

    assert_eq!(bgra_info.width, rgb_info.width);
    assert_eq!(bgra_info.height, rgb_info.height);
    assert_eq!(bgra_info.format, PixelFormat::Bgra);
    assert_eq!(bgra_info.row_stride, bgra_info.width * 4);

    let rgb_map = rgb.map().unwrap();
    let bgra_map = bgra.map().unwrap();
    let rgb_pixels: &[u8] = &rgb_map;
    let bgra_pixels: &[u8] = &bgra_map;
    let pixel_count = bgra_info.width * bgra_info.height;

    for i in 0..pixel_count {
        assert_eq!(bgra_pixels[i * 4], rgb_pixels[i * 3 + 2]);
        assert_eq!(bgra_pixels[i * 4 + 1], rgb_pixels[i * 3 + 1]);
        assert_eq!(bgra_pixels[i * 4 + 2], rgb_pixels[i * 3]);
        assert_eq!(bgra_pixels[i * 4 + 3], 255);
    }
}

#[test]
fn decode_exact_size_tensor() {
    use image::ImageDecoder as _;

    let jpeg = testdata("giraffe.jpg");
    let header =
        image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(jpeg.as_slice())).unwrap();
    let (width, height) = header.dimensions();

    let mut tensor = Tensor::<u8>::image(
        width as usize,
        height as usize,
        PixelFormat::Rgb,
        Some(TensorMemory::Mem),
    )
    .unwrap();
    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();

    assert_eq!(info.width, width as usize);
    assert_eq!(info.height, height as usize);
    assert_eq!(info.format, PixelFormat::Rgb);
    assert_eq!(info.row_stride, info.width * PixelFormat::Rgb.channels());
}

#[test]
fn decode_grey_to_rgb() {
    let jpeg = testdata("grey.jpg");
    let mut grey =
        Tensor::<u8>::image(1024, 681, PixelFormat::Grey, Some(TensorMemory::Mem)).unwrap();
    let mut rgb =
        Tensor::<u8>::image(1024, 681, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();

    let grey_info = grey
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Grey)
                .with_exif(false),
        )
        .unwrap();
    let rgb_info = rgb
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();

    assert_eq!(rgb_info.width, grey_info.width);
    assert_eq!(rgb_info.height, grey_info.height);
    assert_eq!(rgb_info.format, PixelFormat::Rgb);

    let grey_map = grey.map().unwrap();
    let rgb_map = rgb.map().unwrap();
    let grey_pixels: &[u8] = &grey_map;
    let rgb_pixels: &[u8] = &rgb_map;

    for y in 0..rgb_info.height {
        for x in 0..rgb_info.width {
            let grey_val = grey_pixels[y * grey_info.row_stride + x];
            let base = y * rgb_info.row_stride + x * 3;
            assert_eq!(rgb_pixels[base], grey_val);
            assert_eq!(rgb_pixels[base + 1], grey_val);
            assert_eq!(rgb_pixels[base + 2], grey_val);
        }
    }
}

#[test]
fn decode_with_exif_rotation() {
    use image::ImageDecoder as _;

    let jpeg = testdata("zidane_rotated_exif.jpg");
    let header =
        image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(jpeg.as_slice())).unwrap();
    let (stored_w, stored_h) = header.dimensions();
    let max_dim = stored_w.max(stored_h) as usize;

    let mut plain =
        Tensor::<u8>::image(max_dim, max_dim, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut oriented =
        Tensor::<u8>::image(max_dim, max_dim, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();

    let plain_info = plain
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();
    let oriented_info = oriented
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(true),
        )
        .unwrap();

    assert_eq!(plain_info.width, stored_w as usize);
    assert_eq!(plain_info.height, stored_h as usize);
    assert!(
        (oriented_info.width, oriented_info.height) == (plain_info.width, plain_info.height)
            || (oriented_info.width, oriented_info.height) == (plain_info.height, plain_info.width),
        "EXIF-applied dimensions should match stored dims or their rotation"
    );

    let map = oriented.map().unwrap();
    let pixels: &[u8] = &map;
    let decoded_bytes = oriented_info.width * oriented_info.height * PixelFormat::Rgb.channels();
    let nonzero = pixels[..decoded_bytes].iter().filter(|&&v| v != 0).count();
    assert!(nonzero > 1000, "expected EXIF decode to produce image data");
}

#[test]
fn decode_u16_scaling_consistency() {
    let jpeg = testdata("zidane.jpg");
    let mut u8_tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut u16_tensor =
        Tensor::<u16>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let opts = DecodeOptions::default()
        .with_format(PixelFormat::Rgb)
        .with_exif(false);

    let u8_info = u8_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();
    let u16_info = u16_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();

    assert_eq!(u8_info.width, u16_info.width);
    assert_eq!(u8_info.height, u16_info.height);

    let u8_map = u8_tensor.map().unwrap();
    let u16_map = u16_tensor.map().unwrap();
    let u8_pixels: &[u8] = &u8_map;
    let u16_pixels: &[u16] = &u16_map;
    let u16_stride = u16_info.row_stride / std::mem::size_of::<u16>();

    for y in 0..u8_info.height {
        for x in 0..u8_info.width * 3 {
            let u8_val = u8_pixels[y * u8_info.row_stride + x];
            let u16_val = u16_pixels[y * u16_stride + x];
            assert_eq!(u16_val, u16::from(u8_val) * 257);
        }
    }
}

#[test]
fn decode_f32_scaling_consistency() {
    let jpeg = testdata("zidane.jpg");
    let mut u8_tensor =
        Tensor::<u8>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut f32_tensor =
        Tensor::<f32>::image(1280, 720, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();
    let mut decoder = ImageDecoder::new();
    let opts = DecodeOptions::default()
        .with_format(PixelFormat::Rgb)
        .with_exif(false);

    let u8_info = u8_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();
    let f32_info = f32_tensor.load_image(&mut decoder, &jpeg, &opts).unwrap();

    assert_eq!(u8_info.width, f32_info.width);
    assert_eq!(u8_info.height, f32_info.height);

    let u8_map = u8_tensor.map().unwrap();
    let f32_map = f32_tensor.map().unwrap();
    let u8_pixels: &[u8] = &u8_map;
    let f32_pixels: &[f32] = &f32_map;
    let f32_stride = f32_info.row_stride / std::mem::size_of::<f32>();

    for y in 0..u8_info.height {
        for x in 0..u8_info.width * 3 {
            let u8_val = u8_pixels[y * u8_info.row_stride + x];
            let expected = f32::from(u8_val) / 255.0;
            let actual = f32_pixels[y * f32_stride + x];
            assert!(
                (actual - expected).abs() < 1e-6,
                "expected {expected}, got {actual}"
            );
        }
    }
}

#[test]
fn decode_stride_padding_untouched() {
    let jpeg = testdata("zidane.jpg");
    let mut tensor =
        Tensor::<u8>::image(1920, 1080, PixelFormat::Rgb, Some(TensorMemory::Mem)).unwrap();

    {
        let mut map = tensor.map().unwrap();
        let bytes: &mut [u8] = &mut map;
        bytes.fill(0x5A);
    }

    let mut decoder = ImageDecoder::new();
    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Rgb)
                .with_exif(false),
        )
        .unwrap();

    let decoded_row_bytes = info.width * PixelFormat::Rgb.channels();
    let map = tensor.map().unwrap();
    let bytes: &[u8] = &map;

    for y in 0..info.height {
        let row = &bytes[y * info.row_stride..(y + 1) * info.row_stride];
        assert!(
            row[..decoded_row_bytes].iter().any(|&b| b != 0x5A),
            "decoded portion of row {y} should contain image data"
        );
        assert!(
            row[decoded_row_bytes..].iter().all(|&b| b == 0x5A),
            "padding after decoded width in row {y} should remain untouched"
        );
    }

    for y in info.height..1080 {
        let row = &bytes[y * info.row_stride..(y + 1) * info.row_stride];
        assert!(
            row.iter().all(|&b| b == 0x5A),
            "rows past decoded height should remain untouched"
        );
    }
}

#[test]
fn decode_nv12_output() {
    let jpeg = testdata("zidane.jpg");
    // NV12 needs H * W + H/2 * W = 1.5 * H * W bytes.
    // For 1280×720: Y plane = 921600, UV plane = 460800, total = 1382400
    let width = 1280usize;
    let height = 720usize;
    let nv12_size = width * height * 3 / 2;

    // Create a tensor large enough for NV12 (1 channel, height*1.5 rows)
    let mut tensor = Tensor::<u8>::image(
        width,
        height * 3 / 2,
        PixelFormat::Grey,
        Some(TensorMemory::Mem),
    )
    .unwrap();
    let mut decoder = ImageDecoder::new();

    let info = tensor
        .load_image(
            &mut decoder,
            &jpeg,
            &DecodeOptions::default()
                .with_format(PixelFormat::Nv12)
                .with_exif(false),
        )
        .unwrap();
    assert_eq!(info.width, width);
    assert_eq!(info.height, height);
    assert_eq!(info.format, PixelFormat::Nv12);

    let map = tensor.map().unwrap();
    let bytes: &[u8] = &map;

    // Y plane should have non-zero data
    let y_nonzero = bytes[..width * height].iter().filter(|&&v| v != 0).count();
    assert!(
        y_nonzero > 1000,
        "Y plane should have many non-zero pixels, got {y_nonzero}"
    );

    // UV plane should have non-128 data (chrominance varies in real images)
    let uv_start = height * width;
    let uv_size = width * height / 2;
    if uv_start + uv_size <= bytes.len() {
        let uv_non128 = bytes[uv_start..uv_start + uv_size]
            .iter()
            .filter(|&&v| v != 128)
            .count();
        assert!(
            uv_non128 > 100,
            "UV plane should have varied chrominance, non-128 count: {uv_non128}"
        );
    }

    let _ = nv12_size;
}

#[test]
fn unsupported_progressive_jpeg_returns_typed_variant() {
    // person.jpg is a progressive JPEG — the codec rejects it with a
    // typed Unsupported(ProgressiveJpeg). Verifies the error model
    // upgrade from cluster B (callers can pattern-match instead of
    // string-matching).
    let jpeg = testdata("person.jpg");
    let opts = DecodeOptions::default();
    match peek_info(&jpeg, &opts) {
        Err(CodecError::Unsupported(UnsupportedFeature::ProgressiveJpeg)) => {}
        Err(other) => {
            panic!("expected Unsupported(ProgressiveJpeg), got {other:?}");
        }
        Ok(_) => panic!("progressive JPEG should not decode"),
    }
}

#[test]
fn nv12_odd_width_is_rejected() {
    // NV12 requires even dimensions by definition (chroma plane stores
    // one UV pair per 2×2 luma block, and the tensor row stride is
    // sized for img_w not img_w.div_ceil(2)*2). The codec rejects
    // odd-width NV12 up front rather than silently truncating the
    // right-most chroma column (which was the prior 0.22.x behaviour
    // and left a magenta/green edge artefact).
    //
    // jaguar.jpg is 789×384 (odd width).
    let jpeg = testdata("jaguar.jpg");
    let opts = DecodeOptions::default().with_format(PixelFormat::Nv12);

    match peek_info(&jpeg, &opts) {
        Err(CodecError::InvalidData(msg)) => {
            assert!(
                msg.contains("NV12") && msg.contains("even"),
                "expected NV12 even-dim rejection, got: {msg}"
            );
        }
        Err(other) => panic!("expected InvalidData for odd-width NV12, got {other:?}"),
        Ok(_) => panic!("odd-width NV12 should not peek successfully"),
    }
}

#[test]
fn partial_mcu_at_image_edge_decodes_full_width() {
    // jaguar.jpg is 789×384 — neither dim is a multiple of 16, so the
    // right-edge and bottom-edge MCUs are partial. A regression in the
    // MCU clip math would either truncate or write past the tensor end.
    // This test catches both by allocating exactly the image size and
    // verifying the last image row contains decoder output.
    let jpeg = testdata("jaguar.jpg");
    let info = peek_info(
        &jpeg,
        &DecodeOptions::default()
            .with_format(PixelFormat::Rgb)
            .with_exif(false),
    )
    .unwrap();
    let mut tensor = Tensor::<u8>::image(
        info.width,
        info.height,
        PixelFormat::Rgb,
        Some(TensorMemory::Mem),
    )
    .unwrap();
    {
        let mut map = tensor.map().unwrap();
        let slice: &mut [u8] = &mut map;
        for b in slice.iter_mut() {
            *b = 0xAA;
        }
    }
    let mut decoder = ImageDecoder::new();
    let opts = DecodeOptions::default()
        .with_format(PixelFormat::Rgb)
        .with_exif(false);
    decoder.decode_into(&jpeg, &mut tensor, &opts).unwrap();
    let map = tensor.map().unwrap();
    let bytes: &[u8] = &map;
    let stride = info.width * 3;
    let last_row = &bytes[(info.height - 1) * stride..info.height * stride];
    let sentinel_count = last_row.iter().filter(|&&b| b == 0xAA).count();
    assert!(
        sentinel_count < last_row.len() / 4,
        "bottom-edge MCU appears unwritten ({sentinel_count}/{} sentinel bytes)",
        last_row.len(),
    );
}