ctt 0.4.0

Compress images to GPU texture formats
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
//! High-level conversion entry point.

use crate::alpha::AlphaMode;
use crate::encoders::Quality;
use crate::error::{Error, Result};
use crate::format::TargetFormat;
use crate::processing::{
    self, Buffer, PipelineOutput, Swizzle, Variant, encode, load, mipmap, passthrough, store,
    swizzle,
};
use crate::surface::{ColorSpace, Image};
use crate::vk_format::FormatExt;

/// Output container format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Container {
    Dds,
    Ktx2(Option<Ktx2Supercompression>),
    /// Return the processed [`Image`] directly, without encoding into a file format.
    Raw,
}

/// Supercompression to apply when writing KTX2 files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Ktx2Supercompression {
    /// Zstandard compression. `level` is passed directly to the `zstd` crate.
    Zstd { level: i32 },
    /// ZLIB compression (deflate with zlib framing).
    Zlib { level: u8 },
}

impl Container {
    pub fn ktx2() -> Self {
        Container::Ktx2(None)
    }
    pub fn ktx2_zstd(level: i32) -> Self {
        Container::Ktx2(Some(Ktx2Supercompression::Zstd { level }))
    }
    pub fn ktx2_zlib(level: u8) -> Self {
        Container::Ktx2(Some(Ktx2Supercompression::Zlib { level }))
    }
}

/// Settings for the high-level [`convert`] function.
#[derive(Default)]
pub struct ConvertSettings {
    /// Target format. If `None`, the input format is preserved without compression.
    pub format: Option<TargetFormat>,
    pub container: Container,
    pub quality: Quality,
    pub output_color_space: Option<ColorSpace>,
    pub output_alpha: Option<AlphaMode>,
    pub swizzle: Option<Swizzle>,
    pub mipmap: bool,
    pub mipmap_count: Option<usize>,
    pub mipmap_filter: mipmap::MipmapFilter,
}

impl Default for Container {
    fn default() -> Self {
        Container::Ktx2(None)
    }
}

/// Convert an image.
///
/// The input [`Image`] should already be fully assembled. Use
/// [`split_cubemap`](crate::split_cubemap) to prepare cubemap inputs beforehand.
pub fn convert(image: Image, mut settings: ConvertSettings) -> Result<PipelineOutput> {
    profiling::scope!("convert");
    image.validate()?;

    let input_base = &image.surfaces[0][0];
    let input_fmt = input_base.format;
    let input_cs = input_base.color_space;
    let input_alpha = input_base.alpha;

    let (target_fmt, encoder_step) = resolve_target(input_fmt, &mut settings)?;

    let target_cs = settings.output_color_space.unwrap_or(input_cs);
    let target_alpha = settings.output_alpha.unwrap_or(input_alpha);

    // Format that ends up in the output container: the encoder's target when
    // one is set, otherwise the resolved target format.
    let final_target_fmt = encoder_step
        .as_ref()
        .map(|s| s.target_format)
        .unwrap_or(target_fmt);

    log::debug!(
        "convert: {input_fmt:?} ({input_cs:?}, {input_alpha:?}) → \
         {final_target_fmt:?} ({target_cs:?}, {target_alpha:?}) \
         container={:?} swizzle={} mipmap={}",
        settings.container,
        settings.swizzle.is_some(),
        settings.mipmap,
    );

    // Passthrough whenever the bytes already represent the requested output:
    // identical format (modulo the sRGB tag, which rides on the surface),
    // matching color space and alpha, and no pixel-level rewrite. Covers
    // compressed-in == compressed-out and avoids a lossy load/store roundtrip
    // for uncompressed identity conversions.
    let (input_base_fmt, _) = input_fmt.normalize();
    let (target_base_fmt, _) = final_target_fmt.normalize();
    let formats_match = input_base_fmt == target_base_fmt;
    let no_pixel_work = settings.swizzle.is_none() && !settings.mipmap;

    if formats_match && input_cs == target_cs && input_alpha == target_alpha && no_pixel_work {
        log::debug!("convert: taking passthrough path (format and processing match)");
        return passthrough::run(image, final_target_fmt, settings.container);
    }

    // Compressed inputs that didn't qualify for passthrough have nowhere to
    // go — the float/integer pipelines can't decode compressed data. Defer
    // to passthrough::run's strict format check so the error is meaningful.
    if input_fmt.is_compressed() {
        log::debug!(
            "convert: compressed input did not qualify for passthrough; \
             falling back to passthrough format check"
        );
        return passthrough::run(image, final_target_fmt, settings.container);
    }

    // 3D textures only flow through the passthrough fast path. The f32/u32
    // pipelines treat each Surface as a single 2D plane; they can't yet
    // process the stacked Z slices that 3D textures carry.
    if matches!(image.kind, crate::TextureKind::Texture3D) {
        return Err(Error::UnsupportedConversion(
            "3D textures are only supported in passthrough mode (no format change, swizzle, or mipmap generation)".into(),
        ));
    }

    let variant = processing::pick_variant(input_fmt, target_fmt).ok_or_else(|| {
        Error::UnsupportedConversion(format!(
            "cannot derive pipeline variant from {input_fmt:?}{target_fmt:?}"
        ))
    })?;

    if !processing::families_compatible(input_fmt, target_fmt) {
        return Err(Error::UnsupportedConversion(format!(
            "integer/float family mismatch: {input_fmt:?}{target_fmt:?}"
        )));
    }

    log::debug!("convert: routing through {variant:?} pipeline");

    match variant {
        Variant::F32 => convert_f32(image, settings, target_fmt, encoder_step),
        Variant::F64 => convert_f64(image, settings, target_fmt, encoder_step),
        Variant::U32 => convert_u32(image, settings, target_fmt, encoder_step),
        Variant::U64 => convert_u64(image, settings, target_fmt, encoder_step),
    }
}

/// Resolve the final output format and optional encoder step from settings.
///
/// Returns the format the store step should produce (= encoder input for
/// compressed targets, = `TargetFormat::Uncompressed` or input for non-compressed).
fn resolve_target(
    input_fmt: ktx2::Format,
    settings: &mut ConvertSettings,
) -> Result<(ktx2::Format, Option<encode::EncoderStep>)> {
    match settings.format.take() {
        Some(TargetFormat::Compressed { format, encoder }) => {
            let step = encode::EncoderStep {
                target_format: format,
                quality: settings.quality,
                encoder,
            };
            let required_input = step.required_input()?;
            Ok((required_input, Some(step)))
        }
        Some(TargetFormat::Uncompressed(fmt)) => Ok((fmt, None)),
        None => Ok((input_fmt, None)),
    }
}

fn convert_f32(
    image: Image,
    settings: ConvertSettings,
    target_fmt: ktx2::Format,
    encoder_step: Option<encode::EncoderStep>,
) -> Result<PipelineOutput> {
    let input_base = &image.surfaces[0][0];
    let target_color_space = settings
        .output_color_space
        .unwrap_or(input_base.color_space);
    let target_alpha = settings.output_alpha.unwrap_or(input_base.alpha);

    let mut out_layers = Vec::with_capacity(image.surfaces.len());
    for layer in image.surfaces {
        profiling::scope!("convert_f32_layer");
        let base = layer
            .into_iter()
            .next()
            .ok_or_else(|| Error::UnsupportedFormat("empty layer".into()))?;

        let mut buf: Buffer<f32> = load::load_f32(&base)?;

        if let Some(sw) = &settings.swizzle {
            swizzle::apply_f32(&mut buf, sw);
        }

        let bufs = if settings.mipmap {
            mipmap::generate(buf, settings.mipmap_filter, settings.mipmap_count)?
        } else {
            vec![buf]
        };

        let mut mips = Vec::with_capacity(bufs.len());
        for b in bufs {
            mips.push(store::store_f32(
                b,
                target_fmt,
                target_color_space,
                target_alpha,
            )?);
        }
        out_layers.push(mips);
    }

    let processed = Image {
        surfaces: out_layers,
        kind: image.kind,
    };

    let final_image = match encoder_step {
        Some(step) => encode::encode_all(processed, &step)?,
        None => processed,
    };

    passthrough::emit(final_image, settings.container)
}

fn convert_f64(
    image: Image,
    settings: ConvertSettings,
    target_fmt: ktx2::Format,
    encoder_step: Option<encode::EncoderStep>,
) -> Result<PipelineOutput> {
    if settings.mipmap {
        return Err(Error::UnsupportedFormat(
            "f64 pipeline does not yet support mipmap generation".into(),
        ));
    }

    let input_base = &image.surfaces[0][0];
    let target_color_space = settings
        .output_color_space
        .unwrap_or(input_base.color_space);
    let target_alpha = settings.output_alpha.unwrap_or(input_base.alpha);

    let mut out_layers = Vec::with_capacity(image.surfaces.len());
    for layer in image.surfaces {
        profiling::scope!("convert_f64_layer");
        let mut mips = Vec::with_capacity(layer.len());
        for base in layer {
            let mut buf = load::load_f64(&base)?;
            if let Some(sw) = &settings.swizzle {
                swizzle::apply_f64(&mut buf, sw);
            }
            mips.push(store::store_f64(
                buf,
                target_fmt,
                target_color_space,
                target_alpha,
            )?);
        }
        out_layers.push(mips);
    }

    let processed = Image {
        surfaces: out_layers,
        kind: image.kind,
    };

    let final_image = match encoder_step {
        Some(step) => encode::encode_all(processed, &step)?,
        None => processed,
    };

    passthrough::emit(final_image, settings.container)
}

fn convert_u32(
    image: Image,
    settings: ConvertSettings,
    target_fmt: ktx2::Format,
    encoder_step: Option<encode::EncoderStep>,
) -> Result<PipelineOutput> {
    let input_alpha = image.surfaces[0][0].alpha;
    check_uint_unsupported(&settings, input_alpha)?;
    let target_alpha = settings.output_alpha.unwrap_or(input_alpha);

    let mut out_layers = Vec::with_capacity(image.surfaces.len());
    for layer in image.surfaces {
        profiling::scope!("convert_u32_layer");
        let mut mips = Vec::with_capacity(layer.len());
        for base in layer {
            let mut buf = load::load_u32(&base)?;
            if let Some(sw) = &settings.swizzle {
                swizzle::apply_u32(&mut buf, sw);
            }
            mips.push(store::store_u32(buf, target_fmt, target_alpha)?);
        }
        out_layers.push(mips);
    }

    let processed = Image {
        surfaces: out_layers,
        kind: image.kind,
    };

    if encoder_step.is_some() {
        return Err(Error::UnsupportedConversion(
            "integer (uint/sint) formats cannot be block-compressed".into(),
        ));
    }

    passthrough::emit(processed, settings.container)
}

fn convert_u64(
    image: Image,
    settings: ConvertSettings,
    target_fmt: ktx2::Format,
    encoder_step: Option<encode::EncoderStep>,
) -> Result<PipelineOutput> {
    let input_alpha = image.surfaces[0][0].alpha;
    check_uint_unsupported(&settings, input_alpha)?;
    let target_alpha = settings.output_alpha.unwrap_or(input_alpha);

    let mut out_layers = Vec::with_capacity(image.surfaces.len());
    for layer in image.surfaces {
        profiling::scope!("convert_u64_layer");
        let mut mips = Vec::with_capacity(layer.len());
        for base in layer {
            let mut buf = load::load_u64(&base)?;
            if let Some(sw) = &settings.swizzle {
                swizzle::apply_u64(&mut buf, sw);
            }
            mips.push(store::store_u64(buf, target_fmt, target_alpha)?);
        }
        out_layers.push(mips);
    }

    let processed = Image {
        surfaces: out_layers,
        kind: image.kind,
    };

    if encoder_step.is_some() {
        return Err(Error::UnsupportedConversion(
            "integer (uint/sint) formats cannot be block-compressed".into(),
        ));
    }

    passthrough::emit(processed, settings.container)
}

fn check_uint_unsupported(settings: &ConvertSettings, input_alpha: AlphaMode) -> Result<()> {
    if settings.mipmap {
        return Err(Error::UnsupportedFormat(
            "integer pipeline does not support mipmap generation".into(),
        ));
    }
    if settings.output_color_space.is_some() {
        return Err(Error::UnsupportedFormat(
            "integer pipeline does not support output_color_space change".into(),
        ));
    }
    if let Some(out_alpha) = settings.output_alpha
        && out_alpha != input_alpha
    {
        return Err(Error::UnsupportedFormat(
            "integer pipeline does not support output_alpha change".into(),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::surface::Surface;

    fn make_image(
        data: Vec<u8>,
        width: u32,
        height: u32,
        format: ktx2::Format,
        cs: ColorSpace,
        alpha: AlphaMode,
    ) -> Image {
        let bpp = format.bytes_per_pixel().unwrap() as u32;
        Image {
            surfaces: vec![vec![Surface {
                data,
                width,
                height,
                depth: 1,
                stride: width * bpp,
                slice_stride: 0,
                format,
                color_space: cs,
                alpha,
            }]],
            kind: crate::TextureKind::Texture2D,
        }
    }

    #[test]
    fn raw_roundtrip_rgba8_linear() {
        let image = make_image(
            vec![10, 20, 30, 40, 50, 60, 70, 80],
            2,
            1,
            ktx2::Format::R8G8B8A8_UNORM,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let out = convert(
            image,
            ConvertSettings {
                container: Container::Raw,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Raw(img) => {
                assert_eq!(
                    img.surfaces[0][0].data,
                    vec![10, 20, 30, 40, 50, 60, 70, 80]
                );
            }
            _ => panic!("expected Raw output"),
        }
    }

    #[test]
    fn convert_rgba8_to_r8_channel_drop() {
        let image = make_image(
            vec![100, 150, 200, 255],
            1,
            1,
            ktx2::Format::R8G8B8A8_UNORM,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let out = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Uncompressed(ktx2::Format::R8_UNORM)),
                container: Container::Raw,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Raw(img) => {
                assert_eq!(img.surfaces[0][0].format, ktx2::Format::R8_UNORM);
                assert_eq!(img.surfaces[0][0].data, vec![100]);
            }
            _ => panic!("expected Raw output"),
        }
    }

    #[test]
    fn convert_with_mipmap() {
        let data = vec![128u8; 8 * 8 * 4];
        let image = make_image(
            data,
            8,
            8,
            ktx2::Format::R8G8B8A8_UNORM,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let out = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Uncompressed(ktx2::Format::R8G8B8A8_UNORM)),
                container: Container::Raw,
                mipmap: true,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Raw(img) => {
                assert_eq!(img.surfaces[0].len(), 4); // 8,4,2,1
            }
            _ => panic!("expected Raw output"),
        }
    }

    #[test]
    fn convert_integer_family_mismatch_errors() {
        let image = make_image(
            vec![100, 150, 200, 255],
            1,
            1,
            ktx2::Format::R8G8B8A8_UNORM,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let err = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Uncompressed(ktx2::Format::R8G8B8A8_UINT)),
                container: Container::Raw,
                ..Default::default()
            },
        )
        .unwrap_err();
        match err {
            Error::UnsupportedConversion(_) => {}
            _ => panic!("expected UnsupportedConversion, got {err:?}"),
        }
    }

    #[test]
    fn convert_rgba8_to_bc7_ktx2() {
        // 4x4 opaque image, encode to BC7 via default encoder, wrap in KTX2.
        let image = make_image(
            vec![128u8; 4 * 4 * 4],
            4,
            4,
            ktx2::Format::R8G8B8A8_UNORM,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let out = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Compressed {
                    format: ktx2::Format::BC7_UNORM_BLOCK,
                    encoder: crate::encoders::Encoder::Auto,
                }),
                container: Container::ktx2(),
                quality: Quality::UltraFast,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Encoded(bytes) => {
                // Verify KTX2 magic.
                assert!(bytes.len() > 12);
                assert_eq!(&bytes[0..12], b"\xabKTX 20\xbb\r\n\x1a\n");
            }
            _ => panic!("expected Encoded output"),
        }
    }

    #[test]
    fn convert_passthrough_compressed() {
        // BC7 input → BC7 output should use the passthrough fast path.
        let bc7_bytes = vec![0xFFu8; 16]; // 1 BC7 block
        let image = Image {
            surfaces: vec![vec![Surface {
                data: bc7_bytes.clone(),
                width: 4,
                height: 4,
                depth: 1,
                stride: 16,
                slice_stride: 0,
                format: ktx2::Format::BC7_UNORM_BLOCK,
                color_space: ColorSpace::Linear,
                alpha: AlphaMode::Opaque,
            }]],
            kind: crate::TextureKind::Texture2D,
        };
        let out = convert(
            image,
            ConvertSettings {
                container: Container::Raw,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Raw(img) => {
                assert_eq!(img.surfaces[0][0].data, bc7_bytes);
            }
            _ => panic!("expected Raw output"),
        }
    }

    /// Build a 4×2 RGBA8 image whose row stride is `width * 4 + 8` bytes —
    /// each row carries 8 bytes of trailing padding that the pipeline must
    /// skip. The padding is filled with 0xCC so any padding-leak shows up
    /// loudly in the output.
    fn padded_rgba8_4x2() -> Image {
        let pad = 0xCCu8;
        // Row 0: 4 distinct pixels, then 8 bytes padding (stride = 24).
        let mut data = Vec::new();
        for x in 0..4u8 {
            data.extend_from_slice(&[10 + x, 20 + x, 30 + x, 255]);
        }
        data.extend_from_slice(&[pad; 8]);
        for x in 0..4u8 {
            data.extend_from_slice(&[100 + x, 110 + x, 120 + x, 255]);
        }
        data.extend_from_slice(&[pad; 8]);

        Image {
            surfaces: vec![vec![Surface {
                data,
                width: 4,
                height: 2,
                depth: 1,
                stride: 4 * 4 + 8,
                slice_stride: 0,
                format: ktx2::Format::R8G8B8A8_UNORM,
                color_space: ColorSpace::Linear,
                alpha: AlphaMode::Straight,
            }]],
            kind: crate::TextureKind::Texture2D,
        }
    }

    /// Encoding path: padded-stride RGBA8 → swizzle to BGRA → Raw.
    /// The store step always writes a tight stride, and no padding byte
    /// (0xCC) should bleed into the output.
    #[test]
    fn convert_padded_stride_swizzle_to_raw_is_tight() {
        let image = padded_rgba8_4x2();
        let out = convert(
            image,
            ConvertSettings {
                container: Container::Raw,
                swizzle: Some(Swizzle([
                    processing::SwizzleChannel::B,
                    processing::SwizzleChannel::G,
                    processing::SwizzleChannel::R,
                    processing::SwizzleChannel::A,
                ])),
                ..Default::default()
            },
        )
        .unwrap();
        let img = match out {
            PipelineOutput::Raw(img) => img,
            _ => panic!("expected Raw output"),
        };
        let s = &img.surfaces[0][0];
        // Output must be tight.
        assert_eq!(s.stride, 4 * 4);
        assert_eq!(s.data.len(), 4 * 4 * 2);
        // Padding byte must not appear.
        assert!(
            !s.data.contains(&0xCC),
            "padding leaked into output: {:?}",
            s.data,
        );
        // First pixel of row 0: original (10,20,30,255) → BGRA = (30,20,10,255).
        assert_eq!(&s.data[0..4], &[30, 20, 10, 255]);
        // First pixel of row 1: original (100,110,120,255) → (120,110,100,255).
        let row1 = (4 * 4) as usize;
        assert_eq!(&s.data[row1..row1 + 4], &[120, 110, 100, 255]);
    }

    /// Encoding path: padded-stride RGBA8 → BC7 → KTX2.
    /// Just verifies the pipeline accepts padded input and produces a valid
    /// KTX2 file. Re-decoding BC7 to check pixel exactness is too brittle
    /// for an unrelated test, so we assert structural validity only.
    #[test]
    fn convert_padded_stride_to_bc7_succeeds() {
        let image = padded_rgba8_4x2();
        // 4×2 isn't 4×4-aligned, but tile_to_blocks edge-replicates so this
        // still produces 1×1 blocks (rounded up to 4×4).
        let out = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Compressed {
                    format: ktx2::Format::BC7_UNORM_BLOCK,
                    encoder: crate::encoders::Encoder::Auto,
                }),
                container: Container::ktx2(),
                quality: Quality::UltraFast,
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Encoded(bytes) => {
                assert_eq!(&bytes[0..12], b"\xabKTX 20\xbb\r\n\x1a\n");
            }
            _ => panic!("expected Encoded output"),
        }
    }

    /// Passthrough path: padded-stride RGBA8 → KTX2 (format identity, no
    /// pixel work). The output must be a valid KTX2 file containing the
    /// tightly-packed pixels — the per-row padding from the input must not
    /// appear in the level data.
    #[test]
    fn convert_padded_stride_uncompressed_passthrough_is_tight() {
        let image = padded_rgba8_4x2();
        let out = convert(
            image,
            ConvertSettings {
                container: Container::ktx2(),
                ..Default::default()
            },
        )
        .unwrap();
        let bytes = match out {
            PipelineOutput::Encoded(bytes) => bytes,
            _ => panic!("expected Encoded output"),
        };
        // Round-trip through the KTX2 decoder; each pixel must match the
        // original padded source row-by-row.
        let decoded = crate::input::ktx2::decode_ktx2_image(&bytes).unwrap();
        let s = &decoded.surfaces[0][0];
        assert_eq!(s.width, 4);
        assert_eq!(s.height, 2);
        assert_eq!(s.stride, 4 * 4); // tight on the way out
        assert!(
            !s.data.contains(&0xCC),
            "padding leaked into KTX2 level data"
        );
        // Spot-check a pixel from each row.
        assert_eq!(&s.data[0..4], &[10, 20, 30, 255]);
        assert_eq!(&s.data[16..20], &[100, 110, 120, 255]);
    }

    /// Passthrough path: padded-stride BC7 → KTX2.
    /// 8×4 pixels = 2×1 blocks per row of blocks, but with a row-of-blocks
    /// stride deliberately wider than 32 bytes (one 16-byte pad block per row).
    #[test]
    fn convert_padded_stride_compressed_passthrough_is_tight() {
        let pad = 0xCCu8;
        // 2 real BC7 blocks (32 bytes) + 1 block of padding (16 bytes) per
        // row of blocks. 8×4 has 1 row of blocks vertically (4 / 4 = 1).
        let block0 = [0x11u8; 16];
        let block1 = [0x22u8; 16];
        let mut data = Vec::new();
        data.extend_from_slice(&block0);
        data.extend_from_slice(&block1);
        data.extend_from_slice(&[pad; 16]);

        let image = Image {
            surfaces: vec![vec![Surface {
                data,
                width: 8,
                height: 4,
                depth: 1,
                stride: 2 * 16 + 16, // 2 blocks of payload + 1 block of padding
                slice_stride: 0,
                format: ktx2::Format::BC7_UNORM_BLOCK,
                color_space: ColorSpace::Linear,
                alpha: AlphaMode::Opaque,
            }]],
            kind: crate::TextureKind::Texture2D,
        };

        let out = convert(
            image,
            ConvertSettings {
                container: Container::ktx2(),
                ..Default::default()
            },
        )
        .unwrap();
        let bytes = match out {
            PipelineOutput::Encoded(bytes) => bytes,
            _ => panic!("expected Encoded output"),
        };
        // Inspect the encoded KTX2 directly: the level index must say 32
        // bytes (2 BC7 blocks, tight), not 48 (which would mean the padding
        // block was written into the file). The decoder discards trailing
        // bytes, so we have to look at the writer's output to catch this.
        let reader = ktx2::Reader::new(&bytes[..]).expect("valid KTX2");
        let levels: Vec<_> = reader.levels().collect();
        assert_eq!(levels.len(), 1);
        assert_eq!(
            levels[0].data.len(),
            2 * 16,
            "level payload must be tight (2 BC7 blocks), not include the padding block",
        );
        assert!(
            !levels[0].data.contains(&pad),
            "BC7 padding leaked into KTX2 level data",
        );

        let decoded = crate::input::ktx2::decode_ktx2_image(&bytes).unwrap();
        let s = &decoded.surfaces[0][0];
        assert_eq!(s.format, ktx2::Format::BC7_UNORM_BLOCK);
        let mut expected = Vec::new();
        expected.extend_from_slice(&block0);
        expected.extend_from_slice(&block1);
        assert_eq!(s.data, expected);
    }

    /// Passthrough path: 3D RGBA8 with both row and slice padding → KTX2.
    /// Each Z slice is `4×2 RGBA8 + 8 bytes row pad + 8 bytes slice pad`,
    /// none of which may surface in the encoded file.
    #[test]
    fn convert_padded_slice_stride_3d_passthrough_is_tight() {
        let pad = 0xCCu8;
        let row_pad = 8;
        let slice_pad = 8;
        let stride = 4 * 4 + row_pad;
        let slice_payload = stride * 2;
        let slice_stride = slice_payload + slice_pad;
        let depth = 3u32;

        let mut data = Vec::with_capacity((slice_stride * depth) as usize);
        for z in 0..depth as u8 {
            for y in 0..2u8 {
                for x in 0..4u8 {
                    data.extend_from_slice(&[z * 50 + x, y * 30, 0, 255]);
                }
                data.extend_from_slice(&[pad; 8]);
            }
            data.extend_from_slice(&[pad; 8]);
        }

        let image = Image {
            surfaces: vec![vec![Surface {
                data,
                width: 4,
                height: 2,
                depth,
                stride,
                slice_stride,
                format: ktx2::Format::R8G8B8A8_UNORM,
                color_space: ColorSpace::Linear,
                alpha: AlphaMode::Opaque,
            }]],
            kind: crate::TextureKind::Texture3D,
        };

        let out = convert(
            image,
            ConvertSettings {
                container: Container::ktx2(),
                ..Default::default()
            },
        )
        .unwrap();
        let bytes = match out {
            PipelineOutput::Encoded(bytes) => bytes,
            _ => panic!("expected Encoded output"),
        };
        let decoded = crate::input::ktx2::decode_ktx2_image(&bytes).unwrap();
        let s = &decoded.surfaces[0][0];
        assert_eq!(s.depth, depth);
        assert_eq!(s.stride, 4 * 4);
        assert_eq!(s.slice_stride, 4 * 4 * 2);
        assert!(
            !s.data.contains(&pad),
            "padding leaked into 3D KTX2 level data",
        );
        // Spot-check pixel (0,0,z) for each slice.
        for z in 0..depth as usize {
            let base = z * (4 * 4 * 2);
            assert_eq!(
                &s.data[base..base + 4],
                &[(z as u8) * 50, 0, 0, 255],
                "slice {z} pixel (0,0)",
            );
        }
    }

    #[test]
    fn convert_uint_pipeline_with_swizzle() {
        // 4 u32 values = 16 bytes.
        let mut data = Vec::new();
        for v in &[10u32, 20, 30, 40] {
            data.extend_from_slice(&v.to_le_bytes());
        }
        let image = make_image(
            data,
            1,
            1,
            ktx2::Format::R32G32B32A32_UINT,
            ColorSpace::Linear,
            AlphaMode::Opaque,
        );
        let out = convert(
            image,
            ConvertSettings {
                format: Some(TargetFormat::Uncompressed(ktx2::Format::R32G32B32A32_UINT)),
                container: Container::Raw,
                swizzle: Some(Swizzle([
                    processing::SwizzleChannel::A,
                    processing::SwizzleChannel::B,
                    processing::SwizzleChannel::G,
                    processing::SwizzleChannel::R,
                ])),
                ..Default::default()
            },
        )
        .unwrap();
        match out {
            PipelineOutput::Raw(img) => {
                let bytes = &img.surfaces[0][0].data;
                assert_eq!(u32::from_le_bytes(bytes[0..4].try_into().unwrap()), 40);
                assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 30);
                assert_eq!(u32::from_le_bytes(bytes[8..12].try_into().unwrap()), 20);
                assert_eq!(u32::from_le_bytes(bytes[12..16].try_into().unwrap()), 10);
            }
            _ => panic!("expected Raw output"),
        }
    }
}