zenpixels-convert 0.2.9

Transfer-function-aware pixel conversion, gamut mapping, and codec format negotiation for zenpixels
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
#![allow(deprecated)]
//! Tests for `finalize_for_output` — the atomic output preparation path.
//!
//! This is a critical function with zero prior test coverage.

use alloc::sync::Arc;
use core::sync::atomic::{AtomicU32, Ordering};

use zenpixels_convert::cms::{ColorManagement, RowTransform};
use zenpixels_convert::{
    Cicp, ColorAuthority, ColorOrigin, PixelBuffer, PixelDescriptor, PixelFormat,
    finalize_for_output, output::OutputProfile,
};

extern crate alloc;

// ---------------------------------------------------------------------------
// Stub CMS implementation
// ---------------------------------------------------------------------------

/// A no-op CMS that always fails `build_transform`.
struct NoopCms;

impl ColorManagement for NoopCms {
    type Error = &'static str;

    fn build_transform(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        Err("no-op CMS: ICC transforms not supported")
    }

    fn identify_profile(&self, _icc: &[u8]) -> Option<Cicp> {
        None
    }
}

/// A CMS that copies src to dst (identity transform).
struct IdentityCms;

struct IdentityTransform;

impl RowTransform for IdentityTransform {
    fn transform_row(&self, src: &[u8], dst: &mut [u8], _width: u32) {
        let len = src.len().min(dst.len());
        dst[..len].copy_from_slice(&src[..len]);
    }
}

impl ColorManagement for IdentityCms {
    type Error = &'static str;

    fn build_transform(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        Ok(Box::new(IdentityTransform))
    }

    fn identify_profile(&self, _icc: &[u8]) -> Option<Cicp> {
        None
    }
}

/// A CMS that tracks which method was called (ICC vs CICP).
struct TrackingCms {
    icc_calls: AtomicU32,
    cicp_calls: AtomicU32,
}

impl TrackingCms {
    fn new() -> Self {
        Self {
            icc_calls: AtomicU32::new(0),
            cicp_calls: AtomicU32::new(0),
        }
    }
    fn icc_calls(&self) -> u32 {
        self.icc_calls.load(Ordering::Relaxed)
    }
    fn cicp_calls(&self) -> u32 {
        self.cicp_calls.load(Ordering::Relaxed)
    }
    fn total_calls(&self) -> u32 {
        self.icc_calls() + self.cicp_calls()
    }
}

impl ColorManagement for TrackingCms {
    type Error = &'static str;

    fn build_transform(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        self.icc_calls.fetch_add(1, Ordering::Relaxed);
        Ok(Box::new(IdentityTransform))
    }

    fn build_transform_for_format(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
        _src_format: PixelFormat,
        _dst_format: PixelFormat,
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        self.icc_calls.fetch_add(1, Ordering::Relaxed);
        Ok(Box::new(IdentityTransform))
    }

    fn identify_profile(&self, _icc: &[u8]) -> Option<Cicp> {
        None
    }
}

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------

fn make_rgb8_buffer(width: u32, height: u32, pixel: [u8; 3]) -> PixelBuffer {
    let mut data = Vec::new();
    for _ in 0..width * height {
        data.extend_from_slice(&pixel);
    }
    PixelBuffer::from_vec(data, width, height, PixelDescriptor::RGB8_SRGB).unwrap()
}

fn make_rgba8_buffer(width: u32, height: u32, pixel: [u8; 4]) -> PixelBuffer {
    let mut data = Vec::new();
    for _ in 0..width * height {
        data.extend_from_slice(&pixel);
    }
    PixelBuffer::from_vec(data, width, height, PixelDescriptor::RGBA8_SRGB).unwrap()
}

// ---------------------------------------------------------------------------
// SameAsOrigin tests
// ---------------------------------------------------------------------------

#[test]
fn same_as_origin_identity_preserves_pixels() {
    let buf = make_rgb8_buffer(2, 2, [100, 150, 200]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let slice = ready.pixels();
    let row = slice.row(0);
    assert_eq!(&row[..3], &[100, 150, 200]);
    assert_eq!(&row[3..6], &[100, 150, 200]);
}

#[test]
fn same_as_origin_metadata_has_no_icc_no_cicp_for_assumed() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let meta = ready.metadata();
    assert!(meta.icc.is_none());
    assert!(meta.cicp.is_none());
    assert!(meta.hdr.is_none());
}

#[test]
fn same_as_origin_preserves_cicp_from_origin() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(Cicp::SRGB);

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let meta = ready.metadata();
    assert_eq!(meta.cicp, Some(Cicp::SRGB));
}

#[test]
fn same_as_origin_with_format_change_converts() {
    // Source is RGB8, target is RGBA8 — must convert.
    let buf = make_rgb8_buffer(2, 1, [100, 150, 200]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgba8,
        &NoopCms,
    )
    .unwrap();

    let slice = ready.pixels();
    let row = slice.row(0);
    // RGB → RGBA adds alpha=255
    assert_eq!(row[0], 100);
    assert_eq!(row[1], 150);
    assert_eq!(row[2], 200);
    assert_eq!(row[3], 255);
}

// ---------------------------------------------------------------------------
// Named profile tests
// ---------------------------------------------------------------------------

#[test]
fn named_srgb_produces_cicp_metadata() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(Cicp::SRGB),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let meta = ready.metadata();
    assert!(meta.icc.is_none());
    assert_eq!(meta.cicp, Some(Cicp::SRGB));
}

#[test]
fn named_profile_converts_format() {
    // Source is RGBA8, target format is Rgb8 — must drop alpha.
    let buf = make_rgba8_buffer(2, 1, [100, 150, 200, 255]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(Cicp::SRGB),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let slice = ready.pixels();
    let row = slice.row(0);
    assert_eq!(&row[..3], &[100, 150, 200]);
    assert_eq!(&row[3..6], &[100, 150, 200]);
}

// ---------------------------------------------------------------------------
// ICC profile tests
// ---------------------------------------------------------------------------

#[test]
fn icc_profile_output_embeds_icc_bytes() {
    let fake_icc: Arc<[u8]> = Arc::from(vec![0u8; 64].into_boxed_slice());
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc.clone()),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let meta = ready.metadata();
    assert!(meta.icc.is_some());
    assert_eq!(meta.icc.as_ref().unwrap().len(), 64);
    assert!(meta.cicp.is_none());
}

#[test]
fn icc_with_source_icc_uses_cms() {
    use zenpixels_convert::ColorContext;

    let src_icc: Arc<[u8]> = Arc::from(vec![1u8; 32].into_boxed_slice());
    let dst_icc: Arc<[u8]> = Arc::from(vec![2u8; 32].into_boxed_slice());

    let buf = make_rgb8_buffer(2, 1, [100, 150, 200]);
    let buf = buf.with_color_context(Arc::new(ColorContext::from_icc(src_icc.to_vec())));
    let origin = ColorOrigin::from_icc(src_icc.to_vec());

    // IdentityCms copies src→dst, so pixels should be preserved.
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(dst_icc),
        PixelFormat::Rgb8,
        &IdentityCms,
    )
    .unwrap();

    let slice = ready.pixels();
    let row = slice.row(0);
    assert_eq!(&row[..3], &[100, 150, 200]);
}

#[test]
fn icc_without_source_icc_falls_through_to_row_converter() {
    // Source has no ICC profile, so CMS is not invoked. Falls through to RowConverter path.
    let dst_icc: Arc<[u8]> = Arc::from(vec![2u8; 32].into_boxed_slice());
    let buf = make_rgb8_buffer(2, 1, [100, 150, 200]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(dst_icc),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let slice = ready.pixels();
    let row = slice.row(0);
    assert_eq!(&row[..3], &[100, 150, 200]);
}

// ---------------------------------------------------------------------------
// EncodeReady API tests
// ---------------------------------------------------------------------------

#[test]
fn encode_ready_into_parts_works() {
    let buf = make_rgb8_buffer(2, 2, [50, 100, 150]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();

    let (pixels, metadata) = ready.into_parts();
    assert_eq!(pixels.width(), 2);
    assert_eq!(pixels.height(), 2);
    assert!(metadata.icc.is_none());
}

// ---------------------------------------------------------------------------
// Multi-row conversion
// ---------------------------------------------------------------------------

#[test]
fn multi_row_conversion_is_correct() {
    // 3×2 image, convert RGB8 → RGBA8
    let buf = make_rgb8_buffer(3, 2, [10, 20, 30]);
    let origin = ColorOrigin::assumed();

    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgba8,
        &NoopCms,
    )
    .unwrap();

    let slice = ready.pixels();
    for y in 0..2 {
        let row = slice.row(y);
        for x in 0..3 {
            let off = x as usize * 4;
            assert_eq!(row[off], 10, "row {y} pixel {x} R");
            assert_eq!(row[off + 1], 20, "row {y} pixel {x} G");
            assert_eq!(row[off + 2], 30, "row {y} pixel {x} B");
            assert_eq!(row[off + 3], 255, "row {y} pixel {x} A");
        }
    }
}

// ---------------------------------------------------------------------------
// ColorAuthority decision table tests (12 rows)
// ---------------------------------------------------------------------------

fn fake_icc() -> Arc<[u8]> {
    Arc::from(vec![0xFFu8; 32].into_boxed_slice())
}

fn p3_cicp() -> Cicp {
    Cicp::DISPLAY_P3
}

fn srgb_cicp() -> Cicp {
    Cicp::SRGB
}

/// Row 1: Icc authority, no cicp, no icc, SameAsOrigin → no transform
#[test]
fn authority_row01_icc_none_none_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed();
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0);
    assert!(ready.metadata().icc.is_none());
    assert!(ready.metadata().cicp.is_none());
}

/// Row 2: Icc authority, no cicp, sRGB icc, SameAsOrigin → no transform
#[test]
fn authority_row02_icc_none_srgb_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc(fake_icc().to_vec());
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "SameAsOrigin should not invoke CMS");
    assert!(ready.metadata().icc.is_some());
}

/// Row 3: Icc authority, no cicp, P3 icc, Icc(srgb) → CMS from ICC bytes
#[test]
fn authority_row03_icc_none_p3icc_to_srgb() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc(fake_icc().to_vec());
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.icc_calls(), 1, "should use ICC transform");
    assert_eq!(cms.cicp_calls(), 0, "should not use CICP");
}

/// Row 4: Icc authority, P3 cicp, no icc, Icc(srgb) → no ICC bytes, no CMS call
#[test]
fn authority_row04_icc_p3cicp_noicc_fallback() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    // Icc authority but no ICC, only CICP — no ICC bytes available for CMS.
    // build_cms_transform requires ICC bytes on both sides; CICP-only sources
    // fall through to the RowConverter path (no CMS call).
    let origin = ColorOrigin::from_cicp(p3_cicp()).with_color_authority(ColorAuthority::Icc);
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "no ICC bytes on source → no CMS call");
}

/// Row 5: Icc authority, sRGB cicp, sRGB icc, SameAsOrigin → no transform
#[test]
fn authority_row05_icc_srgb_srgb_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), srgb_cicp())
        .with_color_authority(ColorAuthority::Icc);
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "SameAsOrigin should not invoke CMS");
    assert!(ready.metadata().icc.is_some());
    assert_eq!(ready.metadata().cicp, Some(srgb_cicp()));
}

/// Row 6: Icc authority, P3 cicp, P3 icc, Icc(srgb) → CMS from ICC (ignore CICP)
#[test]
fn authority_row06_icc_p3cicp_p3icc_to_srgb() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), p3_cicp())
        .with_color_authority(ColorAuthority::Icc);
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.icc_calls(), 1, "should use ICC (authoritative)");
    assert_eq!(cms.cicp_calls(), 0, "should not use CICP");
}

/// Row 7: Cicp authority, no cicp, no icc, SameAsOrigin → no transform
#[test]
fn authority_row07_cicp_none_none_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed().with_color_authority(ColorAuthority::Cicp);
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0);
    assert!(ready.metadata().icc.is_none());
}

/// Row 8: Cicp authority, sRGB cicp, any icc, SameAsOrigin → no transform
#[test]
fn authority_row08_cicp_srgb_anyicc_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), srgb_cicp())
        .with_color_authority(ColorAuthority::Cicp);
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "SameAsOrigin should not invoke CMS");
    assert_eq!(ready.metadata().cicp, Some(srgb_cicp()));
}

/// Row 9: Cicp authority, P3 cicp, no icc, Icc(srgb) → no ICC bytes, no CMS call
#[test]
fn authority_row09_cicp_p3_noicc_to_srgb() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    // CICP authority but no ICC bytes — CMS requires ICC bytes, so no transform.
    let origin = ColorOrigin::from_cicp(p3_cicp());
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "no ICC bytes on source → no CMS call");
}

/// Row 10: Cicp authority, P3 cicp, P3 icc, Icc(srgb) → CMS uses ICC bytes
/// (build_cms_transform always uses ICC bytes when available, regardless of authority)
#[test]
fn authority_row10_cicp_p3_p3icc_to_srgb() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), p3_cicp());
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(
        cms.icc_calls(),
        1,
        "should use ICC bytes (only ICC path available)"
    );
}

/// Row 11: Cicp authority, no cicp, P3 icc, Icc(srgb) → fallback CMS from ICC
#[test]
fn authority_row11_cicp_nocicp_p3icc_fallback() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin =
        ColorOrigin::from_icc(fake_icc().to_vec()).with_color_authority(ColorAuthority::Cicp);
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.icc_calls(), 1, "should fall back to ICC transform");
    assert_eq!(cms.cicp_calls(), 0, "should not use CICP (none available)");
}

/// Row 12: Icc authority, P3 cicp, P3 icc, SameAsOrigin → no transform
#[test]
fn authority_row12_icc_p3_p3icc_same() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), p3_cicp())
        .with_color_authority(ColorAuthority::Icc);
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "SameAsOrigin should not invoke CMS");
    assert!(ready.metadata().icc.is_some());
    assert_eq!(ready.metadata().cicp, Some(p3_cicp()));
}

// ---------------------------------------------------------------------------
// Additional coverage: both-missing, error paths, Named target
// ---------------------------------------------------------------------------

/// A CMS that always fails — exercises error mapping paths.
struct FailingCms;

impl ColorManagement for FailingCms {
    type Error = &'static str;

    fn build_transform(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        Err("deliberate ICC failure")
    }

    fn build_transform_for_format(
        &self,
        _src_icc: &[u8],
        _dst_icc: &[u8],
        _src_format: PixelFormat,
        _dst_format: PixelFormat,
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        Err("deliberate ICC failure")
    }

    fn identify_profile(&self, _icc: &[u8]) -> Option<Cicp> {
        None
    }
}

/// Icc authority, no icc, no cicp, Icc(target) → no source, falls through
#[test]
fn authority_icc_neither_field_to_icc_target() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed(); // Icc, no icc, no cicp
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "no source profile → no CMS call");
    // Falls through to RowConverter, pixels preserved
    let slice = ready.pixels();
    let row = slice.row(0);
    assert_eq!(&row[..3], &[128, 128, 128]);
}

/// Cicp authority, no icc, no cicp, Icc(target) → no source, falls through
#[test]
fn authority_cicp_neither_field_to_icc_target() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed().with_color_authority(ColorAuthority::Cicp);
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "no source profile → no CMS call");
}

/// CMS ICC transform error is propagated
#[test]
fn authority_icc_transform_error_propagated() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc(fake_icc().to_vec());
    let result = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &FailingCms,
    );
    assert!(result.is_err(), "ICC transform failure should propagate");
}

/// CICP-only source with no ICC bytes → falls through (no CMS call, no error)
#[test]
fn authority_cicp_no_icc_bytes_falls_through() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(p3_cicp());
    let result = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &FailingCms,
    );
    // No ICC bytes on source → CMS is never called → no error.
    assert!(result.is_ok(), "no ICC bytes → no CMS call → no error");
}

/// Icc authority, no ICC bytes, CICP present → falls through (no CMS call)
#[test]
fn authority_icc_no_icc_bytes_cicp_present_falls_through() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(p3_cicp()).with_color_authority(ColorAuthority::Icc);
    let result = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &FailingCms,
    );
    // No ICC bytes on source → CMS is never called → no error.
    assert!(result.is_ok(), "no ICC bytes → no CMS call → no error");
}

/// CMS ICC fallback error is propagated (Cicp authority, no cicp, icc present)
#[test]
fn authority_cicp_icc_fallback_error_propagated() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin =
        ColorOrigin::from_icc(fake_icc().to_vec()).with_color_authority(ColorAuthority::Cicp);
    let result = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &FailingCms,
    );
    assert!(result.is_err(), "ICC fallback failure should propagate");
}

/// Named target never invokes CMS regardless of authority/metadata
#[test]
fn named_target_never_uses_cms_with_icc_authority() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc_and_cicp(fake_icc().to_vec(), p3_cicp())
        .with_color_authority(ColorAuthority::Icc);
    let cms = TrackingCms::new();
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(srgb_cicp()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "Named target uses matrices, not CMS");
    assert_eq!(ready.metadata().cicp, Some(srgb_cicp()));
    assert!(ready.metadata().icc.is_none());
}

/// Named target never invokes CMS regardless of authority/metadata (CICP authority)
#[test]
fn named_target_never_uses_cms_with_cicp_authority() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(p3_cicp());
    let cms = TrackingCms::new();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(srgb_cicp()),
        PixelFormat::Rgb8,
        &cms,
    )
    .unwrap();
    assert_eq!(cms.total_calls(), 0, "Named target uses matrices, not CMS");
}

// ---------------------------------------------------------------------------
// HDR passthrough tests
// TODO(0.3.0): Add HDR→SDR rejection tests once ConvertError has
// HdrTransferRequiresToneMapping. See imazen/zenpixels#10.
// ---------------------------------------------------------------------------

fn pq_cicp() -> Cicp {
    Cicp::BT2100_PQ
}

fn hlg_cicp() -> Cicp {
    Cicp::BT2100_HLG
}

/// HDR origin → SameAsOrigin → allowed (passthrough)
#[test]
fn hdr_pq_same_as_origin_allowed() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(pq_cicp());
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::SameAsOrigin,
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();
    assert_eq!(ready.metadata().cicp, Some(pq_cicp()));
}

/// HDR origin → HDR Named(PQ) target → allowed
#[test]
fn hdr_pq_to_hdr_named_allowed() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(pq_cicp());
    let ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(pq_cicp()),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();
    assert_eq!(ready.metadata().cicp, Some(pq_cicp()));
}

/// HDR (HLG) origin → HDR Named(HLG) target → allowed
#[test]
fn hdr_hlg_to_hdr_named_allowed() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(hlg_cicp());
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(hlg_cicp()),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();
}

/// SDR origin → SDR target → no HDR guard triggered
#[test]
fn sdr_to_sdr_no_hdr_guard() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_cicp(p3_cicp()); // P3 is SDR
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Named(srgb_cicp()),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();
}

/// SDR origin → ICC target → no HDR guard triggered
#[test]
fn sdr_to_icc_no_hdr_guard() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::from_icc(fake_icc().to_vec());
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &IdentityCms,
    )
    .unwrap();
}

/// No color metadata → no HDR guard triggered
#[test]
fn no_metadata_no_hdr_guard() {
    let buf = make_rgb8_buffer(1, 1, [128, 128, 128]);
    let origin = ColorOrigin::assumed();
    let _ready = finalize_for_output(
        &buf,
        &origin,
        OutputProfile::Icc(fake_icc()),
        PixelFormat::Rgb8,
        &NoopCms,
    )
    .unwrap();
}