zenbitmaps 0.1.5

PNM/PAM/PFM, BMP, farbfeld, QOI, TGA, and Radiance HDR image codec
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! # zenbitmaps
//!
//! PNM/PAM/PFM, BMP, and farbfeld image format decoder and encoder.
//!
//! Reference bitmap formats for codec testing and apples-to-apples comparisons.
//! `no_std` compatible (with `alloc`), `forbid(unsafe_code)`, panic-free.
//!
//! ## Quick Start
//!
//! ```
//! use zenbitmaps::*;
//! use enough::Unstoppable;
//!
//! // Encode pixels to PPM
//! let pixels = vec![255u8, 0, 0, 0, 255, 0]; // 2 RGB pixels
//! let encoded = encode_ppm(&pixels, 2, 1, PixelLayout::Rgb8, Unstoppable)?;
//!
//! // Decode (auto-detects PNM/BMP/farbfeld from magic bytes)
//! let decoded = decode(&encoded, Unstoppable)?;
//! assert!(decoded.is_borrowed()); // zero-copy for PPM with maxval=255
//! assert_eq!(decoded.pixels(), &pixels[..]);
//! # Ok::<(), zenbitmaps::BitmapError>(())
//! ```
//!
//! ## Format Detection
//!
//! [`detect_format()`] identifies the format from magic bytes without decoding:
//!
//! ```
//! # use zenbitmaps::*;
//! # use enough::Unstoppable;
//! # let data = encode_ppm(&[0u8; 3], 1, 1, PixelLayout::Rgb8, Unstoppable).unwrap();
//! match detect_format(&data) {
//!     Some(ImageFormat::Pnm) => { /* PGM, PPM, PAM, or PFM */ }
//!     Some(ImageFormat::Bmp) => { /* Windows bitmap */ }
//!     Some(ImageFormat::Farbfeld) => { /* farbfeld RGBA16 */ }
//!     None => { /* unknown format */ }
//!     _ => { /* future formats */ }
//! }
//! ```
//!
//! [`decode()`] uses this internally — you only need `detect_format()` if you
//! want to inspect the format before committing to a full decode.
//!
//! ## Zero-Copy Decoding
//!
//! For PNM files with maxval=255 (the common case), decoding returns a borrowed
//! slice into the input buffer — no allocation or copy needed. Formats that
//! require transformation (BMP row flip, farbfeld endian swap, etc.) allocate.
//!
//! Use `DecodeOutput::as_pixels()` for a zero-copy typed pixel view,
//! or `DecodeOutput::as_imgref()` for a zero-copy 2D view (with `imgref` feature):
//!
//! ```
//! # use zenbitmaps::*;
//! # use enough::Unstoppable;
//! # let data = encode_ppm(&[0u8; 12], 2, 2, PixelLayout::Rgb8, Unstoppable).unwrap();
//! let decoded = decode(&data, Unstoppable)?;
//! // Zero-copy reinterpret as typed pixels
//! # #[cfg(feature = "rgb")]
//! let pixels: &[RGB8] = decoded.as_pixels()?;
//! // Zero-copy 2D view (no allocation)
//! # #[cfg(feature = "imgref")]
//! let img: imgref::ImgRef<'_, RGB8> = decoded.as_imgref()?;
//! # Ok::<(), BitmapError>(())
//! ```
//!
//! ## BGRA Pipeline
//!
//! BMP files store pixels in BGR/BGRA order. Use `decode_bmp_native()` to
//! skip the BGR→RGB swizzle and work in native byte order:
//!
//! ```ignore
//! // Requires `bmp` feature
//! use zenbitmaps::*;
//! use enough::Unstoppable;
//! let decoded = decode_bmp_native(bmp_data, Unstoppable)?;
//! // decoded.layout is Bgr8, Bgra8, or Gray8
//! // Encode to PAM or farbfeld — swizzle happens automatically
//! let pam = encode_pam(decoded.pixels(), decoded.width, decoded.height,
//!                      decoded.layout, Unstoppable)?;
//! ```
//!
//! All encoders accept BGR/BGRA input and swizzle to the target format's
//! channel order automatically.
//!
//! ## Supported Formats
//!
//! ### PNM family (always available)
//! - **P5** (PGM binary) — grayscale, 8-bit and 16-bit
//! - **P6** (PPM binary) — RGB, 8-bit and 16-bit
//! - **P7** (PAM) — arbitrary channels (grayscale, RGB, RGBA), 8-bit and 16-bit
//! - **PFM** — floating-point grayscale and RGB (32-bit float per channel)
//!
//! ### Farbfeld (always available)
//! - RGBA 16-bit per channel
//! - Auto-detected by [`decode()`] via `"farbfeld"` magic
//!
//! ### BMP (`bmp` feature, opt-in)
//! - All standard bit depths: 1, 2, 4, 8, 16, 24, 32
//! - Compression: uncompressed, RLE4, RLE8, BITFIELDS
//! - Palette expansion, bottom-up/top-down, grayscale detection
//! - `BmpPermissiveness` levels: Strict, Standard, Permissive
//! - Auto-detected by [`decode()`] via `"BM"` magic
//!
//! ## Cooperative Cancellation
//!
//! Every function takes a `stop` parameter implementing [`enough::Stop`].
//! Pass [`Unstoppable`] when you don't need cancellation. For server use,
//! pass a token that checks a shutdown flag — decode/encode will bail out
//! promptly via [`BitmapError::Cancelled`].
//!
//! ## Resource Limits
//!
//! ```
//! # use zenbitmaps::*;
//! # use enough::Unstoppable;
//! let limits = Limits {
//!     max_width: Some(4096),
//!     max_height: Some(4096),
//!     max_pixels: Some(16_000_000),
//!     max_memory_bytes: Some(64 * 1024 * 1024),
//!     ..Default::default()
//! };
//! # let data = encode_ppm(&[0u8; 3], 1, 1, PixelLayout::Rgb8, Unstoppable).unwrap();
//! let decoded = decode_with_limits(&data, &limits, Unstoppable)?;
//! # Ok::<(), BitmapError>(())
//! ```
//!
//! ## Credits
//!
//! - PNM: draws from [zune-ppm](https://github.com/etemesi254/zune-image)
//!   by Caleb Etemesi (MIT/Apache-2.0/Zlib)
//! - BMP: forked from [zune-bmp](https://github.com/etemesi254/zune-image) 0.5.2
//!   by Caleb Etemesi (MIT/Apache-2.0/Zlib)
//! - Farbfeld: forked from [zune-farbfeld](https://github.com/etemesi254/zune-image) 0.5.2
//!   by Caleb Etemesi (MIT/Apache-2.0/Zlib)

#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]

extern crate alloc;

#[cfg(feature = "rgb")]
use rgb::{AsPixels as _, ComponentBytes as _};

mod decode;
mod error;
mod limits;
mod pixel;

mod pnm;

mod farbfeld;

#[cfg(feature = "hdr")]
mod hdr;

#[cfg(feature = "tga")]
mod tga;

#[cfg(feature = "qoi")]
mod qoi;

#[cfg(feature = "bmp")]
mod bmp;

#[cfg(feature = "rgb")]
mod pixel_traits;

#[cfg(feature = "zencodec")]
mod codec;

// zennode node definitions — disabled until zennode is published to crates.io
// #[cfg(feature = "zennode")]
// pub mod zennode_defs;

pub use decode::DecodeOutput;
pub use enough::{Stop, Unstoppable};
pub use error::BitmapError;
pub use limits::Limits;
pub use pixel::{ImageFormat, PixelLayout};

#[cfg(feature = "bmp")]
pub use bmp::{BmpMetadata, BmpPermissiveness};

#[cfg(feature = "rgb")]
pub use pixel_traits::{DecodePixel, EncodePixel};

#[cfg(feature = "zencodec")]
pub use codec::{
    PnmDecodeJob, PnmDecoder, PnmDecoderConfig, PnmEncodeJob, PnmEncoder, PnmEncoderConfig,
};

#[cfg(all(feature = "zencodec", feature = "bmp"))]
pub use codec::{
    BmpDecodeJob, BmpDecoder, BmpDecoderConfig, BmpEncodeJob, BmpEncoder, BmpEncoderConfig,
};

#[cfg(feature = "zencodec")]
pub use codec::{
    FarbfeldDecodeJob, FarbfeldDecoder, FarbfeldDecoderConfig, FarbfeldEncodeJob, FarbfeldEncoder,
    FarbfeldEncoderConfig,
};

#[cfg(all(feature = "zencodec", feature = "qoi"))]
pub use codec::{
    QoiDecodeJob, QoiDecoder, QoiDecoderConfig, QoiEncodeJob, QoiEncoder, QoiEncoderConfig,
};

#[cfg(all(feature = "zencodec", feature = "hdr"))]
pub use codec::{
    HdrDecodeJob, HdrDecoder, HdrDecoderConfig, HdrEncodeJob, HdrEncoder, HdrEncoderConfig,
};

#[cfg(all(feature = "zencodec", feature = "tga"))]
pub use codec::{
    TgaDecodeJob, TgaDecoder, TgaDecoderConfig, TgaEncodeJob, TgaEncoder, TgaEncoderConfig,
};

// Re-export rgb pixel types for convenience
#[cfg(feature = "rgb")]
pub use rgb::RGB as Rgb;
#[cfg(feature = "rgb")]
pub use rgb::RGBA as Rgba;
#[cfg(feature = "rgb")]
pub use rgb::alt::BGR as Bgr;
#[cfg(feature = "rgb")]
pub use rgb::alt::BGRA as Bgra;

/// 8-bit RGB pixel.
#[cfg(feature = "rgb")]
pub type RGB8 = rgb::RGB<u8>;
/// 8-bit RGBA pixel.
#[cfg(feature = "rgb")]
pub type RGBA8 = rgb::RGBA<u8>;
/// 8-bit BGR pixel.
#[cfg(feature = "rgb")]
pub type BGR8 = rgb::alt::BGR<u8>;
/// 8-bit BGRA pixel.
#[cfg(feature = "rgb")]
pub type BGRA8 = rgb::alt::BGRA<u8>;

// ── Format detection ──────────────────────────────────────────────────

/// Detect image format from magic bytes.
///
/// Returns `None` if the data doesn't match any supported format's magic bytes.
/// Recognized formats: BMP (`BM`), farbfeld (`farbfeld`), PNM (`P5`/`P6`/`P7`/`Pf`/`PF`).
///
/// ```
/// use zenbitmaps::*;
///
/// assert_eq!(detect_format(b"P6 ..."), Some(ImageFormat::Pnm));
/// assert_eq!(detect_format(b"BM..."), Some(ImageFormat::Bmp));
/// assert_eq!(detect_format(b"farbfeld..."), Some(ImageFormat::Farbfeld));
/// assert_eq!(detect_format(b"unknown"), None);
/// ```
pub fn detect_format(data: &[u8]) -> Option<ImageFormat> {
    if data.len() >= 2 && data[0] == b'B' && data[1] == b'M' {
        return Some(ImageFormat::Bmp);
    }
    if data.len() >= 8 && &data[0..8] == b"farbfeld" {
        return Some(ImageFormat::Farbfeld);
    }
    if data.len() >= 4 && &data[0..4] == b"qoif" {
        return Some(ImageFormat::Qoi);
    }
    // Radiance HDR: starts with #?RADIANCE or #?RGBE
    if data.len() >= 10 && data.starts_with(b"#?RADIANCE") {
        return Some(ImageFormat::Hdr);
    }
    if data.len() >= 6 && data.starts_with(b"#?RGBE") {
        return Some(ImageFormat::Hdr);
    }
    // PNM magic: P followed by 1-7 (ASCII/binary PBM/PGM/PPM/PAM) or f/F (PFM).
    // Matches zencodec's PNM detection. We only decode P5-P7 and PFM but
    // detect all variants so the error message is "unsupported PNM variant"
    // rather than "unrecognized format".
    if data.len() >= 2 && data[0] == b'P' {
        match data[1] {
            b'1'..=b'7' | b'f' | b'F' => return Some(ImageFormat::Pnm),
            _ => {}
        }
    }

    // TGA: no reliable magic bytes, so this MUST be last.
    // False positive rate ~1 in 5.6M on random data (header heuristic).
    // TGA v2 footer ("TRUEVISION-XFILE.\0" at EOF-26) is checked first
    // as a definitive signal when the full file is available.
    if data.len() >= 18 {
        // Check TGA v2 footer if file is large enough (26 bytes from end)
        if data.len() >= 44 {
            let footer = &data[data.len() - 18..];
            if footer == b"TRUEVISION-XFILE.\0" {
                return Some(ImageFormat::Tga);
            }
        }

        let color_map_type = data[1];
        let image_type = data[2];
        let pixel_depth = data[16];
        let descriptor = data[17];
        let width = u16::from_le_bytes([data[12], data[13]]);
        let height = u16::from_le_bytes([data[14], data[15]]);
        let alpha_bits = descriptor & 0x0F;
        // Reserved descriptor bits 6-7 must be zero
        let reserved_ok = descriptor & 0xC0 == 0;
        // byte[0] is image ID length — must be reasonable (< 128 for safety)
        let id_length_ok = data[0] < 128;

        if reserved_ok
            && id_length_ok
            && matches!(image_type, 1 | 2 | 3 | 9 | 10 | 11)
            && color_map_type <= 1
            && width > 0
            && height > 0
        {
            // Validate pixel_depth per image type
            let depth_ok = match image_type {
                1 | 9 => pixel_depth == 8 && color_map_type == 1,
                2 | 10 => matches!(pixel_depth, 15 | 16 | 24 | 32),
                3 | 11 => pixel_depth == 8,
                _ => false,
            };
            // Alpha bits should not exceed pixel depth
            let alpha_ok = match pixel_depth {
                32 => alpha_bits <= 8,
                16 => alpha_bits <= 1,
                _ => alpha_bits == 0,
            };
            // For color-mapped images, validate color map depth
            let cmap_ok = if color_map_type == 1 {
                let cmap_depth = data[7];
                matches!(cmap_depth, 15 | 16 | 24 | 32)
            } else {
                true
            };
            if depth_ok && alpha_ok && cmap_ok {
                return Some(ImageFormat::Tga);
            }
        }
    }

    None
}

// ── Auto-detect decode (PNM, BMP, farbfeld from magic bytes) ─────────

/// Decode any supported format (auto-detected from magic bytes).
///
/// Detects PNM (P5/P6/P7/PFM), farbfeld, and BMP (if the `bmp` feature is enabled).
/// Zero-copy when possible — PNM with maxval=255 returns a borrowed slice.
pub fn decode(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    decode_dispatch(data, None, &stop)
}

/// Decode any supported format with resource limits.
pub fn decode_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    decode_dispatch(data, Some(limits), &stop)
}

fn decode_dispatch<'a>(
    data: &'a [u8],
    limits: Option<&Limits>,
    stop: &dyn enough::Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    match detect_format(data) {
        Some(ImageFormat::Bmp) => {
            #[cfg(feature = "bmp")]
            return bmp::decode(data, limits, stop);
            #[cfg(not(feature = "bmp"))]
            return Err(BitmapError::UnsupportedVariant(
                "BMP support requires the 'bmp' feature".into(),
            ));
        }
        Some(ImageFormat::Farbfeld) => farbfeld::decode(data, limits, stop),
        Some(ImageFormat::Qoi) => {
            #[cfg(feature = "qoi")]
            return qoi::decode(data, limits, stop);
            #[cfg(not(feature = "qoi"))]
            return Err(BitmapError::UnsupportedVariant(
                "QOI support requires the 'qoi' feature".into(),
            ));
        }
        Some(ImageFormat::Pnm) => pnm::decode(data, limits, stop),
        Some(ImageFormat::Hdr) => {
            #[cfg(feature = "hdr")]
            return hdr::decode(data, limits, stop);
            #[cfg(not(feature = "hdr"))]
            return Err(BitmapError::UnsupportedVariant(
                "HDR support requires the 'hdr' feature".into(),
            ));
        }
        Some(ImageFormat::Tga) => {
            #[cfg(feature = "tga")]
            return tga::decode(data, limits, stop);
            #[cfg(not(feature = "tga"))]
            return Err(BitmapError::UnsupportedVariant(
                "TGA support requires the 'tga' feature".into(),
            ));
        }
        None => Err(BitmapError::UnrecognizedFormat),
    }
}

// ── PNM encode ───────────────────────────────────────────────────────

/// Encode pixels as PPM (P6, binary RGB).
pub fn encode_ppm(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    pnm::encode(pixels, width, height, layout, pnm::PnmFormat::Ppm, &stop)
}

/// Encode pixels as PGM (P5, binary grayscale).
pub fn encode_pgm(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    pnm::encode(pixels, width, height, layout, pnm::PnmFormat::Pgm, &stop)
}

/// Encode pixels as PAM (P7, arbitrary channels).
pub fn encode_pam(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    pnm::encode(pixels, width, height, layout, pnm::PnmFormat::Pam, &stop)
}

/// Encode pixels as PFM (floating-point).
pub fn encode_pfm(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    pnm::encode(pixels, width, height, layout, pnm::PnmFormat::Pfm, &stop)
}

// ── Farbfeld encode/decode ────────────────────────────────────────────

/// Decode farbfeld data to pixels.
///
/// Also auto-detected by [`decode()`] via the `"farbfeld"` magic bytes.
/// Output layout is always [`PixelLayout::Rgba16`].
pub fn decode_farbfeld(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    farbfeld::decode(data, None, &stop)
}

/// Decode farbfeld with resource limits.
pub fn decode_farbfeld_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    farbfeld::decode(data, Some(limits), &stop)
}

/// Encode pixels as farbfeld.
///
/// Accepts `Rgba16` (direct), `Rgba8` (expand via val*257),
/// `Rgb8` (expand + alpha=65535), or `Gray8` (expand to RGBA).
pub fn encode_farbfeld(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    farbfeld::encode(pixels, width, height, layout, &stop)
}

// ── TGA encode/decode ────────────────────────────────────────────────

/// Decode TGA data to pixels.
#[cfg(feature = "tga")]
///
/// Also auto-detected by [`decode()`] via header heuristics (TGA has no magic bytes).
/// Output layout is [`PixelLayout::Rgb8`], [`PixelLayout::Rgba8`], or [`PixelLayout::Gray8`].
pub fn decode_tga(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    tga::decode(data, None, &stop)
}

/// Decode TGA with resource limits.
#[cfg(feature = "tga")]
pub fn decode_tga_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    tga::decode(data, Some(limits), &stop)
}

/// Encode pixels as TGA.
///
/// Accepts `Gray8`, `Rgb8`, `Rgba8`, `Bgr8`, `Bgra8` input layouts.
/// Writes uncompressed TGA with bottom-left origin.
#[cfg(feature = "tga")]
pub fn encode_tga(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    tga::encode(pixels, width, height, layout, &stop)
}

// ── HDR encode/decode ────────────────────────────────────────────────

/// Decode Radiance HDR data to pixels.
///
/// Also auto-detected by [`decode()`] via `#?RADIANCE` / `#?RGBE` magic.
/// Output layout is always [`PixelLayout::RgbF32`].
#[cfg(feature = "hdr")]
pub fn decode_hdr(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    hdr::decode(data, None, &stop)
}

/// Decode Radiance HDR with resource limits.
#[cfg(feature = "hdr")]
pub fn decode_hdr_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    hdr::decode(data, Some(limits), &stop)
}

/// Encode pixels as Radiance HDR (RGBE with new-style RLE).
///
/// Accepts `RgbF32` (3×f32) or `Rgb8` (converted via /255.0).
#[cfg(feature = "hdr")]
pub fn encode_hdr(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    hdr::encode(pixels, width, height, layout, &stop)
}

// ── QOI encode/decode ────────────────────────────────────────────────

/// Decode QOI data to pixels.
///
/// Also auto-detected by [`decode()`] via the `"qoif"` magic bytes.
/// Output layout is [`PixelLayout::Rgb8`] or [`PixelLayout::Rgba8`].
#[cfg(feature = "qoi")]
pub fn decode_qoi(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    qoi::decode(data, None, &stop)
}

/// Decode QOI with resource limits.
#[cfg(feature = "qoi")]
pub fn decode_qoi_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    qoi::decode(data, Some(limits), &stop)
}

/// Encode pixels as QOI.
///
/// Accepts `Rgb8`, `Rgba8`, `Bgr8`, `Bgra8` input layouts.
#[cfg(feature = "qoi")]
pub fn encode_qoi(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    qoi::encode(pixels, width, height, layout, &stop)
}

// ── BMP (auto-detected, or explicit) ─────────────────────────────────

/// Probe BMP metadata without decoding pixels.
///
/// Returns resolution (DPI), pixel layout, dimensions, and color table
/// information from the BMP header. This is much faster than a full decode
/// when you only need metadata.
#[cfg(feature = "bmp")]
pub fn probe_bmp(data: &[u8]) -> Result<BmpMetadata, BitmapError> {
    bmp::probe(data)
}

/// Decode BMP data to pixels.
///
/// Also auto-detected by [`decode()`] via the `"BM"` magic bytes.
/// BMP always allocates (BGR→RGB conversion + row flip).
#[cfg(feature = "bmp")]
pub fn decode_bmp(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    bmp::decode(data, None, &stop)
}

/// Decode BMP with resource limits.
#[cfg(feature = "bmp")]
pub fn decode_bmp_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    bmp::decode(data, Some(limits), &stop)
}

/// Decode BMP data in native byte order (BGR for 24-bit, BGRA for 32-bit).
///
/// Unlike [`decode_bmp`], this skips the BGR→RGB channel swizzle,
/// returning pixels in the BMP-native byte order. The output layout will be
/// [`PixelLayout::Bgr8`], [`PixelLayout::Bgra8`], or [`PixelLayout::Gray8`].
#[cfg(feature = "bmp")]
pub fn decode_bmp_native(data: &[u8], stop: impl Stop) -> Result<DecodeOutput<'_>, BitmapError> {
    bmp::decode_native(data, None, &stop)
}

/// Decode BMP in native byte order with resource limits.
#[cfg(feature = "bmp")]
pub fn decode_bmp_native_with_limits<'a>(
    data: &'a [u8],
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    bmp::decode_native(data, Some(limits), &stop)
}

/// Decode BMP with a specific permissiveness level.
///
/// - [`BmpPermissiveness::Strict`]: reject any spec violation
/// - [`BmpPermissiveness::Standard`]: default, reject corrupted files but
///   accept benign metadata errors (bad DPI, wrong file size field)
/// - [`BmpPermissiveness::Permissive`]: best-effort recovery (zero-pad
///   truncated files, clamp RLE overflows, accept unknown compression)
#[cfg(feature = "bmp")]
pub fn decode_bmp_permissive(
    data: &[u8],
    permissiveness: BmpPermissiveness,
    stop: impl Stop,
) -> Result<DecodeOutput<'_>, BitmapError> {
    bmp::decode_with_permissiveness(data, None, permissiveness, &stop)
}

/// Decode BMP with a specific permissiveness level and resource limits.
#[cfg(feature = "bmp")]
pub fn decode_bmp_permissive_with_limits<'a>(
    data: &'a [u8],
    permissiveness: BmpPermissiveness,
    limits: &'a Limits,
    stop: impl Stop,
) -> Result<DecodeOutput<'a>, BitmapError> {
    bmp::decode_with_permissiveness(data, Some(limits), permissiveness, &stop)
}

/// Encode pixels as 24-bit BMP (RGB, no alpha).
#[cfg(feature = "bmp")]
pub fn encode_bmp(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    bmp::encode(pixels, width, height, layout, false, &stop)
}

/// Encode pixels as 32-bit BMP (RGBA with alpha).
#[cfg(feature = "bmp")]
pub fn encode_bmp_rgba(
    pixels: &[u8],
    width: u32,
    height: u32,
    layout: PixelLayout,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError> {
    bmp::encode(pixels, width, height, layout, true, &stop)
}

// ── Typed pixel API (rgb feature) ────────────────────────────────────

/// Decode any PNM format to typed pixels.
#[cfg(feature = "rgb")]
pub fn decode_pixels<P: DecodePixel>(
    data: &[u8],
    stop: impl Stop,
) -> Result<(alloc::vec::Vec<P>, u32, u32), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode(data, stop)?;
    decoded_to_pixels(decoded)
}

/// Decode any PNM format to typed pixels with resource limits.
#[cfg(feature = "rgb")]
pub fn decode_pixels_with_limits<P: DecodePixel>(
    data: &[u8],
    limits: &Limits,
    stop: impl Stop,
) -> Result<(alloc::vec::Vec<P>, u32, u32), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode_with_limits(data, limits, stop)?;
    decoded_to_pixels(decoded)
}

/// Decode BMP to typed pixels.
#[cfg(all(feature = "bmp", feature = "rgb"))]
pub fn decode_bmp_pixels<P: DecodePixel>(
    data: &[u8],
    stop: impl Stop,
) -> Result<(alloc::vec::Vec<P>, u32, u32), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode_bmp(data, stop)?;
    decoded_to_pixels(decoded)
}

/// Decode BMP to typed pixels with resource limits.
#[cfg(all(feature = "bmp", feature = "rgb"))]
pub fn decode_bmp_pixels_with_limits<P: DecodePixel>(
    data: &[u8],
    limits: &Limits,
    stop: impl Stop,
) -> Result<(alloc::vec::Vec<P>, u32, u32), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode_bmp_with_limits(data, limits, stop)?;
    decoded_to_pixels(decoded)
}

#[cfg(feature = "rgb")]
fn decoded_to_pixels<P: DecodePixel>(
    decoded: DecodeOutput<'_>,
) -> Result<(alloc::vec::Vec<P>, u32, u32), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    if !decoded.layout.is_memory_compatible(P::layout()) {
        return Err(BitmapError::LayoutMismatch {
            expected: P::layout(),
            actual: decoded.layout,
        });
    }
    let pixels: &[P] = decoded.pixels().as_pixels();
    Ok((pixels.to_vec(), decoded.width, decoded.height))
}

// ── Typed pixel encode (rgb feature) ─────────────────────────────────

/// Encode typed pixels as PPM (P6).
#[cfg(feature = "rgb")]
pub fn encode_ppm_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_ppm(pixels.as_bytes(), width, height, P::layout(), stop)
}

/// Encode typed pixels as PGM (P5).
#[cfg(feature = "rgb")]
pub fn encode_pgm_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_pgm(pixels.as_bytes(), width, height, P::layout(), stop)
}

/// Encode typed pixels as PAM (P7).
#[cfg(feature = "rgb")]
pub fn encode_pam_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_pam(pixels.as_bytes(), width, height, P::layout(), stop)
}

/// Encode typed pixels as PFM (floating-point).
#[cfg(feature = "rgb")]
pub fn encode_pfm_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_pfm(pixels.as_bytes(), width, height, P::layout(), stop)
}

/// Encode typed pixels as 24-bit BMP.
#[cfg(all(feature = "bmp", feature = "rgb"))]
pub fn encode_bmp_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_bmp(pixels.as_bytes(), width, height, P::layout(), stop)
}

/// Encode typed pixels as 32-bit BMP (RGBA).
#[cfg(all(feature = "bmp", feature = "rgb"))]
pub fn encode_bmp_rgba_pixels<P: EncodePixel>(
    pixels: &[P],
    width: u32,
    height: u32,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    encode_bmp_rgba(pixels.as_bytes(), width, height, P::layout(), stop)
}

// ── ImgVec/ImgRef API (imgref feature) ───────────────────────────────

/// Decode any PNM format to an [`imgref::ImgVec`].
#[cfg(feature = "imgref")]
pub fn decode_img<P: DecodePixel>(
    data: &[u8],
    stop: impl Stop,
) -> Result<imgref::ImgVec<P>, BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let (pixels, w, h) = decode_pixels::<P>(data, stop)?;
    Ok(imgref::ImgVec::new(pixels, w as usize, h as usize))
}

/// Decode any PNM format to an [`imgref::ImgVec`] with resource limits.
#[cfg(feature = "imgref")]
pub fn decode_img_with_limits<P: DecodePixel>(
    data: &[u8],
    limits: &Limits,
    stop: impl Stop,
) -> Result<imgref::ImgVec<P>, BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let (pixels, w, h) = decode_pixels_with_limits::<P>(data, limits, stop)?;
    Ok(imgref::ImgVec::new(pixels, w as usize, h as usize))
}

/// Decode BMP to an [`imgref::ImgVec`].
#[cfg(all(feature = "bmp", feature = "imgref"))]
pub fn decode_bmp_img<P: DecodePixel>(
    data: &[u8],
    stop: impl Stop,
) -> Result<imgref::ImgVec<P>, BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let (pixels, w, h) = decode_bmp_pixels::<P>(data, stop)?;
    Ok(imgref::ImgVec::new(pixels, w as usize, h as usize))
}

/// Decode BMP to an [`imgref::ImgVec`] with resource limits.
#[cfg(all(feature = "bmp", feature = "imgref"))]
pub fn decode_bmp_img_with_limits<P: DecodePixel>(
    data: &[u8],
    limits: &Limits,
    stop: impl Stop,
) -> Result<imgref::ImgVec<P>, BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let (pixels, w, h) = decode_bmp_pixels_with_limits::<P>(data, limits, stop)?;
    Ok(imgref::ImgVec::new(pixels, w as usize, h as usize))
}

/// Decode PNM into an existing [`imgref::ImgRefMut`] buffer.
///
/// The output buffer dimensions must match the decoded image exactly.
/// Handles arbitrary stride (row-by-row copy).
#[cfg(feature = "imgref")]
pub fn decode_into<P: DecodePixel>(
    data: &[u8],
    output: imgref::ImgRefMut<'_, P>,
    stop: impl Stop,
) -> Result<(), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode(data, stop)?;
    copy_decoded_into(decoded, output)
}

/// Decode BMP into an existing [`imgref::ImgRefMut`] buffer.
#[cfg(all(feature = "bmp", feature = "imgref"))]
pub fn decode_bmp_into<P: DecodePixel>(
    data: &[u8],
    output: imgref::ImgRefMut<'_, P>,
    stop: impl Stop,
) -> Result<(), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    let decoded = decode_bmp(data, stop)?;
    copy_decoded_into(decoded, output)
}

#[cfg(feature = "imgref")]
fn copy_decoded_into<P: DecodePixel>(
    decoded: DecodeOutput<'_>,
    mut output: imgref::ImgRefMut<'_, P>,
) -> Result<(), BitmapError>
where
    [u8]: rgb::AsPixels<P>,
{
    if !decoded.layout.is_memory_compatible(P::layout()) {
        return Err(BitmapError::LayoutMismatch {
            expected: P::layout(),
            actual: decoded.layout,
        });
    }
    let out_w = output.width();
    let out_h = output.height();
    if decoded.width as usize != out_w || decoded.height as usize != out_h {
        return Err(BitmapError::InvalidData(alloc::format!(
            "dimension mismatch: decoded {}x{}, output buffer {}x{}",
            decoded.width,
            decoded.height,
            out_w,
            out_h
        )));
    }
    let src_pixels: &[P] = decoded.pixels().as_pixels();
    for (src_row, dst_row) in src_pixels.chunks_exact(out_w).zip(output.rows_mut()) {
        <[P]>::copy_from_slice(dst_row, src_row);
    }
    Ok(())
}

/// Encode an [`imgref::ImgRef`] as PPM (P6).
///
/// Handles arbitrary stride by copying row-by-row when needed.
#[cfg(feature = "imgref")]
pub fn encode_ppm_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_ppm(&bytes, w, h, P::layout(), stop)
}

/// Encode an [`imgref::ImgRef`] as PGM (P5).
#[cfg(feature = "imgref")]
pub fn encode_pgm_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_pgm(&bytes, w, h, P::layout(), stop)
}

/// Encode an [`imgref::ImgRef`] as PAM (P7).
#[cfg(feature = "imgref")]
pub fn encode_pam_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_pam(&bytes, w, h, P::layout(), stop)
}

/// Encode an [`imgref::ImgRef`] as PFM.
#[cfg(feature = "imgref")]
pub fn encode_pfm_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_pfm(&bytes, w, h, P::layout(), stop)
}

/// Encode an [`imgref::ImgRef`] as 24-bit BMP.
#[cfg(all(feature = "bmp", feature = "imgref"))]
pub fn encode_bmp_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_bmp(&bytes, w, h, P::layout(), stop)
}

/// Encode an [`imgref::ImgRef`] as 32-bit BMP (RGBA).
#[cfg(all(feature = "bmp", feature = "imgref"))]
pub fn encode_bmp_rgba_img<P: EncodePixel>(
    img: imgref::ImgRef<'_, P>,
    stop: impl Stop,
) -> Result<alloc::vec::Vec<u8>, BitmapError>
where
    [P]: rgb::ComponentBytes<u8>,
{
    let (bytes, w, h) = collect_img_bytes(img);
    encode_bmp_rgba(&bytes, w, h, P::layout(), stop)
}

/// Collect image rows into contiguous bytes, handling arbitrary stride.
#[cfg(feature = "imgref")]
fn collect_img_bytes<P: EncodePixel>(img: imgref::ImgRef<'_, P>) -> (alloc::vec::Vec<u8>, u32, u32)
where
    [P]: rgb::ComponentBytes<u8>,
{
    let w = img.width();
    let h = img.height();
    if img.stride() == w {
        // Contiguous — single memcpy, no intermediate Vec<P>
        let pixels = &img.buf()[..w * h];
        (pixels.as_bytes().to_vec(), w as u32, h as u32)
    } else {
        // Strided — collect row-by-row directly into bytes
        let bpp = core::mem::size_of::<P>();
        let mut bytes = alloc::vec::Vec::with_capacity(w * h * bpp);
        for row in img.rows() {
            bytes.extend_from_slice(row.as_bytes());
        }
        (bytes, w as u32, h as u32)
    }
}