zenpixels 0.5 Type Atlas & Visual Drilldown

Start with a struct or enum name below to see how it fits into the zenpixels / zenpixels-convert type hierarchy, what fields and variants it contains, the most common real-world values, and how to construct and use it.


§Quick Type Index (Start by Name)

§1. Format & Color Description (zenpixels)

TypeKindOne-line roleJump to
PixelFormatstructFull pixel description: layout: SampleLayout + color: ColorSpace (can own ICC Arc<[u8]>)Drilldown 1
FormatCow<'a>enumZero-alloc Borrowed(&'a PixelFormat) or Owned(Arc<PixelFormat>) stored inside viewsDrilldown 1
SampleLayoutstruct (Copy)Physical byte shape: sample: SampleType, order: ChannelOrder, packing: BitPackingDrilldown 1
SampleTypeenum (Copy)Scalar element storage: U8, U16, U32, U64, I8..I64, F16, F32, F64Drilldown 1
ChannelOrderenum (Copy)Interleaved channel sequence: Rgb, Rgba, Bgr, Bgra, Rgbx, Bgrx, Gray, GrayAlpha, Cmyk*, Oklab*, Xyz*, Perceptual*, Generic(u8)Drilldown 1
BitPackingenum (Copy)Coded bit placement inside storage words: Full, Lsb { bits }, Msb { bits }, Shifted, Bitfields (U10_LSB, P010, RGB565, RGB10A2)Drilldown 1
ColorSpaceenumAlgebraic color interpretation: Rgb, Gray, Oklab, Xyz, Perceptual, Cmyk, Icc, UntaggedDrilldown 1
Primaries / CustomPrimariesenum / structRGB chromaticity primaries (Bt709, DisplayP3, Bt2020, AdobeRgb, DciP3, Custom(...), etc.)Drilldown 1
Transfer / Gamma / HlgModeenum / struct / enumElectro-optical curve: Srgb, Linear, Pq, Hlg(Scene | Display(HlgRendering)), Bt709, Gamma22, Gamma(Gamma), etc.Drilldown 1
AlphaModeenum (Copy)Alpha channel meaning: None, Opaque, Straight, Premultiplied, UndefinedDrilldown 1
SignalRangeenum (Copy)Integer code swing: Full (0..=255 / 0..=65535) vs Narrow (studio 16..=235)Drilldown 1
RenderingIntentenum (Copy)ICC rendering intent: Perceptual, RelativeColorimetric, Saturation, AbsoluteColorimetricDrilldown 1
WhitePoint / Chromaticityenum / structCIE 1931 (x, y) chromaticity (D65, D50, Dci, C, E, Custom(...))Drilldown 1

§2. Packed Image Carriers & Storage (zenpixels)

TypeKindOne-line roleJump to
PixelBufstructOwned, alignment-exact, stride-preserving 2D image buffer + metadata (Orientation, HdrMetadata, ColorOrigin, SampleClaims)Drilldown 2
PixelView<'a>structZero-copy borrowed strided 2D image or rectangular crop (immutable)Drilldown 2
PixelViewMut<'a>structZero-copy borrowed mutable strided 2D image or rectangular cropDrilldown 2
PixelRectstruct (Copy)Rectangular crop region { x, y, width, height } in pixels passed to every crop* / into_crop methodDrilldown 2
PixelCow<'a>enumBorrowed(PixelView<'a>) or Owned(PixelBuf) (used by EncodeReady)Drilldown 2
PixelStorageenumOwned backing memory behind PixelBuf/PlaneBuf (U8..F64, F16, Aligned64, External, ExternalMut)Drilldown 2
PixelBufPartsstructDetached storage, geometry, and descriptive metadata of PixelBuf for into_parts / from_parts (drops cached claims)Drilldown 2
BandedBuf / BandSizing / BandRowLocation / BandMutstruct / enumGigapixel-safe image split into compact (~64 B/band) horizontal bands with shared metadata and per-band SampleClaims (BandSizing::{MaxBandBytes, RowsPerBand}, band_views, mutate_band_with_claims, with_bands_mut)Drilldown 2
InPlaceTransformInput / Output / Decisionstruct / enumNamed input, output, and decision (Unchanged / Updated) types for PixelBuf::transform_in_place closureDrilldown 2
PixelSource / PixelSinktraitRow-by-row source/sink traits implemented by PixelBuf, PixelView/PixelViewMut, and BandedBufDrilldown 2
ByteStorage / ByteStorageMuttraitZero-copy external backing storage traits (Arc<[T]>, Box<[T]>, Vec<T>, custom FFI owners)Drilldown 2
RowAlign / BufFill / InteropTargetenumStride alignment (Tight, Cache64, PixelCache64, Samples(u16)), initial fill (Black, SignalWhite), and interop preflightDrilldown 2
F16Sample, Rgbx, Bgrx, GrayAlpha*structBuilt-in #[repr(C)] Pod sample and pixel element typesDrilldown 2

§3. Planar & Bit-Packed Carriers (zenpixels)

TypeKindOne-line roleJump to
PlanarBufstructOwned multi-plane image (Vec<PlaneBuf>, e.g. YCbCr 4:2:0, P010, planar RGB+A) + frame-level color/matrix/sitingDrilldown 3
PlanarView<'a> / PlanarViewMut<'a>structBorrowed multi-plane image or chroma-phase-exact crop (inline for <= 4 planes, zero alloc)Drilldown 3
PlaneBuf / PlaneView<'a> / PlaneViewMut<'a>structSingle plane (owned or borrowed) pairing PlaneFormat + (width, height, stride_bytes) + storage/bytesDrilldown 3
PlaneFormatstruct (Copy)Per-plane descriptor: role: PlaneRole, sample: SampleType, packing: BitPacking, subsampling: (NonZeroU8, NonZeroU8) (components() derived from role)Drilldown 3
PlaneRoleenum (Copy)Semantic role: Y, Cb, Cr, CbCr, CrCb, R, G, B, Alpha, Cyan, Magenta, Yellow, Key, Depth, GainMap, Matte, Thermal, Packed(PlaneComponents), Extra { id: u16, components: PlaneComponents }Drilldown 3
SampleStridestruct (Copy)Newtype SampleStride(usize) expressing a plane stride in scalar elements S (not bytes)Drilldown 3
CodePlane<'a> / CodePlaneMut<'a> / InterleavedCodeLayoutstructZero-copy reader/writer for raw N-bit integer codes (0..=1023, etc.) and interleaved component layoutDrilldown 3
SampleEncodingstruct (Copy)Integer word bit-layout for CodePlane / CodeMap: (storage: SampleType, code_bits: u8, bit_shift: u8)Drilldown 3
ChromaSitingenum (Copy)Subsampled chroma sample position relative to luma (Unknown, Center, Left, TopLeft, Top, BottomLeft, Bottom)Drilldown 3
ChromaSubsamplingenum (Copy)Chroma grid ratio: Mono, Yuv444, Yuv422, Yuv420, Yuv440, Yuv411Drilldown 3
MatrixCoefficientsstruct (Copy)Lossless 1-byte H.273 Table 4 matrix code (BT709, BT601, BT2020_NCL, IDENTITY, YCGCO, ICTCP, from_code(u8))Drilldown 3

§4. Metadata, Evidence, Orientation & Dual-Layer HDR (zenpixels)

TypeKindOne-line roleJump to
ColorOrigin / OriginKindstruct / enumFile provenance of original color chunks (Assumed, Cicp, Icc, IccAndCicp, GamaChrm), distinct from active ColorSpaceDrilldown 4
Cicp / CicpTagstruct (Copy)4-byte H.273 CICP tuple and 12/44-byte ICC.1 cicpType tag (with signed s15Fixed16 custom primaries)Drilldown 4
HdrMetadatastruct (Copy)Optional content_light_level: Option<ContentLightLevel> + mastering: Option<MasteringDisplay>Drilldown 4
Nits / DiffuseWhite / HlgRenderingstruct (Copy)Validated positive luminance units (cd/m²), SDR paper-white anchor (BT2408 = 203 nits), and HLG display OOTFDrilldown 4
SampleClaims / ExactDepth / FloatClaimsstruct (Copy)Proven or caller-asserted content invariants (all_opaque, all_grayscale, binary_alpha, exact bit-grid depth, float finiteness/range)Drilldown 4
Orientationenum (Copy)EXIF 1..=8 D4 dihedral transform (Identity, FlipH, Rotate90, Rotate180, Rotate270, FlipV, Transpose, Transverse)Drilldown 4
DualLayerHdrBuf / DualLayerHdrView<'a>structISO 21496-1 / UltraHDR base layer + gain map layer + GainMapMetadata + optional alternate ColorSpaceDrilldown 4
GainMapMetadata / GainMapChannels / GainMapComponentstruct / enum / structRational ISO 21496-1 gain-map math parameters (SignedFraction / UnsignedFraction with .numerator/.denominator)Drilldown 4

§5. Conversion Engine (zenpixels-convert)

TypeKindOne-line roleJump to
ConvertPolicystructComplete conversion rules: loss gates (DepthPolicy, AlphaPolicy, GamutPolicy, RangePolicy), luma, HDR anchors, CMS, tone mapper, SIMDDrilldown 5
ImagePlanstructCompiled reusable whole-image converter (PixelSource → PixelBuf or PixelSink)Drilldown 5
RowPlanstructCompiled streaming row-by-row converter with zero per-row heap allocation (convert_row / convert_row_at)Drilldown 5
OutputPlan / EncodeReady<'a> / OutputSignaling / ResolvedSignalingstruct / struct / enum / structEncoder adaptation plan that converts pixels and resolves matching CICP + ICC signaling atomicallyDrilldown 5
Negotiate / NegotiatedFormat / FormatCost / LossKindstruct / struct / struct / enumPicks the lowest-loss, lowest-effort encoder format from &[PixelFormat]Drilldown 5
Acceleratorsstruct (Copy)const SIMD accelerator table (SCALAR, LAYOUT, WEB_SDR, HDR, GAINMAP, OKLAB, ROW_PIPELINE, ALL)Drilldown 5
CmsBackend / CmsTransform / MoxCms / Lcmstrait / structPluggable ICC/CMYK color management backends (cms-moxcms, cms-lcms features)Drilldown 5
ColorServices / CmsBinding / CmsChoice / CmsQuotestruct / enumShared host color-management + tone-mapper bundle (Inherit / StrictNoIcc / Use(CmsBinding)) with versioned cache keys and conservative memory/stack/capability quotesDrilldown 5
ToneMapper / Bt2446A / Bt2446APipelineManaged / SoftCompresstrait / structPluggable HDR→SDR tone mapper (ITU-R BT.2446 Method A: baked Bt2446A or Bt2446APipelineManaged) and Oklab gamut soft-knee compressorDrilldown 5
GainMapApplier / GainMapLayer / GainMapApplyConfig / GainMapExtractConfig / GainMapRowExtractorstructStreaming and whole-image ISO 21496-1 / UltraHDR gain-map rendering and extraction (gainmap module)Drilldown 5
PlanarReconstructionOptions / ChromaUpsamplestruct / enumPlanar YCbCr/GBR/RGB → interleaved reconstruction settings (nearest, bilinear, siting fallback)Drilldown 3
PlanarCapturePlan / PlanarCaptureSpec / PlanarCaptureOptions / CaptureScratch / ChromaDownsamplestruct / enumExact forward packed → planar YCbCr / YCgCo / GBR / RGB / monochrome capture with phase-exact chroma downsampling and reusable O(width) scratchDrilldown 3
CompactionReport / AlphaCompactionstruct / enumContent analysis (requires_alpha, requires_chroma, requires_u16_precision) + lossless compactionDrilldown 5
LightLevelHistogram / LightLevelMethodstruct / enumHDR luminance histogram for MaxCLL / MaxFALL / peak measurementDrilldown 5
CodeMap / CodeRolestruct / enumBit-depth and bit-shift integer code remapping between SampleEncodingsDrilldown 3

§Big-Picture Architecture Map

Every packed image in zenpixels separates bytes in memory (PixelStorage / &[u8]) from what those bytes mean (PixelFormat), where the file came from (ColorOrigin), display geometry (Orientation), HDR luminance bounds (HdrMetadata), and content claims (SampleClaims).

flowchart TD
    subgraph Core["zenpixels — Interchange Types (lightweight, codecs depend on this)"]
        PB["PixelBuf (owned 2D)"]
        PV["PixelView / PixelViewMut (borrowed 2D)"]
        BB["BandedBuf (gigapixel row bands)"]
        PLB["PlanarBuf / PlanarView (multi-plane)"]
        DL["DualLayerHdrBuf / DualLayerHdrView (base + gain map)"]

        PF["PixelFormat (owned, may hold ICC Arc)"]
        SL["SampleLayout (SampleType + ChannelOrder + BitPacking)"]
        CS["ColorSpace (Rgb | Gray | Oklab | Xyz | Cmyk | Icc | ...)"]
        PS["PixelStorage (Vec | Aligned64 | External)"]
        META["Auxiliary Metadata: Orientation + HdrMetadata + ColorOrigin + SampleClaims"]
        PLF["PlaneFormat (PlaneRole + SampleType + BitPacking + subsampling)"]

        PB --> PF
        PB --> PS
        PB --> META
        PV -->|"FormatCow (0-alloc static formats::*)"| PF
        BB -->|"Vec of PixelBuf"| PB
        DL -->|"base + gain_map"| PB
        PLB -->|"PlaneBuf[]"| PLF
        PLB -->|"ColorSpace + MatrixCoefficients + ChromaSiting"| CS
        PF --> SL
        PF --> CS
    end

    subgraph Convert["zenpixels-convert — Conversion Engine (re-exports zenpixels::*)"]
        CSRV["ColorServices (CmsChoice / CmsBinding + ToneMapper)"]
        POL["ConvertPolicy (loss gates + HDR anchors + CMS + Accelerators)"]
        NEG["Negotiate (select best target format)"]
        IP["ImagePlan (whole image)"]
        RP["RowPlan (streaming row loop)"]
        OP["OutputPlan -> EncodeReady (pixels + CICP + ICC)"]
        PCP["PlanarCapturePlan (packed -> planar YCbCr/RGB)"]
        GM["gainmap::GainMapApplier / GainMapRowExtractor"]

        CSRV -->|"with_color_services()"| POL
        POL --> IP
        POL --> RP
        POL --> OP
        POL --> NEG
        POL --> PCP
        POL --> GM
    end

    PV --> IP
    PB --> IP
    BB --> IP
    PV --> OP
    PV --> PCP
    PCP -->|"capture_to_buf / execute"| PLB
    DL --> GM
    PLB -->|"reconstruct_planar_*"| PB
Rendered Mermaid diagram · Open the interactive clickable Data Structures Atlas →

§Drilldown 1: PixelFormat, FormatCow, SampleLayout, ColorSpace

§Anatomy of PixelFormat

PixelFormat (Clone, Eq, Hash — NOT Copy because ColorSpace::Icc holds Arc<[u8]>)
├── layout: SampleLayout (Copy, const)
│   ├── sample:  SampleType      ── U8 | U16 | U32 | U64 | I8..I64 | F16 | F32 | F64
│   ├── order:   ChannelOrder    ── Rgb | Rgba | Bgr | Bgra | Rgbx | Bgrx | Gray | GrayAlpha
│   │                               | Cmyk | CmykInverted | Cmyka | CmykaInverted
│   │                               | Oklab | OklabA | Xyz | XyzA | Perceptual3 | Perceptual4
│   │                               | Generic(u8)
│   └── packing: BitPacking      ── Full | Lsb { bits } | Msb { bits } | Shifted { bits, shift }
│                                   | Bitfields { bits: [u8; 4], shifts: [u8; 4] }
│                                   (const presets: U10_LSB, U12_LSB, P010, RGB565, RGB10A2)
│
└── color: ColorSpace (Clone, Eq, Hash)
    ├── Rgb        { primaries: Primaries, transfer: Transfer, range: SignalRange,
    │                alpha: AlphaMode, diffuse_white: Option<DiffuseWhite> }
    ├── Gray       { transfer: Transfer, range: SignalRange,
    │                alpha: AlphaMode, diffuse_white: Option<DiffuseWhite> }
    ├── Oklab      { alpha: AlphaMode }
    ├── Xyz        { white_point: WhitePoint, alpha: AlphaMode, diffuse_white: Option<DiffuseWhite> }
    ├── Perceptual { space: PerceptualSpace (CieLab | CieLch | Oklch | Hsl | Hsv | Jzazbz | Jzczhz),
    │                alpha: AlphaMode }
    ├── Cmyk       { inverted: bool, alpha: AlphaMode, icc: Option<Arc<[u8]>> }
    ├── Icc        { profile: Arc<[u8]>, color_channels: u8, alpha: AlphaMode, intent: RenderingIntent }
    └── Untagged   { total_channels: u8, alpha: AlphaMode }

    where:
    ├── Primaries  ── Bt709 | DisplayP3 | Bt2020 | AdobeRgb | DciP3 | Bt601 | Bt470M | Bt470Bg
    │                 | Smpte240M | GenericFilm | Xyz | Ebu3213 | Custom(CustomPrimaries) | Unknown
    ├── Transfer   ── Srgb | Linear | Pq | Hlg(HlgMode::Scene | HlgMode::Display(HlgRendering))
    │                 | Bt709 | Bt601 | Bt2020_10bit | Bt2020_12bit | Gamma22 | Gamma28
    │                 | AdobeRgb | DciCinema | Gamma(Gamma) | ... | Unknown
    ├── AlphaMode  ── None | Opaque | Straight | Premultiplied | Undefined
    └── SignalRange── Full (0..=255 / 0..=65535) | Narrow (studio 16..=235 / 4096..=60160)

§PixelFormat, FormatCow, and formats::*

Encoder capabilities use a slice of PixelFormat. A pixel view can borrow a format or share ownership through FormatCow.

flowchart LR
    PF["PixelFormat (Clone, owns optional ICC Arc)"]
    STAT["formats::RGB8_SRGB (static PixelFormat ref)"]
    COW["FormatCow (Borrowed ref | Owned Arc)"]

    STAT -->|"FormatCow::Borrowed (0 heap alloc)"| COW
    PF -->|"FormatCow::from_owned (0 alloc for presets via as_static_ref, else Arc)"| COW
Rendered Mermaid diagram · Open the interactive clickable Data Structures Atlas →
Use thisWhen
PixelFormat::RGB8_SRGB (owned const)Constructing PixelBuf or chaining .with_alpha(...) / .with_primaries(...)
&formats::RGB8_SRGB (&'static PixelFormat)Borrowing into PixelView::from_bytes / PixelView::new or passing endpoints to ImagePlan::convert / ImagePlan::build / RowPlan::build with zero heap allocation
const SUPPORTED: &[PixelFormat]Static encoder capability tables using presets and PixelFormat::new_const
FormatCow<'a>Escape hatch for PixelView::new_with_format_cow when a view must hold a dynamically built custom/ICC PixelFormat

§Most-Used PixelFormat Examples

Real-world imagePreset or constructionlayoutcolor
Web JPEG / PNG RGB8PixelFormat::RGB8_SRGB / &formats::RGB8_SRGBU8 · Rgb · FullRgb { Bt709, Srgb, Full, None, None }
Straight-alpha PNG / WebPPixelFormat::RGBA8_SRGB / &formats::RGBA8_SRGBU8 · Rgba · FullRgb { Bt709, Srgb, Full, Straight, None }
Premultiplied RGBA8 (compositing/GPU)PixelFormat::RGBA8_SRGB.with_alpha(AlphaMode::Premultiplied)U8 · Rgba · FullRgb { Bt709, Srgb, Full, Premultiplied, None }
Opaque 4-channel RGBA8 (fast 32-bit pixels)PixelFormat::RGBA8_SRGB.with_alpha(AlphaMode::Opaque)U8 · Rgba · FullRgb { Bt709, Srgb, Full, Opaque, None }
RGBX / BGRX with ignored padding bytePixelFormat::BGRX8_SRGBU8 · Bgrx · FullRgb { Bt709, Srgb, Full, Undefined, None }
Display P3 8-bitPixelFormat::RGB8_DISPLAY_P3 / &formats::RGB8_DISPLAY_P3U8 · Rgb · FullRgb { DisplayP3, Srgb, Full, None, None }
Display P3 16-bitPixelFormat::RGB16_DISPLAY_P3 / &formats::RGB16_DISPLAY_P3U16 · Rgb · FullRgb { DisplayP3, Srgb, Full, None, None }
Display P3 with straight alphaPixelFormat::RGBA8_DISPLAY_P3 / PixelFormat::RGBA16_DISPLAY_P3U8 or U16 · Rgba · FullRgb { DisplayP3, Srgb, Full, Straight, None }
Linear working-space floatPixelFormat::RGBAF32_LINEAR / &formats::RGBAF32_LINEARF32 · Rgba · FullRgb { Bt709, Linear, Full, Straight, None }
HDR10 / BT.2100 PQ 16-bitPixelFormat::RGB16_BT2100_PQU16 · Rgb · FullRgb { Bt2020, Pq, Full, None, None }
HDR BT.2100 HLG (scene vs 1000-nit display)PixelFormat::RGB16_BT2100_HLG_SCENE / RGB16_BT2100_HLG_1000U16 · Rgb · FullRgb { Bt2020, Hlg(Scene | Display(1000 nit)), ... }
Arbitrary ICC profile (e.g. Adobe RGB)PixelFormat::new(SampleLayout::RGB8, ColorSpace::Icc { profile, color_channels: 3, alpha: AlphaMode::None, intent: RenderingIntent::RelativeColorimetric })U8 · Rgb · FullIcc { profile: Arc<[u8]>, ... }
CMYK JPEG (with optional ICC)PixelFormat::cmyk8(Some(icc_arc)) or PixelFormat::cmyk8(None)U8 · Cmyk · FullCmyk { inverted: false, None, icc }
Grayscale 8-bit / linear floatPixelFormat::GRAY8_SRGB / PixelFormat::GRAYF32_LINEARU8/F32 · Gray · FullGray { Srgb / Linear, Full, None, None }

§Constructing & Validating PixelFormat

use std::sync::Arc;
use zenpixels::{
    AlphaMode, BitPacking, ChannelOrder, ColorSpace, DiffuseWhite,
    PixelFormat, Primaries, RenderingIntent, SampleLayout, SampleType, SignalRange, Transfer,
    formats,
};

// 1. Owned const preset and checked builder methods:
let p3_premul = PixelFormat::RGBA8_DISPLAY_P3.with_alpha(AlphaMode::Premultiplied);

// 2. Checked builder (returns Option<PixelFormat>; None if variant doesn't carry primaries):
assert!(PixelFormat::GRAY8_SRGB.try_with_primaries(Primaries::DisplayP3).is_none());

// 3. Explicit custom layout + ColorSpace (e.g. 10-bit narrow-range BT.2020 PQ):
let pq10_narrow = PixelFormat::new(
    SampleLayout::new(SampleType::U16, ChannelOrder::Rgb).try_with_packing(BitPacking::U10_LSB)?,
    ColorSpace::BT2100_PQ.with_range(SignalRange::Narrow).with_diffuse_white(DiffuseWhite::BT2408),
)?;

// 4. Static capability table:
const ENCODER_FORMATS: &[PixelFormat] = &[
    PixelFormat::RGB8_SRGB,
    PixelFormat::RGB8_DISPLAY_P3,
    PixelFormat::RGBA8_SRGB,
    PixelFormat::GRAY8_SRGB,
];


// 5. Static borrowed reference (zero allocation for PixelView / plans):
let static_ref: &'static PixelFormat = &formats::RGB8_SRGB;
assert_eq!(&ENCODER_FORMATS[0], static_ref);

// 6. ICC-tagged RGB8:
let icc_fmt = PixelFormat::new(
    SampleLayout::RGB8,
    ColorSpace::from_icc(
        Arc::from(icc_bytes),
        AlphaMode::None,
        RenderingIntent::RelativeColorimetric,
    )?,
)?;
assert!(matches!(icc_fmt.color(), ColorSpace::Icc { .. }));

§Drilldown 2: Packed Image Carriers (PixelBuf, PixelView, PixelViewMut, PixelStorage, BandedBuf)

§Ownership and Borrowing Relationships

flowchart LR
    EXT["External owner (Arc, Box, FFI)"] -->|"from_external / from_external_mut (0-copy)"| PB
    VEC["Vec / ImgVec"] -->|"from_bytes / from_typed / from_imgvec (0-copy)"| PB

    PB["PixelBuf (owned, CoW on external)"]
    PV["PixelView (borrowed read-only)"]
    PVM["PixelViewMut (borrowed mutable)"]
    PCOW["PixelCow (Borrowed | Owned)"]
    BB["BandedBuf (compact bands + bandwise facts)"]

    PB -->|"as_view() / crop_view() / sub_rows()"| PV
    PB -->|"try_cow_view_mut() / crop_view_mut() / sub_rows_mut()"| PVM
    PVM -->|"as_view() / into_view()"| PV
    PV -->|"to_tight_buf() (allocates)"| PB
    PV -->|"PixelCow::Borrowed"| PCOW
    PB -->|"PixelCow::Owned"| PCOW
    PB <-->|"from_buf() / into_buf()"| BB

    PB -.->|"impl"| SRC["PixelSource + PixelSink"]
    PV -.->|"impl"| SRC2["PixelSource"]
    PVM -.->|"impl"| SINK["PixelSink"]
    BB -.->|"impl"| SRC
Rendered Mermaid diagram · Open the interactive clickable Data Structures Atlas →

§Anatomy of PixelBuf and PixelStorage

Every PixelBuf can be disassembled losslessly into PixelBufParts (and reassembled with PixelBuf::from_parts / from_parts_recover):

PixelBuf  <── into_parts() / from_parts() ──>  PixelBufParts
├── storage:     PixelStorage
│   ├── U8(Vec<u8>) | U16(Vec<u16>) | U32(Vec<u32>) | U64(Vec<u64>)
│   ├── I8(Vec<i8>) | I16(Vec<i16>) | I32(Vec<i32>) | I64(Vec<i64>)
│   ├── F16(Vec<F16Sample>) | F32(Vec<f32>) | F64(Vec<f64>)
│   ├── Aligned64(AlignedSamples)           // 64-byte cache-line aligned allocation
│   ├── External(ExternalStorage)           // Read-only zero-copy (Arc<[u8]>, FFI); CoW on mutation
│   └── ExternalMut(ExternalMutStorage)     // Mutable zero-copy (Box<[T]>, custom ByteStorageMut)
├── byte_offset:  usize                      // Byte offset into storage (updated O(1) by into_crop!)
├── width:        u32                        // Active width in pixels
├── height:       u32                        // Active height in rows
├── stride_bytes: usize                      // Byte distance between consecutive row starts (>= width * bpp)
├── format:       PixelFormat                // layout: SampleLayout + color: ColorSpace
├── claims:       SampleClaims               // Proven/asserted content claims (cleared on mutable access)
├── hdr:          HdrMetadata                // Optional ContentLightLevel + MasteringDisplay
├── origin:       ColorOrigin                // Original file signaling provenance
└── orientation:  Orientation                // EXIF 1..=8 (Identity by default)

PixelView<'a>                               PixelViewMut<'a>
├── data:         &'a [u8]                  ├── data:         &'a mut [u8]
├── width:        u32                       ├── width:        u32
├── height:       u32                       ├── height:       u32
├── stride_bytes: usize                     ├── stride_bytes: usize
├── format:       FormatCow<'a>             ├── format:       FormatCow<'a>
├── claims:       SampleClaims              ├── hdr:          HdrMetadata
├── hdr:          HdrMetadata               └── orientation:  Orientation
├── origin:       Option<&'a ColorOrigin>
└── orientation:  Orientation

§Choosing a PixelBuf Constructor

If you have…UseNotes
Nothing yet — want safe black pixelsPixelBuf::new(w, h, format)Fills black; fills alpha to channel max if AlphaMode::Opaque
Nothing yet — want signal whitePixelBuf::new_signal_white(w, h, format)255/65535/1.0 (studio 235 << shift for narrow range)
Nothing yet — decoder will overwrite every bytePixelBuf::new_raw_zeroed(w, h, format)Fastest (zero-fill only); refuses AlphaMode::Opaque on alpha-bearing layouts
Custom row alignment (e.g. 64-byte SIMD)PixelBuf::new_aligned(w, h, format, RowAlign::Cache64) or new_raw_zeroed_aligned / new_with_fillRowAlign::{Tight, Cache64, PixelCache64, Samples(u16)}
Tight Vec<u8> raw bytesPixelBuf::from_bytes(bytes, w, h, format)Use from_bytes_recover to get Vec<u8> back on error
Tight Vec<P> (u8, u16, f32, [u8; 3], Rgbx, rgb::Rgb<u8>)PixelBuf::from_typed(vec, w, h, format)Checks P: TypedElement against format.layout(); use from_typed_recover to recover
Tight scalar Vec<S> (u8/u16/f32/F16Sample)PixelBuf::from_samples(vec, w, h, format)Checks S::SAMPLE_TYPE == format.layout().sample()
Tight rgb::Rgb<T> / Rgba<T> (rgb feature)PixelBuf::from_pixels_with_color(vec, w, h, ColorSpace::SRGB)Layout inferred from P::LAYOUT, so takes ColorSpace (not PixelFormat)
Arbitrary Vec<P: Pod> (unchecked cast)PixelBuf::from_pod_bytes(vec, w, h, format)Reinterprets native-endian bytes without checking P’s channel structure
External Arc<[u8]>, Box<[T]>, or FFI bufferPixelBuf::from_external(owner, w, h, stride_bytes, format) / from_external_mutZero-copy; returns Err((err, owner)) on failure; _with_byte_offset takes a leading byte offset

§Constructing, Borrowing, Cropping & Relabeling

use std::sync::Arc;
use zenpixels::{AlphaMode, ColorSpace, PixelBuf, PixelFormat, PixelRect, PixelView, formats};

// 1. Borrow raw bytes with zero heap allocation using `&formats::*`:
let raw = [255u8, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255];
let view = PixelView::from_bytes(&raw, 2, 2, &formats::RGB8_SRGB)?;
assert_eq!(view.row(1), &[0, 0, 255, 255, 255, 255]);

// 2. Adopt shared Arc<[u8]> zero-copy, crop in O(1), mutate via fallible CoW:
let shared: Arc<[u8]> = Arc::from(raw.to_vec());
let mut buf = PixelBuf::from_external(shared.clone(), 2, 2, 6, PixelFormat::RGB8_SRGB)
    .map_err(|(err, _orig)| err)?;
let crop = buf.crop_view(PixelRect::new(1, 0, 1, 2))?;
assert_eq!(crop.stride_bytes(), 6);        // Parent stride preserved; row(y) has 3 active bytes
buf.try_cow_view_mut()?.row_mut(0)[0] = 42; // CoW promotes `buf`; `shared` stays untouched

// 3. Relabel metadata without changing pixel bytes:
let p3_buf = buf.relabel_color(ColorSpace::DISPLAY_P3)?; // Same layout, new ColorSpace
let bgr_buf = p3_buf.relabel_format(PixelFormat::BGR8_SRGB)?; // Same sample/bpp, different order
let _tight = bgr_buf.into_crop(PixelRect::new(0, 0, 1, 2))?.into_tight_rows()?; // O(1) crop, then pack tight rows

§BandedBuf for Gigapixel Images

BandedBuf holds compact horizontal bands (~64 B header per band; zero per-band Arc clones or duplicated PixelFormats) sized via BandSizing::{MaxBandBytes(usize), RowsPerBand(u32)} (default BandSizing::DEFAULT). Each band tracks its own SampleClaims (updated atomically via mutate_band_with_claims or parallel Send with_bands_mut), and BandedBuf implements both PixelSource and PixelSink so ImagePlan::convert / execute_into and apply_orientation_banded process arbitrarily large images without one contiguous allocation:

use zenpixels::{BandRowLocation, BandSizing, BandedBuf, PixelFormat};

let big = BandedBuf::new(64, 64, PixelFormat::RGB8_SRGB, BandSizing::RowsPerBand(16))?;
let BandRowLocation { band_index, local_y } = big.locate_row(20).unwrap();
let _row: &[u8] = big.row(20);
let _band_view = big.band_view(band_index).unwrap();

§Drilldown 3: Planar and Bit-Packed Types

§Anatomy of PlanarBuf and PlaneFormat

PlanarBuf (owned) / PlanarView<'a> (inline <= 4 planes, 0-alloc) / PlanarViewMut<'a>
├── width, height:       u32                      // Full luma-frame dimensions in pixels
├── crop_origin:         (u32, u32)               // Luma-grid crop origin (views; preserves chroma phase)
├── color:               Option<ColorSpace>       // Primaries + transfer (+ optional range/alpha)
├── matrix_coefficients: Option<MatrixCoefficients> // 1-byte H.273 Table 4 code (BT709, BT601, BT2020_NCL, ...)
├── chroma_siting:       ChromaSiting             // Unknown | Center | Left | TopLeft | Top | BottomLeft | Bottom
├── range_override:      Option<SignalRange>      // Overrides color.range() -> read via effective_range()
├── alpha_override:      Option<AlphaMode>        // Overrides color.alpha() -> read via effective_alpha()
├── hdr:                 HdrMetadata
├── origin:              ColorOrigin (Option<&'a ColorOrigin> on PlanarView)
├── orientation:         Orientation
└── planes:              [PlaneBuf | PlaneView<'a> | PlaneViewMut<'a>] (1..=MAX_PLANES)
    ├── format: PlaneFormat (Copy, const)
    │   ├── role:        PlaneRole                // Y | Cb | Cr | CbCr | CrCb | R | G | B | Alpha | Packed(PlaneComponents) | Extra { id, components }
    │   ├── sample:      SampleType               // U8 | U16 | F32 | ...
    │   ├── packing:     BitPacking               // Full | U10_LSB | U12_LSB | P010 | ...
    │   └── subsampling: (NonZeroU8, NonZeroU8)   // (hx, vy): (1,1)=4:4:4, (2,1)=4:2:2, (2,2)=4:2:0 (components() derived from role)
    ├── width, height:   u32                      // THIS plane's element dimensions (post-subsampling!)
    ├── stride_bytes:    usize                    // Row stride in BYTES
    └── storage / data:  PixelStorage / &'a [u8] / &'a mut [u8]

§Most-Used Planar Examples

FormatPlanes (PlaneFormat)Frame metadata
8-bit 4:2:0 YCbCr (JPEG / AV1 I420)Y (U8, 1×1), Cb (U8, 2×2), Cr (U8, 2×2)ColorSpace::SRGB, MatrixCoefficients::BT601 (JPEG) or BT709 (AV1), ChromaSiting::Center or Left
10-bit 4:2:0 LSB (AV1 / HEVC)Y (U16, U10_LSB, 1×1), Cb (U16, U10_LSB, 2×2), Cr (U16, U10_LSB, 2×2)ColorSpace::BT2100_PQ, MatrixCoefficients::BT2020_NCL, SignalRange::Narrow, ChromaSiting::TopLeft
P010 semi-planar (hardware video)Y (U16, P010, 1×1), CbCr (U16, components=2, P010, 2×2)ColorSpace::BT2100_PQ, MatrixCoefficients::BT2020_NCL, SignalRange::Narrow
Planar F32 RGB + Alpha (EXR / JXL)R (F32), G (F32), B (F32), Alpha (F32)ColorSpace::LINEAR_SRGB_ALPHA

§Plane Stride Rules (Bytes vs Samples)

Constructor on PlaneView / PlaneViewMut / PlaneBufArgsStride unit
from_samples(samples, width, height, plane_format)4 argsTight automatic (width * components * size_of::<S>())
from_samples_strided(samples, width, height, SampleStride(n), plane_format)5 argsScalar elements S (wrapped in SampleStride so bytes cannot be confused with samples)
new(bytes, width, height, stride_bytes, plane_format)5 argsBytes (stride_bytes() always returns bytes)

§Constructing and Reconstructing Planar Images

use zenpixels_convert::{
    BitPacking, ChromaSiting, ColorSpace, MatrixCoefficients, PixelBuf, PixelFormat,
    PlanarReconstructionOptions, PlanarView, PlaneFormat, PlaneRole, PlaneView, SampleLayout,
    SampleStride, SampleType, SignalRange, reconstruct_planar_into, reconstruct_planar_to_buf,
};

let y_fmt = PlaneFormat::new(PlaneRole::Y, SampleType::U16).try_with_packing(BitPacking::U10_LSB)?;
let cb_fmt = PlaneFormat::new(PlaneRole::Cb, SampleType::U16)
    .try_with_packing(BitPacking::U10_LSB)?
    .with_subsampling(2, 2);
let cr_fmt = PlaneFormat::new(PlaneRole::Cr, SampleType::U16)
    .try_with_packing(BitPacking::U10_LSB)?
    .with_subsampling(2, 2);

// Tight typed samples (or `from_samples_strided(..., SampleStride(padded_samples), fmt)`):
let py = PlaneView::from_samples(&y_u16, 4, 4, y_fmt)?;
let pcb = PlaneView::from_samples(&cb_u16, 2, 2, cb_fmt)?;
let pcr = PlaneView::from_samples(&cr_u16, 2, 2, cr_fmt)?;

let planar = PlanarView::new(4, 4, &[py, pcb, pcr])?
    .with_color(ColorSpace::SRGB)
    .with_matrix_coefficients(MatrixCoefficients::BT709)
    .with_range_override(SignalRange::Narrow)
    .with_chroma_siting(ChromaSiting::Left);

// Option A: allocate interleaved RGBA8 buffer:
let rgba = reconstruct_planar_to_buf(
    &planar,
    SampleLayout::RGBA8,
    &PlanarReconstructionOptions::bilinear(),
)?;

// Option B: zero-alloc into pre-allocated destination (src, dst, options):
let mut dst = PixelBuf::new(4, 4, PixelFormat::BGRA8_SRGB)?;
reconstruct_planar_into(
    &planar,
    &mut dst.as_view_mut(),
    &PlanarReconstructionOptions::bilinear(),
)?;

§Forward Packed-to-Planar Capture (PlanarCapturePlan)

For the reverse direction — encoding packed RGB/RGBA/Gray pixels into subsampled YCbCr, YCgCo, GBR, planar RGB, or monochrome planes (U8, U16 8/10/12/16-bit including U10_LSB / P010, U32, or F32) — compile a reusable PlanarCapturePlan from a PlanarCaptureSpec and execute with reusable O(width) CaptureScratch:

PlanarCaptureSpec (coded_extent, visible_rect, planes: Box<[PlaneFormat]>, chroma_siting, signal: Cicp, alpha, diffuse_white)
  + PlanarCaptureOptions (downsample: ChromaDownsample::{SitingAware | BoxAverage | Nearest}, unknown_siting_fallback)
  + ConvertPolicy (same color/transfer/HDR/alpha/CMS contract as RowPlan!)
  ──> PlanarCapturePlan::build / build_with_options (reusable, Send + Sync)
        ├── execute(src_view, &mut dst_planar_mut, &mut CaptureScratch)  // 0-heap capture when borrowing &mut [f64]
        └── capture_to_buf(src_view, &mut CaptureScratch) -> PlanarBuf   // allocates destination PlanarBuf
use zenpixels_convert::{
    CaptureScratch, ChromaDownsample, ChromaSiting, Cicp, ConvertPolicy, PixelBuf, PixelFormat,
    PlanarCaptureOptions, PlanarCapturePlan, PlanarCaptureSpec, PlaneFormat, PlaneRole,
    SampleType, formats,
};

let src = PixelBuf::new_signal_white(4, 4, PixelFormat::RGB8_SRGB)?;
let planes = [
    PlaneFormat::new(PlaneRole::Y, SampleType::U8),
    PlaneFormat::new(PlaneRole::Cb, SampleType::U8).with_subsampling(2, 2),
    PlaneFormat::new(PlaneRole::Cr, SampleType::U8).with_subsampling(2, 2),
];
let spec = PlanarCaptureSpec::full_frame(4, 4, planes, ChromaSiting::Center, Cicp::new(1, 13, 1, false));
let plan = PlanarCapturePlan::build_with_options(
    &formats::RGB8_SRGB,
    spec,
    &ConvertPolicy::permissive(),
    PlanarCaptureOptions::siting_aware().with_downsample(ChromaDownsample::SitingAware),
    None,
)?;

// Reuse scratch across frames (or borrow a caller slice via CaptureScratch::from_f64_slice):
let mut scratch = CaptureScratch::with_capacity_f64s(plan.required_scratch_f64s())?;
let yuv420 = plan.capture_to_buf(src.as_view(), &mut scratch)?;
assert_eq!(yuv420.planes().len(), 3);

§CodePlane and SampleEncoding

When you want raw integer codes (e.g. 10-bit 0..=1023 from U10_LSB or P010) without color math:

use zenpixels_convert::{
    BitPacking, CodeMap, CodeRole, PlaneFormat, PlaneRole, PlaneView, SampleEncoding, SampleType,
    SignalRange,
};

// Borrow component 0 directly from a PlaneView:
let code_plane = py.as_code_plane(0)?;
let sample_code: Option<u16> = code_plane.code(0, 0);

// Map individual N-bit codes between encodings (e.g. 10-bit LSB -> 16-bit full):
let enc10 = SampleEncoding::new(SampleType::U16, 10, 0)?;
let enc16 = SampleEncoding::new(SampleType::U16, 16, 0)?;
let map = CodeMap::new(enc10, enc16, CodeRole::Intensity, SignalRange::Full)?;
let widened_code = map.map_code(512);

§Drilldown 4: Metadata, Evidence, Orientation & Dual-Layer HDR

§ColorOrigin, Cicp, and CicpTag

ColorOrigin (file provenance — what the container originally declared)
├── kind: OriginKind ── Assumed | Cicp | Icc | IccAndCicp | GamaChrm
├── cicp: Option<Cicp>
│   ├── color_primaries:          u8   (H.273 Table 2: 1=BT.709, 9=BT.2020, 12=Display P3)
│   ├── transfer_characteristics: u8   (H.273 Table 3: 1=BT.709, 8=Linear, 13=sRGB, 16=PQ, 18=HLG)
│   ├── matrix_coefficients:      u8   (H.273 Table 4: 0=Identity/RGB, 1=BT.709, 6=BT.601, 9=BT.2020)
│   └── full_range:               bool
└── icc:  Option<Arc<[u8]>>            (raw ICC profile bytes)

CicpTag (ICC.1 cicpType: 12-byte base OR 44-byte extended with signed s15Fixed16 CustomPrimaries)

ColorSpace on PixelFormat says what the pixels mean right now; ColorOrigin says what the input file originally contained so OutputSignaling::PreserveOrigin / Auto knows whether to preserve or re-emit CICP/ICC.

use zenpixels::{AlphaMode, Cicp, CicpTag, ColorOrigin, CustomPrimaries};

let cicp = Cicp::DISPLAY_P3;
let color = cicp.to_color_space(AlphaMode::None)?;
let origin = ColorOrigin::from_cicp(cicp);

// 44-byte ICC.1 cicpType with custom primaries (supports negative chromaticities like ACES AP0):
let tag = CicpTag::with_custom_primaries(CustomPrimaries::ACES_AP0, 16, 0, true);
assert_eq!(tag.encoded_len(), 44);

§HdrMetadata, Nits, DiffuseWhite, and HlgRendering

HdrMetadata (Copy, Default = empty)
├── content_light_level: Option<ContentLightLevel>
│   ├── max_content_light_level:       u16   (MaxCLL in cd/m²)
│   └── max_frame_average_light_level: u16   (MaxFALL in cd/m²)
└── mastering: Option<MasteringDisplay>      (presets: HDR10_REFERENCE, DISPLAY_P3_1000)
    ├── primaries_xy:   [[f32; 2]; 3]        (R, G, B CIE xy)
    ├── white_point_xy: [f32; 2]             (white CIE xy)
    ├── max_luminance:  f32                  (cd/m²)
    └── min_luminance:  f32                  (cd/m²)

Validated luminance wrappers:
├── Nits(f32)         ── finite > 0.0; Nits::new_positive(1000.0) -> Option<Nits>, const Nits::new_positive_or_panic(1000.0)
├── DiffuseWhite(f32) ── SDR paper-white anchor; DiffuseWhite::new(v) -> Option, DiffuseWhite::BT2408 = 203.0 nits
└── HlgRendering      ── peak: Nits, black_nits: f32, system_gamma: f32 (REFERENCE_1000_NIT; HlgRendering::new(HlgRenderingParams { ... }))

§SampleClaims, ExactDepth, and FloatClaims

SampleClaims (Copy, Default = NONE; automatically cleared on any mutable pixel access!)
├── float:         FloatClaims        (bitflags: NO_NAN, NO_INFINITE, NO_SUBNORMALS,
│                                      NON_NEGATIVE, POSITIVE, AT_MOST_ONE, FINITE,
│                                      UNIT_INTERVAL, NORMAL_UNIT_INTERVAL)
├── depth:         Option<ExactDepth> (storage: SampleType, range: SignalRange,
│                                      color_bits: u8, alpha_bits: u8)
├── all_opaque:    bool               (every active alpha sample == channel max)
├── all_grayscale: bool               (every active pixel has R == G == B)
└── binary_alpha:  bool               (every active alpha sample is 0 or max)

§Orientation

Orientation is the 8-element EXIF dihedral group (Identity = 1, FlipH = 2, Rotate180 = 3, FlipV = 4, Transpose = 5, Rotate90 = 6, Transverse = 7, Rotate270 = 8).

§DualLayerHdrBuf and GainMapMetadata

DualLayerHdrBuf / DualLayerHdrView<'a>
├── base:                  PixelBuf / PixelView<'a>   (SDR or HDR base rendition)
├── gain_map:              PixelBuf / PixelView<'a>   (1-channel Gray or 3-channel RGB gain map)
├── metadata:              GainMapMetadata (Copy)
│   ├── channels:               GainMapChannels::Shared(GainMapComponent)
│   │                         | GainMapChannels::PerChannel([GainMapComponent; 3])
│   │                           └── GainMapComponent:
│   │                               ├── min_gain_stops:   SignedFraction   { numerator: i32, denominator: NonZeroU32 }
│   │                               ├── max_gain_stops:   SignedFraction
│   │                               ├── gamma:            UnsignedFraction { numerator: u32, denominator: NonZeroU32 }
│   │                               ├── base_offset:      SignedFraction
│   │                               └── alternate_offset: SignedFraction
│   ├── base_hdr_headroom:      UnsignedFraction (log2 stops)
│   ├── alternate_hdr_headroom: UnsignedFraction (log2 stops)
│   ├── application_space:      GainMapColorSpace::Base | Alternate
│   └── backward_direction:     Option<bool>
├── alternate_color_space: Option<ColorSpace>         (required when application_space == Alternate)
└── orientation:           Orientation                (shared by both base and gain map)

§Drilldown 5: Conversion Engine (zenpixels-convert)

§Dataflow Across Entry Points

flowchart LR
    SRC["Source: PixelView / PixelBuf / BandedBuf"]
    POL["ConvertPolicy (default = lossless())"]
    PEAK["PeakSource (Measured | Declared | Fixed Nits)"]
    SIG["OutputSignaling (Auto | PreserveOrigin | CicpOnly | IccOnly | CicpAndIcc | ExplicitIcc | Strip)"]

    SRC --> Q["to_rgb8_if_opaque / to_rgba8 / to_bgra8 / to_gray8_if_opaque"]
    SRC --> ONESHOT["ImagePlan::convert / convert_into"]
    SRC --> IP["ImagePlan::build -> execute / execute_into"]
    SRC --> RP["RowPlan::build(Option Nits) -> convert_row"]
    SRC --> OP["OutputPlan::build / OutputPlan::adapt_for_encode"]

    POL --> ONESHOT
    POL --> IP
    POL --> RP
    POL --> OP
    PEAK --> IP
    PEAK --> OP
    SIG --> OP

    Q --> OUT1["PixelBuf"]
    ONESHOT --> OUT1
    IP --> OUT1
    RP --> OUT2["dst_row mut byte slice (0 heap alloc)"]
    OP --> OUT3["EncodeReady (pixels: PixelCow, cicp, icc, hdr)"]
Rendered Mermaid diagram · Open the interactive clickable Data Structures Atlas →

§ConvertPolicy Anatomy and Presets

ConvertPolicy (Default == ConvertPolicy::lossless() — refuses silent loss!)
├── Loss Permission Gates
│   ├── depth:              DepthPolicy      ── Forbid | Round | OrderedDither | Truncate
│   ├── alpha:              AlphaPolicy      ── Forbid | DiscardIfOpaque | DiscardUnchecked | CompositeOnto(Color)
│   ├── gamut:              GamutPolicy      ── Forbid | PreserveExtended | Clip | SoftCompress
│   └── range:              RangePolicy      ── Forbid | Convert
├── RGB -> Gray Luma
│   ├── luma:               LumaCoefficients ── FromSourcePrimaries | Bt709 | Bt601 | Bt2020 | Custom([f32; 3])
│   └── luma_domain:        LumaDomain       ── Encoded (JPEG/video Y') | LinearLight (physical Y)
├── HDR Anchors & Tone Mapping
│   ├── diffuse_white:      Option<DiffuseWhite>
│   ├── sdr_peak:           Nits
│   ├── hlg_rendering:      Option<HlgRendering>
│   ├── tone_map_hdr_to_sdr: bool
│   └── tone_mapper:        Option<Arc<dyn ToneMapper>>  (e.g. Bt2446A::pipeline_managed())
└── Backends, Evidence & SIMD
    ├── cms:                    Option<Arc<dyn CmsBackend>> (e.g. MoxCms, Lcms)
    ├── allow_icc_substitution: bool
    ├── allow_approximate:      bool
    ├── source_claims:          SampleClaims
    └── accelerators:           Option<Accelerators> (None -> global process setting; default scalar)
Presetdepthalphagamutrangetone_map_hdr_to_sdrallow_icc_substitution
ConvertPolicy::lossless() (default())ForbidForbidPreserveExtendedForbidfalsefalse
ConvertPolicy::permissive()RoundDiscardUncheckedClipConvertfalsetrue
ConvertPolicy::working_linear()RoundDiscardIfOpaquePreserveExtendedConvertfalse (BT2408 white)true
ConvertPolicy::display_sdr(white, peak)RoundCompositeOnto(BLACK)ClipConverttruetrue

§ColorServices and Named CMS Bindings

When an application or server shares one CMS provider and tone mapper across zenpixels-convert, codecs, and renderers, configure a ColorServices bundle once, resolve per-run overrides via resolve_against / freeze_or_strict, and stamp it onto ConvertPolicy::with_color_services:

ColorServices (shared host bundle, Clone)
├── cms: CmsChoice
│   ├── Inherit          (inherit parent/host default until frozen)
│   ├── StrictNoIcc      (forbid ICC CMS evaluation AND inferred matrix+TRC substitution)
│   └── Use(CmsBinding)
│       ├── id: &str              (e.g. "org.imazen.cms.moxcms")
│       ├── revision: &str        (deterministic cache key component)
│       ├── backend: Arc<dyn CmsBackend>
│       └── quote: CmsQuote       (supports_u8/u16/f16/f32/cmyk/abs_col/float_mpe, memory/stack bounds)
└── tone_mapper: Option<Arc<dyn ToneMapper>>
use zenpixels_convert::{CmsChoice, ColorServices, ConvertPolicy, MoxCms};

// Host startup: bind MoxCms once with its conservative capability/resource quote.
let host_services = ColorServices::with_cms_binding(MoxCms::binding());
assert_eq!(host_services.cms_binding().unwrap().id(), "org.imazen.cms.moxcms");
assert!(host_services.cms_binding().unwrap().quote().supports_cmyk);

// Per-request override inherits the host CMS unless explicitly pinned to StrictNoIcc:
let request_services = ColorServices::inherit().resolve_against(&host_services);
assert!(matches!(request_services.cms_choice(), CmsChoice::Use(_)));

// Stamp onto ConvertPolicy (StrictNoIcc also clears allow_icc_substitution!):
let policy = ConvertPolicy::permissive().with_color_services(&request_services);
assert!(policy.cms.is_some());

§Choosing a Conversion Entry Point

use std::sync::Arc;
use zenpixels_convert::{
    Accelerators, Bt2446A, ConvertPolicy, DiffuseWhite, ImagePlan, Nits, PeakSource, PixelBuf,
    PixelConvertExt, PixelFormat, RowPlan, formats,
};

// 1. One-line 8-bit sRGB:
let rgba = src_view.to_rgba8()?;

// 2. One-shot arbitrary destination (lossless widening RGB8 -> linear F32):
let linear = src_view.convert_to(&formats::RGBF32_LINEAR, &ConvertPolicy::lossless())?;

// 3. Streaming row loop (zero per-row heap allocation):
let row_plan = RowPlan::build(
    &formats::RGB8_SRGB,
    &formats::RGBF32_LINEAR,
    &ConvertPolicy::lossless().with_accelerators(Accelerators::WEB_SDR),
    None, // resolved source peak (Only needed for HDR -> SDR tone mapping)
)?;
let mut dst = PixelBuf::new(src_view.width(), src_view.height(), PixelFormat::RGBF32_LINEAR)?;
for y in 0..src_view.height() {
    row_plan.convert_row_at(y, src_view.row(y), dst.row_mut(y), src_view.width())?;
}

// 4. Whole-image HDR PQ -> SDR tone mapping with streaming peak measurement:
let hdr_policy = ConvertPolicy::display_sdr(DiffuseWhite::BT2408, Nits::new_positive(100.0).unwrap())
    .with_tone_mapper(Arc::new(Bt2446A::pipeline_managed()));
let sdr = ImagePlan::build(
    &formats::RGB16_BT2100_PQ,
    &formats::RGB8_SRGB,
    &hdr_policy,
    PeakSource::Measured,
)?
.execute(&pq_view)?;

§OutputPlan, Negotiate, and EncodeReady

Encoders combine format selection (Negotiate) with pixel conversion and container metadata signaling (OutputSignaling) in one step:

use zenpixels_convert::{
    ConvertPolicy, OutputPlan, OutputSignaling, PeakSource, PixelBuf, PixelFormat,
};

const SUPPORTED: &[PixelFormat] = &[
    PixelFormat::RGB8_SRGB,
    PixelFormat::RGBA8_SRGB,
    PixelFormat::GRAY8_SRGB,
];

let (negotiated, ready) = OutputPlan::adapt_for_encode(
    buf.as_view(),
    buf.origin(),
    SUPPORTED,
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::Auto,
)?;
// `negotiated.format` is the chosen PixelFormat (`negotiated.index`, `negotiated.loss`, `negotiated.cost`)
// `ready.pixels()` is `PixelCow::Borrowed` if already compatible (zero copy!), or `PixelCow::Owned`
// `ready.cicp()` and `ready.icc()` match `ready.pixels()` atomically

§Gain Maps, Compaction, and Measurement


§Key Contracts & Conventions to Keep in Mind

AreaContract
PixelBuf::new vs PixelBuf::new_raw_zeroednew fills black + channel-max alpha for AlphaMode::Opaque. new_raw_zeroed skips alpha fill and rejects AlphaMode::Opaque with BufferError::UnverifiedOpaqueAlpha until you fill pixels and call into_opaque_verified() / assume_opaque().
crop(PixelRect) / crop_view(PixelRect)Takes PixelRect::new(x, y, width, height) in pixels. Crops preserve the parent’s stride_bytes().
RowPlan::convert_row vs convert_row_atconvert_row(src, dst, width_pixels) is the common 3-arg call; convert_row_at(row_index, src, dst, width_pixels) passes the image row index for deterministic 4×4 Bayer ordered dithering.
reconstruct_planar_to_buf vs reconstruct_planar_intoBoth put &PlanarReconstructionOptions last: to_buf(src, dst_layout, options) and into(src, dst, options).
with_* vs try_with_* on ColorSpace and PixelFormatPixelFormat::with_* checks the revised format and returns a Result. The try_with_* builders return None for inapplicable or invalid changes.
LightLevelHistogram::quantile_nits(quantile)quantile is a fraction in 0.0..=1.0 (e.g. 0.999), not 0.0..=100.0. LightLevelHistogram::new(method) is fallible (Result<Self, At<ConvertError>>).
PixelView::as_strided_bytes() vs as_contiguous_bytes() vs to_contiguous_bytes()as_strided_bytes() includes row padding bytes; as_contiguous_bytes() returns Option<&[u8]> (only when tight); to_contiguous_bytes() returns Result<Cow<[u8]>, _> (copies to strip padding when strided).
PixelBuf::as_view_mut() vs try_cow_view_mut()On immutable External storage (Arc<[u8]>), as_view_mut() promotes via CoW and panics on OOM; try_cow_view_mut() returns Result<PixelViewMut<'_>, At<BufferError>>.
ExactDepth::intersect_same_buffer vs union_disjoint_regionsintersect_same_buffer takes the tighter depth (min) of two facts about the same buffer; union_disjoint_regions computes the smallest common containing grid (lcm / max) across disjoint strips of an image.
Nits::new_positive / DiffuseWhite::new / GainMapMetadata::sdr_to_hdr_stopsFallible (Option<Self>) when rejecting non-positive or non-finite values; const panicking constructors use explicit _or_panic (Nits::new_positive_or_panic, DiffuseWhite::new_or_panic).