zenpixels 0.5 User Guide & Cookbook

A task-oriented guide to storing, borrowing, and converting pixels in Rust with zenpixels and zenpixels-convert. Both crates are #![forbid(unsafe_code)] and support no_std + alloc (disable default std features for no_std).

If you want an interactive visual diagram & inspector, open the Data Structures Atlas (or read the Type Atlas drilldown). If you are upgrading from zenpixels 0.2 or 0.4, see the 0.2 / 0.4 → 0.5 migration guide. Unfamiliar term (SampleFacts, DiffuseWhite, CICP, ChromaSiting, whereat::At<E>)? Jump to the Quick Glossary.


§Your First 60 Seconds (Wrap → Crop → Convert)

use zenpixels_convert::{
    ConvertPolicy, PixelBuf, PixelFormat, PixelRect, formats, PixelConvertExt,
};

// 1. Own tightly packed sRGB RGB8 pixels (annotate literals so Rust infers u8):
let img = PixelBuf::from_typed(
    vec![255u8, 0, 0,  0, 255, 0,  0, 0, 255,  255, 255, 255],
    2, 2,
    PixelFormat::RGB8_SRGB,
)?;

// 2. Borrow a zero-copy rectangular crop (keeps parent stride = 6 bytes):
let right_col = img.crop_view(PixelRect::new(1, 0, 1, 2))?;
assert_eq!(right_col.row(0), &[0, 255, 0]);

// 3. Convert to straight-alpha RGBA8 in one call, or widen losslessly to linear F32:
let rgba = right_col.to_rgba8()?;
assert_eq!(rgba.row(0), &[0, 255, 0, 255]);

let linear = right_col.convert_to(&formats::RGBF32_LINEAR, &ConvertPolicy::lossless())?;
assert_eq!(linear.format(), &formats::RGBF32_LINEAR);

§1. The 4-Type Mental Model

You only need four types on day one:

TypeWhat it isOwns memory?Copy?When to use
PixelFormatFull image description: SampleLayout (bytes/order/depth) + ColorSpace (RGB/Gray/Oklab/XYZ/CMYK/ICC/Untagged)Only if ColorSpace::Icc (Arc<[u8]>)NoDescribing any buffer or conversion endpoint
PixelBufOwned, stride-preserving, alignment-exact 2D pixel buffer (+ Orientation, HdrMetadata, ColorOrigin, SampleFacts)Yes (Vec, aligned, or external Arc/Box/FFI)NoHolding decoded or converted images
PixelView<'a> / PixelViewMut<'a>Borrowed strided 2D view or rectangular crop (zero copies)NoNoPassing images or tiles into functions

Two preset jobs, two spellings:

Auxiliary metadata carried on buffers/views:

§Validate and measure an image

PixelBuf owns the sample bytes. PixelView borrows them. Dimensions, stride, and SampleLayout tell you where each sample lives, and ColorSpace tells you how to interpret it. Constructors check that the bytes can be viewed with the given layout. Use PixelScanExt when you also need to check the sample values.

What do you need to know?API
What claims are already attached to this image?attached_claims() reads the inline metadata in constant time.
Is a particular claim true of these pixels?verify_claims(required) checks the requested properties and names the first one it cannot establish.
What can I prove about these pixels now?measure_claims() returns fresh opacity, grayscale, depth, and float evidence.
How do I refresh the claims before conversion?measure_and_attach_claims() replaces the attached claims with fresh measurements and returns them.
Which pixel violated the requested bounds?check_samples(bounds) reports the violated bound and view-relative pixel. Use check_nominal_samples() for nominal bounds.

Claims travel with the buffer or view as a small value beside its format, even when the sample bytes are borrowed or externally owned. Each positive flag asserts a property. For example, all_opaque == false leaves opacity unknown. Planners trust attached claims, which may come from construction, measurement, or a caller assertion. Mutable pixel access clears them.

§Verify a claim for conversion

When you own a straight RGBA8 buffer, use into_opaque_verified() to check that every stored alpha is 255 and retag the buffer without copying pixels.

use zenpixels_convert::{PixelBuf, PixelConvertExt, PixelFormat};

let image = PixelBuf::from_typed(vec![17u8, 85, 153, 255], 1, 1, PixelFormat::RGBA8_SRGB)?;
let rgb = image.into_opaque_verified()?.to_rgb8_if_opaque()?;
assert_eq!(rgb.row(0), &[17, 85, 153]);

The conversion uses the alpha mode and attached claims to decide whether it can discard alpha. To verify only opacity while retaining the original format, use verify_claims with SampleClaims::NONE.with_all_opaque(true). Attach that verified claim if a conversion needs to use it.

When a decoder guarantees the stored alpha it wrote, it can attach that claim directly with assume_claims for a constant-time handoff. This method replaces the attached claims. To retain other established claims about the same pixels, combine them with SampleClaims::intersect_same_buffer.

§Diagnose sample values and attached claims

Check the bounds and the attached claims independently. If you want to take new measurements for further processing, use measure_and_attach_claims() to replace the claims with the measured properties. This example shows a valid straight-alpha pixel with an incorrect opacity claim.

use zenpixels_convert::{PixelBuf, PixelFormat, PixelScanExt, SampleBounds, SampleClaims};

let mut image = PixelBuf::from_typed(vec![17u8, 85, 153, 128], 1, 1, PixelFormat::RGBA8_SRGB)?;
image.assume_claims(SampleClaims::NONE.with_all_opaque(true));

let bounds = image.check_samples(SampleBounds::Nominal);
let recorded = image.verify_claims(image.attached_claims());
let observed = image.measure_and_attach_claims();
eprintln!("bounds={bounds:?}, attached claims={recorded:?}, observed={observed:?}");
assert!(bounds.is_ok());
assert!(recorded.is_err());
assert!(!observed.all_opaque);
assert_eq!(image.attached_claims(), observed);

Pass an explicit SampleClaims to verify_claims to check an expectation that the caller has yet to attach. For a format tagged AlphaMode::Opaque, bounds validation already checks that the stored alpha is maximal.

SampleBounds::Format requires finite tagged float color and normalized alpha, including maximum alpha when declared opaque. It permits finite extended float color and narrow-range headroom and footroom. SampleBounds::Nominal adds the nominal color-code limits for narrow-range integers and [0, 1] for RGB, gray, and CMYK floats. Both policies check numerical values. Row padding, RGBX/BGRX padding, and unused packed bits are outside their scope. File-format conformance and color-profile behavior are separate from these checks.

Both bounds policies report the exact pixel on failure. The checker searches within the failing row only after an error. Coordinates are zero-based and relative to the checked view, including when it is a crop. view.check_nominal_samples()? is equivalent to view.check_samples(SampleBounds::Nominal)?.

use zenpixels_convert::{PixelBuf, PixelFormat, PixelRect, PixelScanExt};

let image = PixelBuf::from_typed(
    vec![[0.25f32, 0.5, 0.75], [0.25, 1.25, 0.75]],
    2, 1, PixelFormat::RGBF32_LINEAR,
)?;
let view = image.as_view();
let error = view.check_nominal_samples().unwrap_err();
assert_eq!(error.to_string(), "color outside nominal range at pixel (1, 0)");
let pixel = view.crop(error.pixel())?;
assert_eq!(error.pixel(), PixelRect::new(1, 0, 1, 1));
assert_eq!(pixel.row_samples::<f32>(0)?, &[0.25, 1.25, 0.75]);

§White fill and luminance

Color::WHITE is relative-linear [1.0; 3] in sRGB/BT.709 primaries with a D65 white point. As an alpha matte, it is transformed into the working primaries and takes the luminance of the resolved white anchor.

ColorSpace::diffuse_white() reads the optional luminance anchor for relative-linear 1.0. With DiffuseWhite::BT2408, linear 1.0 represents 203 cd/m² and neutral linear 2.0 represents 406 cd/m² in a luminance conversion. When crossing between PQ and relative light, the relative format’s anchor takes precedence over the conversion policy’s fallback. A display peak comes from the rendering target, such as HlgRendering::peak(). A content peak comes from image measurement or metadata. ITU-R BT.2408, §2.1

For RGB and gray, PixelBuf::new_signal_white fills nominal signal white, the code for normalized signal 1.0. For example, it writes 255 in full-range U8 or 235 in narrow-range U8. The transfer determines what that code represents. In PQ it represents 10,000 cd/m². In display-rendered HLG it represents the configured display peak. Scene HLG and unanchored SDR carry relative values. new_signal_white uses model-specific values for formats such as XYZ and CMYK. ITU-R BT.2100, tables 4, 5 and 9


§2. Error Handling (3 Exact Shapes)

Not every fallible API returns whereat::At<E>. The boundary is consistent:

  1. Located whereat::At<E> — carrier constructors, into_tight_rows, plans, conversions, orientation, planar reconstruction, gain maps, CMS, measurements, and PixelFormat::validate / Cicp::try_from_bytes / CicpTag::from_tag_bytes:
    use zenpixels::{BufferError, PixelFormat, PixelBuf};
    
    let _buf = match PixelBuf::from_bytes(bytes, w, h, PixelFormat::RGB8_SRGB) {
        Ok(buf) => buf,
        Err(err) => match *err.error() { // or `err.decompose()` to take ownership of `(E, trace)`
            BufferError::InsufficientData => return Ok(()),
            BufferError::UnverifiedOpaqueAlpha => return Ok(()),
            other => return Err(other.into()),
        },
    };
  2. Bare E — const-capable layout, storage, code-plane, validation, and CICP projection primitives (LayoutError, StorageError, SampleEncodingError, ExactDepthError, CodePlaneError, CicpProjectionError, IccValidationError, CodeMapError, plus TryFrom<Cicp> for image::metadata::Cicp):
    use zenpixels::{CicpProjectionError, ColorSpace};
    
    match color.project_cicp_tag() {
        Ok(_tag) => { /* ... */ }
        Err(CicpProjectionError::HlgDisplayRenderingLost) => { /* ... */ }
        Err(_other) => { /* ... */ }
    }
  3. Recovery returns — when you want your input buffer back on error:

Naming rule for try_: Standalone fallible methods use ordinary names (from_typed, from_bytes, into_tight_rows, into_vec_zero_copy, make_mut, merge, project_cicp). The try_ prefix appears only when the same type already has a direct value-returning twin or returns Option for partial domain inputs (try_clone/clone, try_cow_view_mut/as_view_mut, try_with_*/with_*, try_image_srgb_default_color, Cicp::try_from_bytes/Cicp::from_bytes_lenient).


§3. Buffers, Views, Cropping & External Storage

§Choosing a PixelBuf Constructor

GoalConstructorNotes
Fresh black buffer (max alpha if AlphaMode::Opaque)PixelBuf::new(w, h, spec)Safe default; sets claims.all_opaque = true when opaque
Fresh signal-white bufferPixelBuf::new_signal_white(w, h, spec)255 for U8, 65535 for U16, 1.0 for F32
Fast zeroed buffer for decoders that overwrite every pixelPixelBuf::new_raw_zeroed(w, h, spec)Skips alpha-fill pass; refuses AlphaMode::Opaque on alpha-bearing layouts (BufferError::UnverifiedOpaqueAlpha)
Fresh buffer preflighted for an interop targetPixelBuf::new_for_interop(w, h, spec, target)Checks InteropTarget compatibility upfront (does not convert)
Adopt tightly packed Vec<u8>PixelBuf::from_bytes(vec, w, h, spec)Handles odd-address allocators; use from_bytes_recover to get vec back on error
Adopt typed Vec<P> (u8, u16, f32, [u8; 3], Rgb<u8>, …)PixelBuf::from_typed(vec, w, h, spec)Validates P against spec.layout() (annotate literals like vec![255u8, ...]); use from_typed_recover to recover on error
Adopt scalar channel Vec<S> (u8/u16/f32/F16Sample)PixelBuf::from_samples(vec, w, h, spec)Checks sample type only
Adopt external owned storage zero-copy (Arc<[u8]>, Box<[T]>, FFI)PixelBuf::from_external(storage, w, h, stride, spec)Mutable zero-copy: from_external_mut; returns (err, storage) on error
Rebuild from PixelBufParts / raw PixelStoragePixelBuf::from_parts(parts) / from_storage_parts(...)Use from_parts_recover to keep parts on error

Relabeling vs numeric conversion (pixel bytes untouched):

§Fast Opaque Decode (Zero-Overhead Fill-Then-Retag)

use zenpixels::{AlphaMode, BufferError, PixelFormat, PixelBuf};

// 1. `new_raw_zeroed` refuses unverified `AlphaMode::Opaque` on alpha-bearing layouts:
let opaque_rgba = PixelFormat::RGBA8_SRGB.with_alpha(AlphaMode::Opaque)?;
let err = PixelBuf::new_raw_zeroed(4, 4, opaque_rgba).unwrap_err();
assert_eq!(*err.error(), BufferError::UnverifiedOpaqueAlpha);

// 2. Allocate as Straight, write every pixel (with A = 255), then verify & retag zero-copy:
let mut buf = PixelBuf::new_raw_zeroed(4, 4, PixelFormat::RGBA8_SRGB)?;
for y in 0..buf.height() {
    for px in buf.row_mut(y).chunks_exact_mut(4) {
        px.copy_from_slice(&[10, 20, 30, 255]);
    }
}
// `into_opaque_verified` scans all active pixels itself (no prior `assume_claims` needed):
let opaque = buf.into_opaque_verified()?;
assert!(opaque.attached_claims().all_opaque);
assert_eq!(opaque.format().color().alpha(), AlphaMode::Opaque);
// (Or `into_opaque_filled()` to fill alpha to max, or `assume_opaque()` if caller guarantees it.)

§Zero-Copy External Arc<[u8]> + Crop + Fallible Copy-on-Write

use std::sync::Arc;
use zenpixels::{PixelBuf, PixelFormat, PixelRect};

let shared: Arc<[u8]> = Arc::from(vec![42u8; 8 * 6 * 3]);
let mut buf = PixelBuf::from_external(shared.clone(), 8, 6, 8 * 3, PixelFormat::RGB8_SRGB)
    .map_err(|(err, _orig)| err)?;

// Rectangular zero-copy crop preserves parent stride (24 bytes):
let tile = buf.crop_view(PixelRect::new(2, 1, 4, 3))?;
assert_eq!((tile.width(), tile.height()), (4, 3));
assert_eq!(tile.stride_bytes(), 24);
assert_eq!(tile.row(0).len(), 4 * 3);

// Fallible CoW mutation promotes `buf` to owned storage without touching `shared`:
buf.try_cow_view_mut()?.row_mut(0)[0] = 99;
assert_eq!(buf.row(0)[0], 99);
// Mutable crops (`crop_view_mut` / `sub_rows_mut`) also promote fallibly on CoW;
// `buf.into_crop(PixelRect::new(x, y, w, h))?` crops an owned `PixelBuf` in O(1) without copying pixels
// (chain `.into_tight_rows()?` afterwards to compact row stride).
assert_eq!(shared[0], 42);

§Zero-Allocation Borrowed Views (PixelView / PixelViewMut)

Primary view constructors take &'a PixelFormat so borrowing raw bytes never allocates:

use zenpixels::{PixelFormat, PixelView, PixelViewMut, FormatCow, formats};

// Tightly packed bytes (zero allocations):
let view = PixelView::from_bytes(rgb_bytes, w, h, &formats::RGB8_SRGB)?;

// Strided bytes (zero allocations):
let strided = PixelView::new(rgb_bytes, w, h, stride_bytes, &formats::RGB8_SRGB)?;
let mut_view = PixelViewMut::new(rgb_bytes_mut, w, h, stride_bytes, &formats::RGB8_SRGB)?;

// Advanced escape hatch: owned/shared spec on a view (0-alloc for standard presets, Arc for custom/ICC):
let cow_view = PixelView::new_with_format_cow(
    rgb_bytes, w, h, stride_bytes, FormatCow::from_owned(PixelFormat::RGB8_SRGB),
)?;

§Error Recovery & Zero-Copy Vec Extraction

use zenpixels::{PixelFormat, PixelBuf};

// Recover original Vec intact on failure:
let too_small = vec![1u8, 2, 3];
let (_err, recovered) = PixelBuf::from_typed_recover(too_small, 2, 2, PixelFormat::RGB8_SRGB)
    .unwrap_err();
assert_eq!(recovered, vec![1, 2, 3]);

// Zero-copy extraction back to Vec<u8> (fails returning `Err(buf)` if alignment/stride differs;
// use `into_vec::<P>()` to copy if zero-copy isn't possible):
let data = vec![10u8; 2 * 2 * 3];
let ptr = data.as_ptr();
let buf = PixelBuf::from_typed(data, 2, 2, PixelFormat::RGB8_SRGB)?;
let back: Vec<u8> = buf.into_vec_zero_copy::<u8>().expect("tight u8 Vec");
assert_eq!(back.as_ptr(), ptr);

§4. Converting Pixels (zenpixels-convert)

zenpixels-convert re-exports all of zenpixels::* at its root with zero module collisions.

§Which Conversion API Should I Pick?

TaskFunction / TypePolicy & Peak
Quick full-range sRGB 8-bit outputview.to_rgb8_if_opaque(), view.to_gray8_if_opaque()permissive().with_alpha(DiscardIfOpaque) (refuses unproven alpha loss!)
Quick straight-alpha sRGB 8-bit outputview.to_rgba8(), view.to_bgra8()permissive()
One-shot conversion into a new PixelBufview.convert_to(destination_format, &policy)Defaults to PeakSource::Measured (measured only when HDR tone mapping needs a peak); use convert_to_with_peak for explicit PeakSource
One-shot conversion into an existing sinksrc.convert_into(&mut dst, &policy)Works with PixelBuf, PixelViewMut, BandedBuf; use convert_into_with_peak for explicit PeakSource
Reusable whole-image converterImagePlan::build(src, dst, &policy, peak).execute(&src) or .execute_into(&src, &mut dst)
Streaming row-by-row converter (zero heap scratch)RowPlan::build(src, dst, &policy, resolved_source_peak)Takes Option<Nits> (cannot measure a whole image from one row); plan.convert_row(src_row, dst_row, width_pixels) (or convert_row_at(row_index, ...) for ordered dithering)
Negotiate + convert + resolve CICP/ICC for an encoderOutputPlan::adapt_for_encodeReturns EncodeReady with pixel and signaling accessors under OutputSignaling

§ConvertPolicy Presets (Safe by Default)

ConvertPolicy::default() equals ConvertPolicy::lossless() — a strict loss-permission preset (not a universal mathematical identity proof for float operations) that refuses unprovable depth narrowing, alpha discard, and range scaling, and preserves extended float gamut. It is content-aware on whole-image plans (ImagePlan): freshly allocated all-black/white buffers (PixelBuf::new, new_signal_white) seed exact 1-bit SampleClaims, so narrowing an untouched black RGB16 buffer to RGB8 is provably lossless and succeeds, whereas non-exact 16-bit content fails with ConvertError::DepthReductionForbidden (and RowPlan::build, which cannot see image content, refuses unconditionally unless claims are attached on the policy). Opt in explicitly when loss is desired:

PresetDepthAlphaGamutRangeHDR→SDR Tone MapICC Sub
ConvertPolicy::lossless() / default()ForbidForbidPreserveExtendedForbidfalsefalse
ConvertPolicy::permissive()RoundDiscardUncheckedClipConvertfalsetrue
ConvertPolicy::working_linear()RoundDiscardIfOpaquePreserveExtendedConvertfalse (BT2408 white)true
ConvertPolicy::display_sdr(white, peak)RoundCompositeOnto(BLACK)ClipConverttruetrue

RGB → Gray luma domain: Defaults to LumaDomain::Encoded (Y' on encoded samples, matching JPEG/video — sRGB (255, 0, 0) → 54). Switch to physical luminance with .with_luma_domain(LumaDomain::LinearLight) (sRGB (255, 0, 0) → 127).

§HDR PQ → SDR Tone Mapping & SIMD/Scalar 0-Bit Parity

Plain ConvertPolicy::permissive() refuses unanchored PQ→SDR routes (ConvertError::MissingHdrAnchor) until you configure a diffuse white anchor and tone mapper (Bt2446A, enabled via the bt2446a Cargo feature; use Bt2446A::pipeline_managed() or explicit typed Bt2446A::with_peaks(Nits::new_positive(1000.0).unwrap(), Nits::new_positive(100.0).unwrap())):

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

let policy = ConvertPolicy::display_sdr(DiffuseWhite::BT2408, Nits::new_positive(100.0).unwrap())
    .with_tone_mapper(Arc::new(Bt2446A::pipeline_managed()));

// Whole-image streaming peak measurement (O(1) row memory):
let plan = ImagePlan::build(
    &formats::RGB16_BT2100_PQ,
    &formats::RGB8_SRGB,
    &policy,
    PeakSource::Measured,
)?;
let sdr_buf = plan.execute(&pq16_buf)?;

// Streaming row-by-row with explicit resolved source peak (e.g. 1000 nits) + SIMD vs scalar parity:
let peak = Nits::new_positive(1000.0);
let simd_row = RowPlan::build(
    &formats::RGB16_BT2100_PQ,
    &formats::RGB8_SRGB,
    &policy.clone().with_accelerators(Accelerators::ALL),
    peak,
)?;
let scalar_row = RowPlan::build(
    &formats::RGB16_BT2100_PQ,
    &formats::RGB8_SRGB,
    &policy.with_accelerators(Accelerators::SCALAR),
    peak,
)?;
// `simd_row.convert_row(...)` and `scalar_row.convert_row(...)` produce 0-bit identical bytes!

§Explicit ICC Conversion via MoxCms and Lcms

Enable Cargo features cms-moxcms and/or cms-lcms on zenpixels-convert:

use std::sync::Arc;
use zenpixels_convert::{
    AlphaMode, ColorSpace, ConvertPolicy, Lcms, MoxCms, PixelBuf, PixelFormat, RenderingIntent,
    SampleLayout, PixelConvertExt, formats, icc_profiles,
};

let adobe_spec = PixelFormat::new(
    SampleLayout::RGB8,
    ColorSpace::Icc {
        profile: Arc::from(icc_profiles::ADOBE_RGB),
        color_channels: 3,
        alpha: AlphaMode::None,
        intent: RenderingIntent::RelativeColorimetric,
    },
)?;

// Disable matrix+TRC fast substitution so the CMS backend actually executes:
let mox_pol = ConvertPolicy::permissive()
    .with_icc_substitution(false)
    .with_cms(Arc::new(MoxCms));
let lcms_pol = ConvertPolicy::permissive()
    .with_icc_substitution(false)
    .with_cms(Arc::new(Lcms));

let out_mox = src.convert_to(&formats::RGB8_SRGB, &mox_pol)?;
let out_lcms = src.convert_to(&formats::RGB8_SRGB, &lcms_pol)?;

§Encoder Format Negotiation & Output Signaling (OutputPlan)

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

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

// Borrows zero-copy (`PixelCow::Borrowed`) when input already matches a supported format:
let (chosen, ready) = OutputPlan::adapt_for_encode(
    buf.as_view(),
    buf.origin(),
    SUPPORTED,
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::Auto,
)?;
assert!(matches!(ready.pixels(), PixelCow::Borrowed(_)));

// Reusable OutputPlan (borrows specs & policy; checks DESTINATION signaling eagerly):
let plan = OutputPlan::build(
    &formats::RGB8_SRGB,
    &formats::RGB8_SRGB,
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::Auto,
)?;
assert!(plan.is_identity());
let ready_owned = plan.execute_buf(buf)?; // Zero-copy move on identity!

// Destination signaling guard: CICP cannot carry `HlgMode::Display(_)`, so targeting
// `RGB16_BT2100_HLG_1000` as `dst` under `CicpOnly` or `Auto` fails eagerly:
let err = OutputPlan::build(
    &formats::RGB8_SRGB,
    &formats::RGB16_BT2100_HLG_1000,
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::CicpOnly,
)
.unwrap_err();
assert_eq!(*err.error(), ConvertError::OutputSignalingUnavailable);

§5. Planar YCbCr, GBR, Planar RGB & Monochrome (planar)

Plane constructors (PlaneView, PlaneViewMut, PlaneBuf) keep byte vs. sample strides unambiguous:

§10-bit 4:2:0 YCbCr → Pre-Allocated BGRA8 (Zero Allocation)

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

let y_spec = PlaneFormat::new(PlaneRole::Y, SampleType::U16).try_with_packing(BitPacking::U10_LSB)?;
let cb_spec = PlaneFormat::new(PlaneRole::Cb, SampleType::U16)
    .try_with_packing(BitPacking::U10_LSB)?
    .with_subsampling(2, 2);
let cr_spec = PlaneFormat::new(PlaneRole::Cr, SampleType::U16)
    .try_with_packing(BitPacking::U10_LSB)?
    .with_subsampling(2, 2);

// Tight typed planes (for padded strides, use `from_samples_strided(..., SampleStride(n), spec)`):
let py = PlaneView::from_samples(&y_u16, 4, 4, y_spec)?;
let pcb = PlaneView::from_samples(&cb_u16, 2, 2, cb_spec)?;
let pcr = PlaneView::from_samples(&cr_u16, 2, 2, cr_spec)?;

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);

// Inspect 10-bit luma code directly (component 0):
let y_plane = planar.plane_by_role(PlaneRole::Y).unwrap();
let code = y_plane.code_u32(0, 0, 0).unwrap();
let code_plane = y_plane.as_code_plane(0)?;
assert_eq!(code_plane.code(0, 0), Some(code as u16));

// Zero-alloc reconstruction into pre-allocated BGRA8 buffer (source metadata drives range/matrix):
let mut dst = PixelBuf::new(4, 4, PixelFormat::BGRA8_SRGB)?;
planar.reconstruct_into(
    &mut dst.as_view_mut(),
    &PlanarReconstructionOptions::bilinear(),
)?;

§Planar F32 RGB+Alpha → Interleaved RGBA8

use zenpixels_convert::{
    ColorSpace, Orientation, PlanarBuf, PlanarReconstructionOptions, PlaneRole, PlaneFormat,
    SampleLayout, SampleType, bake_orientation_owned, PlanarConvertExt,
};

let specs = [
    PlaneFormat::new(PlaneRole::R, SampleType::F32),
    PlaneFormat::new(PlaneRole::G, SampleType::F32),
    PlaneFormat::new(PlaneRole::B, SampleType::F32),
    PlaneFormat::new(PlaneRole::Alpha, SampleType::F32),
];
let mut planar = PlanarBuf::new(4, 2, &specs)?
    .with_color(ColorSpace::LINEAR_SRGB_ALPHA)
    .with_orientation(Orientation::Rotate90);

// Write pixels via typed row slices:
planar.plane_view_mut_by_role(PlaneRole::R).unwrap().row_as_mut::<f32>(0)?[0] = 1.0;

// Reconstruct to interleaved RGBA8 (preserves Orientation::Rotate90):
let rgba = planar.as_view().reconstruct_to_buf(
    SampleLayout::RGBA8,
    &PlanarReconstructionOptions::nearest(),
)?;
assert_eq!(rgba.display_dimensions(), (2, 4));

// Physically bake pending orientation -> dimensions become (2, 4), orientation becomes Identity:
let baked = bake_orientation_owned(rgba)?;
assert_eq!((baked.width(), baked.height()), (2, 4));
assert_eq!(baked.orientation(), Orientation::Identity);

§6. Orientation & Gigapixel BandedBuf

§Orientation Verb Reference

IntentAPIPixel movement?Resulting orientation()
Replace EXIF metadatawith_orientation(self, o) / set_orientation(&mut self, o)None (O(1))o
Compose EXIF metadata (old.then(delta))compose_orientation(self, delta)None (O(1))old.then(delta)
Physically apply explicit o into a new/owned buffer (ignores pending metadata)apply_orientation(&view, o) / apply_orientation_owned(buf, o) / apply_orientation_banded(&bands, o, sizing)Yes (apply_orientation_owned(_, Identity) is zero-copy)Identity
Physically apply explicit o into a caller sinkapply_orientation_into(&view, o, &mut dst) / apply_orientation_banded_into(&bands, o, &mut dst_bands)Yes (zero allocation)Unchanged on caller’s dst (pixel write only)
Physically bake pending metadatabake_orientation(&view) / bake_orientation_owned(buf) / bake_orientation_banded(&bands, sizing)Yes (bake_orientation_owned is zero-copy when Identity)Identity
Dual-layer gain-map physical bakegainmap::bake_dual_layer_orientation(&view) / gainmap::bake_dual_layer_orientation_after(&view, delta)Both layersIdentity

§Gigapixel BandedBuf

BandedBuf splits huge images into row bands sized via BandSizing::{MaxBandBytes(usize), RowsPerBand(u32)} (default BandSizing::DEFAULT) and implements both PixelSource and PixelSink:

use zenpixels_convert::{
    BandSizing, BandedBuf, ConvertPolicy, ImagePlan, Orientation, PeakSource, PixelFormat,
    apply_orientation_banded,
};

let mut src = BandedBuf::new(8, 6, PixelFormat::RGB8_SRGB, BandSizing::MaxBandBytes(48))?;
assert!(src.band_count() > 1);
src.row_mut(0)[0..3].copy_from_slice(&[200, 100, 50]);

let mut dst = BandedBuf::new(8, 6, PixelFormat::RGBA8_SRGB, BandSizing::MaxBandBytes(64))?;
ImagePlan::build(src.format(), dst.format(), &ConvertPolicy::permissive(), PeakSource::Measured)?
    .execute_into(&src, &mut dst)?;

let rotated = apply_orientation_banded(&src, Orientation::Rotate90, BandSizing::MaxBandBytes(48))?;
assert_eq!((rotated.width(), rotated.height()), (6, 8));

// Materialize back to a single contiguous PixelBuf when needed (zero-copy if 1 band):
let flat = rotated.into_buf()?;
assert_eq!((flat.width(), flat.height()), (6, 8));

§7. Lossless H.273 CICP & 44-Byte ICC.1 cicpType

ColorOrigin::from_icc_cicp(embedded_icc, embedded_cicp) preserves either or both raw declarations and returns None when both are absent. A decoder can then select its own fallback, such as ColorOrigin::gama_chrm() or ColorOrigin::assumed().

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

// Standard 4-byte H.273 CICP round-trip:
let bt601 = Cicp::new(6, 6, 0, true);
let cs = bt601.to_color_space(AlphaMode::None)?;
assert_eq!(cs.project_cicp()?, bt601);

// 44-byte ICC.1 cicpType with custom primaries (negative y_B supported via signed s15Fixed16):
let tag = CicpTag::with_custom_primaries(CustomPrimaries::ACES_AP0, 16, 0, true);
let bytes = tag.to_tag_bytes_vec();
assert_eq!(bytes.len(), 44);
let decoded = CicpTag::from_tag_bytes(&bytes)?;
// Wire encoding quantizes chromaticities to signed s15Fixed16 (1/65536), so raw `f32`
// constants differ slightly from decoded floats. Compare serialized bytes or `to_s15fixed16()`:
assert_eq!(decoded.to_tag_bytes_vec(), bytes);
assert_eq!(decoded.cicp(), tag.cicp());
assert_eq!(
    decoded.custom_primaries().unwrap().to_s15fixed16(),
    CustomPrimaries::ACES_AP0.to_s15fixed16(),
);
let _cs_custom = decoded.to_color_space(AlphaMode::None)?;

// ICC Annex 1 D50 Bradford matrix (rows sum to ICC PCS D50 = [0.9642, 1.0, 0.8249]):
let m = CustomPrimaries::ACES_AP0.to_icc_d50_matrix_f64().unwrap();

§8. UltraHDR / ISO 21496-1 Gain Maps (DualLayerHdrBuf & gainmap::*)

use zenpixels_convert::gainmap::{
    GainMapApplyConfig, GainMapExtractConfig, GainMapOrientation, apply_gain_map_oriented,
    apply_gain_map_with, extract_gain_map_only,
};
use zenpixels_convert::{DualLayerHdrBuf, Orientation, PixelBuf, PixelFormat};

let cfg = GainMapExtractConfig::default();
let (gain_map, meta) = extract_gain_map_only(&sdr_base.as_view(), &hdr_alt.as_view(), &cfg, None)?;
let dual = DualLayerHdrBuf::new(sdr_base, gain_map, meta)?
    .compose_orientation(Orientation::Rotate90); // O(1) EXIF orientation update

let apply_bake = GainMapApplyConfig::from_display_boost_linear(2.5)
    .with_orientation(GainMapOrientation::Bake);
let hdr_baked = apply_gain_map_with(&dual.as_view(), &apply_bake, None)?;
assert_eq!(hdr_baked.orientation(), Orientation::Identity);

let apply_pass = GainMapApplyConfig::from_display_boost_linear(2.5)
    .with_orientation(GainMapOrientation::Passthrough);
let (hdr_stored, pending_orient) = apply_gain_map_oriented(&dual.as_view(), &apply_pass, None)?;
assert_eq!(pending_orient, Orientation::Rotate90);

§9. Content Inspection & Lossless Compaction (compact)

Inspect actual pixel data to find whether alpha, chroma, or full U16 precision are needed, and compact without loss (plain free functions — no extension traits to import):

use zenpixels_convert::{
    AlphaCompaction, AlphaMode, CompactOutcome, PixelBuf, PixelFormat, SampleLayout,
    CompactionReport, compact_in_place, compact_to_buf,
};

// Inspect & allocating compaction (e.g. neutral opaque RGBA16 -> GRAY8):
let report = CompactionReport::measure(&rgba16_neutral.as_view());
assert_eq!(report.requires_alpha(), Some(false));
assert_eq!(report.requires_chroma(), Some(false));
assert_eq!(report.requires_u16_precision(), Some(false));
let compact = compact_to_buf(&rgba16_neutral.as_view())?.unwrap();
assert_eq!(compact.format().layout(), SampleLayout::GRAY8);

// Zero-reallocation in-place compaction on opaque RGBA8:
// 1. Retag alpha to AlphaMode::Opaque without shifting lanes:
let outcome = compact_in_place(&mut rgba8_opaque, AlphaCompaction::RetagOpaque)?;
assert_eq!(outcome, CompactOutcome::Compacted);
assert_eq!(rgba8_opaque.format().color().alpha(), AlphaMode::Opaque);
assert_eq!(rgba8_opaque.format().layout(), SampleLayout::RGBA8);

// 2. Physically drop unused alpha lane in-place (reusing the same allocation):
let outcome = compact_in_place(&mut rgba8_opaque, AlphaCompaction::DropUnusedLanes)?;
assert!(outcome.is_compacted());
assert_eq!(rgba8_opaque.format().layout(), SampleLayout::RGB8);

§10. Interop (rgb, imgref, image 0.25)

Enable features = ["imgref", "image"] on zenpixels:

use imgref::ImgVec;
use rgb::Rgb;
use zenpixels::{ColorSpace, PixelBuf, PixelFormat};

// `imgref` round-trip (note `ImgVec::new(pixels, width, height)` and `img[(x_usize, y_usize)]`):
let img_ref = buf.as_view().as_imgref::<Rgb<u8>>()?;
let top_left = img_ref[(0usize, 0usize)];
let owned_img = ImgVec::new(vec![top_left; 4], 2, 2);
let back_from_imgref = PixelBuf::from_imgvec(owned_img, ColorSpace::SRGB)?;

// `image` 0.25 round-trip (propagates CICP color space automatically):
let dyn_img = buf.into_dynamic_image()?;
let back_from_image = PixelBuf::from_dynamic_image(dyn_img.clone())?;
// Or attach an explicit ColorSpace (e.g. Display P3):
let p3_from_image = PixelBuf::from_dynamic_image_with_color(dyn_img, ColorSpace::DISPLAY_P3)?;

§11. Quick Glossary

TermMeaning in zenpixels 0.5
whereat::At<E>Error wrapper pairing the typed error E with source-location trace frames. Match the inner enum via *err.error() (or take (E, trace) via err.decompose()).
SampleClaimsProven or caller-asserted content invariants (all_opaque, all_grayscale, binary_alpha, float, depth). Measured via view.measure_claims() / into_opaque_verified(), seeded by PixelBuf::new/new_signal_white/new_raw_zeroed, or asserted via assume_claims / with_assumed_claims / policy.with_source_claims. Cleared on mutable access.
ColorOriginFile-level provenance (assumed(), from_cicp, from_icc, from_icc_and_cicp) recording how the file originally signaled color, distinct from the buffer’s active ColorSpace.
OutputSignalingEncoder signaling policy (Auto, PreserveOrigin, CicpOnly, IccOnly, CicpAndIcc, ExplicitIcc, Strip) controlling which CICP/ICC metadata OutputPlan emits alongside encoded pixels.
CICP / ITU-T H.2734-byte wire code (color_primaries, transfer_characteristics, matrix_coefficients, full_range) used in PNG, AVIF, HEIF, JPEG XL, and video. CicpTag also supports the 44-byte ICC.1 custom-primaries amendment.
MatrixCoefficients1-byte lossless wrapper around an ITU-T H.273 Table 4 matrix code (BT709, BT601, BT2020_NCL, IDENTITY, ICTCP, or any unknown from_code(u8)), attached to PlanarBuf / PlanarView / PlanarViewMut.
SampleStrideNewtype (SampleStride(n)) expressing a plane row stride in scalar samples (not bytes) for Plane*::from_samples_strided.
SignalRangeInteger code swing: Full (0..=255 / 0..=65535) vs Narrow (video “limited” / studio swing: 16..=235 / 4096..=60160).
AlphaModeNone (no alpha channel), Opaque (alpha slot present and logically all-max), Straight (unpremultiplied / unassociated), Premultiplied (associated), Undefined (ignored RGBx/BGRx padding byte).
BitPackingHow coded integers sit inside U8/U16/U32 storage: Full, Lsb { bits } (U10_LSB), Msb { bits } (P010), or packed-word Bitfields (RGB565, RGB10A2).
CodePlaneZero-copy borrowed reader (CodePlaneMut writer) exposing raw coded integer samples (0..=1023, etc.) from bit-packed or multi-component planes without color conversion.
ChromaSitingSubsampled chroma sample position relative to luma pixels (also called chroma location): Unknown, Center (JPEG), Left (H.264/HEVC/AV1), TopLeft (BT.2020), Top, BottomLeft, Bottom.
Nits & DiffuseWhiteTyped luminance in cd/m² (Nits::new_positive(100.0).unwrap() or const Nits::new_positive_or_panic(100.0)). DiffuseWhite anchors SDR paper white in HDR workflows (e.g. DiffuseWhite::BT2408 = 203 cd/m²).
PeakSourceHow HDR→SDR tone mapping obtains source peak luminance on whole-image plans: Measured (streaming O(1) scan when needed), Declared (MaxCLL / MasteringDisplay), or Fixed(Nits).
HlgModeDistinguishes HlgMode::Scene (scene-referred ARIB STD-B67, representable in 4-byte CICP) from HlgMode::Display(HlgRendering) (BT.2100 display-rendered at e.g. 1000 nits; cannot be carried by CICP alone).
FormatCow<'a>Borrow-or-share PixelFormat wrapper inside views (Borrowed(&'a PixelFormat) for 0-alloc views vs Owned(Arc<PixelFormat>) for dynamic specs).
try_cow_view_mut / make_mutFallible copy-on-write (CoW) promotion for PixelBuf / PlaneBuf / PlanarBuf backed by immutable external storage (Arc<[u8]>, &'static [u8], FFI pools).