Migrating from zenpixels 0.2 / 0.4 to 0.5

zenpixels 0.5 and zenpixels-convert 0.5 consolidate the 0.2 and 0.4 APIs around a single unified descriptor (PixelFormat), type-erased zero-copy buffers with external storage ownership (PixelBuf + ByteStorage), zero-allocation borrowed views (PixelView<'a> / PixelViewMut<'a> taking &'a PixelFormat), and stateless Send + Sync row/image conversion plans (RowPlan, ImagePlan, OutputPlan).

Both crates remain #![forbid(unsafe_code)] and support no_std + alloc (disable default std feature).


§1. Descriptor & Concept Map

In 0.5, the old layout-only PixelFormat became SampleLayout. The new PixelFormat pairs a layout with its color meaning. Encoder capability tables use const SUPPORTED: &[PixelFormat], so negotiation compares both layout and color.

0.2 (e96e4e9c) / 0.4 (666814ab)0.5Notes
PixelFormat::Rgb8 + ChannelType + ChannelLayoutSampleLayout::RGB8 (SampleType, ChannelOrder, BitPacking)Physical byte/sample layout only; cannot authorize a color conversion
PixelDescriptor::RGB8_SRGBPixelFormat::RGB8_SRGB (owned), or &formats::RGB8_SRGB ('static ref)Both include color; use PixelFormat::from_layout_assuming_color only when intentionally assuming default color for a raw layout
PixelDescriptor + ColorContext (ICC)PixelFormat::new(layout, ColorSpace::from_icc(profile, alpha, intent)?)? + optional ColorOriginAttach active ICC with checked PixelFormat::new. Preserve the original profile bytes in ColorOrigin. Use PixelFormat::new_const for checked constant construction
TransferFunction / ColorPrimariesTransfer / Primaries + CicpTagLossless H.273 (11 CP, 16 TC, 9 MC) + ICC.1 cicpType 44-byte custom-primaries amendment (CicpTag, CustomPrimaries::{ACES_AP0, ACES_CG, PROPHOTO_RGB}, Annex 1 to_icc_d50_matrix_f64); explicit Transfer::Hlg(HlgMode::Scene | HlgMode::Display(HlgRendering))
PixelBuffer<P, S>PixelBufType-erased, stride-preserving, fallible (into_tight_rows), O(1) zero-copy into_crop, symmetric crop_view/crop_view_mut/sub_rows/sub_rows_mut, direct row/row_mut, carries Orientation; supports external storage (from_external*), new_for_interop, new_signal_white, fast new_raw_zeroed + into_opaque_verified/assume_opaque, and explicit relabel_color/relabel_format/reinterpret_bytes
PixelSlice<'a> / PixelSliceMut<'a>PixelView<'a> / PixelViewMut<'a>Borrowed strided views taking &'a PixelFormat (0 heap allocations; borrow &formats::* or any local spec; explicit new_with_format_cow when owning/sharing a FormatCow)
BandedPixelBuffer (0.4)BandedBufBounded row-band storage (BandSizing::{MaxBandBytes, RowsPerBand}, RowAlign, DEFAULT_MAX_BAND_BYTES) carrying Orientation for gigapixel images
MultiPlaneImage (0.2) / PlanarBuffer / PlanarSlice (0.4)PlanarBuf / PlanarView / PlanarViewMutAlways built (no planar feature); symmetric crop_view/crop_view_mut/crop/crop_mut/into_crop/sub_rows*; carry ColorSpace, typed MatrixCoefficients (matrix_coefficients), range_override/effective_range, alpha_override/effective_alpha, chroma_siting, crop_origin (new_with_crop_origin), hdr, origin, and orientation
AnyPlane / PlaneRef<T> / PlaneBuf<T> (0.4)PlaneView / PlaneViewMut / PlaneBufZero-copy typed codec APIs: tight 4-arg from_samples(samples, width, height, spec) and strided 5-arg from_samples_strided(..., SampleStride(n), spec); raw byte new / from_external take byte stride (stride_bytes() returns bytes)
CodePlaneCodePlane + CodePlaneMutUnconditional in zenpixels; read/write arbitrary bit-packed or P010 codes (InterleavedCodeLayout)
Dual-layer gain mapsDualLayerHdrBuf / DualLayerHdrView / DualLayerHdrBufPartsUnified base + gain-map + ISO 21496-1 metadata + orientation carrier (new_with_alternate_color for Alternate space)
ConvertOptions (0.2/0.4) + ConversionSpec (0.4)ConvertPolicyDefault is lossless() (never silently drops alpha/depth/range); explicit permissive(), working_linear(), display_sdr(...). All planners borrow &ConvertPolicy
RowConverter (0.2) / ConvertPlan + RowConverter (0.4)RowPlan + ImagePlanRowPlan is stateless, Send + Sync, zero heap allocation per convert_row / convert_row_at, takes resolved Option<Nits>; ImagePlan takes PeakSource
buf.to_rgb8() / slice.convert_to(...)view.to_rgb8_if_opaque()? / view.convert_to(&dst, &policy)?to_rgb8_if_opaque / to_gray8_if_opaque use DiscardIfOpaque (refuse unproven alpha discard); ImagePlan::convert/ImagePlan::convert_into default to PeakSource::Measured when HDR needs it (*_with_peak for explicit PeakSource)
scan_factsbuf.measure_claims() or view.measure_claims() with PixelScanExtattached_claims() reads attached claims. measure_and_attach_claims() replaces them with measured evidence. Use verify_claims to check specific claims against storage and check_samples / check_nominal_samples for pixel-level format or nominal bounds diagnostics.
white, with_white, try_with_whitediffuse_white, with_diffuse_white, try_with_diffuse_whiteThe luminance anchor is separate from the signal endpoint filled for RGB and gray by PixelBuf::new_signal_white.
OutputPlan / adapt_for_encodeOutputPlan::adapt_for_encode (OutputSignaling::{Auto, PreserveOrigin, CicpOnly, IccOnly, CicpAndIcc, ExplicitIcc, Strip}, ResolvedSignaling)Canonicalizes unverified AlphaMode::Opaque (including F64/wide/CMYKA/ICC/untagged); rejects MetadataOnly or conflicting-TRC ICC on structured Rgb/RgbCustom/Gray; rejects HlgMode::Display on dst under CicpOnly/Auto
PluggableCms + RowTransformMutCmsBackend + CmsTransformStateless Send + Sync row transforms; build_transform and ToneMapper::prepare take Option<&dyn how_far::Pulse>; built-in MoxCms and Lcms
CllMeasure / LightLevelHistogrammeasure_content_light_level, measure_histogram, measure_max_smoothedLightLevelHistogram::{bins, merge, quantile_nits, to_robust_content_light_level} + 3-tap smoothed peak

§2. Cargo Feature Changes

§zenpixels

Feature0.2 / 0.40.5
default["std", "icc"]["std", "icc"]
planaropt-inRemoved (planar, banded, and CodePlane types are always built)
perceptualopt-inRemoved (ColorSpace::Perceptual is always representable; math stays gated in zenpixels-convert/perceptual)
rgb, imgref, imagergb / imgref / imageUnchanged (imgref implies rgb; image uses image 0.25)
hashopt-inPortable endian/stride-independent XXH3-64 (xxhash-rust)

§zenpixels-convert

Feature0.2 / 0.40.5
defaultstd, icc-db, oklab, hdr-transfers, …["std", "fast-transpose", "oklab", "hdr-transfers", "gainmap"]
icc-dbdefault-onDefault-off (opt-in for full CICP -> ICC LZ4 bundle; compact P3/Rec.2020 profiles remain built-in)
gainmapseparate / experimentalDefault-on (ISO 21496-1 / UltraHDR gain-map reconstruction & extraction)
hdr-experimentalopt-inRemoved (use hdr-transfers, bt2446a, gainmap)
planar / introspection / zencms-liteopt-inRemoved
fastopt-inDefault-off (registers full SIMD kernels globally; library crates should leave off to preserve dead-stripping)
cms-moxcms / cms-lcmsopt-inPure-Rust MoxCms and Lcms CMS backends

§3. Policy Presets & Fallibility / Error Contracts

§ConvertPolicy Presets (Safe Default!)

Neither pinned 0.2 nor pinned 0.4 implemented Default on ConvertOptions. In 0.5, ConvertPolicy::default() equals ConvertPolicy::lossless() so callers never silently drop alpha, quantize bit depth, or rescale narrow/full range.

Presetdepthalphagamutrangetone_map_hdr_to_sdrallow_icc_substitutionNotes
lossless() / default()ForbidForbidPreserveExtendedForbidfalsefalseLoss-permission preset (allow_approximate: false); forbids RGB→Gray unless proven grayscale; does not claim universal mathematical invertibility of float transforms
permissive()RoundDiscardUncheckedClipConvertfalsetrueExplicit opt-in for unchecked lossy conversion
working_linear()RoundDiscardIfOpaquePreserveExtendedConvertfalsetrueDefaults diffuse_white to BT.2408 (203 cd/m²)
display_sdr(white, peak)RoundCompositeOnto(BLACK)ClipConverttruetrueEnables HDR→SDR tone mapping + HLG 1000-nit reference rendering

to_rgb8_if_opaque / to_gray8_if_opaque: Both convenience helpers target full-range sRGB RGB8 / encoded-Y’ GRAY8 under ConvertPolicy::permissive().with_alpha(AlphaPolicy::DiscardIfOpaque). Unproven straight/premultiplied alpha returns ConvertError::AlphaLossForbidden; pass proven-opaque inputs (via PixelScanExt::measure_claims / into_opaque_verified) or call ImagePlan::convert with AlphaPolicy::CompositeOnto / DiscardUnchecked.

§Fallibility Naming & Error Shapes


§4. Code Migration Examples

§Constructing Specs & Converting Rows

Before — zenpixels 0.2 (e96e4e9c):

use zenpixels::{PixelBuffer, PixelDescriptor};
use zenpixels_convert::{ConvertOptions, RowConverter};

let src = PixelBuffer::try_new(w, h, PixelDescriptor::RGB8_SRGB)?;
let mut conv = RowConverter::new_explicit(
    src.descriptor(),
    PixelDescriptor::RGBA8_SRGB,
    &ConvertOptions::permissive(),
)?;
conv.try_convert_row(src.as_slice().row(0), dst_row, w)?;

Before — zenpixels 0.4 (666814ab — note ConvertOptions had no permissive() or Default):

use zenpixels::{ConvertOptions, DepthPolicy, PixelBuffer, PixelDescriptor};
use zenpixels_convert::{ConversionSpec, ConvertPlan};

let src = PixelBuffer::try_new(w, h, PixelDescriptor::RGB8_SRGB)?;
let opts = ConvertOptions::retain_channels().with_depth_policy(DepthPolicy::Round);
let plan = ConvertPlan::build(
    src.descriptor().into(),
    PixelDescriptor::RGBA8_SRGB.into(),
    &ConversionSpec::new(opts),
)?;
let mut conv = plan.prepare(w)?;
conv.try_convert_row(src.as_slice().row(0), dst_row, w)?;

After — zenpixels 0.5:

use zenpixels::{PixelFormat, PixelBuf, formats};
use zenpixels_convert::{ConvertPolicy, RowPlan};

let src = PixelBuf::new(w, h, PixelFormat::RGB8_SRGB)?;
let plan = RowPlan::build(
    src.format(),
    &formats::RGBA8_SRGB,
    &ConvertPolicy::lossless(),
    None, // resolved_source_peak: Option<Nits>
)?;
plan.convert_row(src.row(0), dst_row, w)?;

For whole-image conversion, import PixelConvertExt and use src.convert_to(...) (defaults to PeakSource::Measured only when HDR tone mapping needs a peak; use convert_to_with_peak for explicit PeakSource) or the safe 8-bit helpers:

use zenpixels_convert::PixelConvertExt;
let linear = src.convert_to(
    &zenpixels_convert::formats::RGBF32_LINEAR,
    &ConvertPolicy::lossless(),
)?;
let rgb = linear.to_rgb8_if_opaque()?;
let gray = linear.to_gray8_if_opaque()?;

§Zero-Allocation Borrowed Views (&'a PixelFormat vs FormatCow)

Normal PixelView / PixelViewMut constructors take &'a PixelFormat so view construction never allocates:

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

// Zero heap allocation: borrow a static preset (or any local `PixelFormat`):
let view = PixelView::from_bytes(rgb_bytes, w, h, &formats::RGB8_SRGB)?;

// Only when a view must carry an owned/shared spec (e.g. a dynamically built custom spec),
// opt in explicitly via `new_with_format_cow` + `FormatCow`:
let view_cow = PixelView::new_with_format_cow(
    rgb_bytes, w, h, stride, FormatCow::from_owned(PixelFormat::RGB8_SRGB), // 0-alloc for presets!
)?;

§Zero-Copy External Owned Data into PixelBuf / PlaneBuf

External buffers (Vec<T>, Box<[T]>, Arc<[T]>, FFI allocations, memory-mapped slices, or custom pools) move into PixelBuf or PlaneBuf with zero copies via ByteStorage / ByteStorageMut:

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

// Built-in impls exist for Vec<u8>/Vec<u16>/Vec<f32>, Box<[T]>, Arc<[T]>, Arc<Vec<T>>, etc.
let shared: Arc<[u8]> = Arc::from(vec![255u8; 4 * 4 * 3]);
let mut buf = PixelBuf::from_external(shared, 4, 4, 12, PixelFormat::RGB8_SRGB)
    .map_err(|(err, _orig)| err)?;

// Read zero-copy:
let view = buf.as_view();

// Mutate via fallible copy-on-write (only copies if storage is immutable / shared):
let mut mut_view = buf.try_cow_view_mut()?;

For mutable zero-copy external ownership (in-place mutation without CoW), implement ByteStorageMut and construct via PixelBuf::from_external_mut or PlaneBuf::from_external_mut.

§Sound AlphaMode::Opaque Allocation & Fast Fill-Then-Retag

PixelBuf::new fills black (setting alpha to channel max on AlphaMode::Opaque), and PixelBuf::new_signal_white fills signal white. When a decoder or renderer overwrites every pixel and wants to skip the upfront alpha-fill pass:

use zenpixels::{PixelFormat, PixelBuf};

let mut buf = PixelBuf::new_raw_zeroed(w, h, PixelFormat::RGBA8_SRGB)?; // refuses AlphaMode::Opaque
// ... write all pixels including A = 255 ...
let opaque = buf.into_opaque_verified()?; // scans active pixels itself; or `assume_opaque()` / `into_opaque_filled()`

§RGB -> Gray Luma Domain (Encoded vs LinearLight)

ConvertPolicy defaults to LumaDomain::Encoded, matching JPEG/video Y' and zenpixels 0.2/0.4 defaults (neutral (v, v, v) maps bit-for-bit to v, sRGB (255, 0, 0) maps to 54, and U8 RGB/BGR/RGBA/BGRA -> Gray8 takes the direct SIMD fast path).

To request physical linear-light luminance (Y = w_r*R + w_g*G + w_b*B, where sRGB (255, 0, 0) maps to 127):

use zenpixels_convert::{ConvertPolicy, LumaDomain};

let policy = ConvertPolicy::permissive().with_luma_domain(LumaDomain::LinearLight);

§Encoder Output Adaptation (OutputPlan)

Read adapted pixels and color signaling through ready.pixels(), ready.cicp(), ready.icc(), and ready.hdr(). For ownership, ready.into_parts() returns the pixel carrier, resolved signaling, and HDR metadata. Call signaling.into_parts() to take the ICC bytes without copying.

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

// Quick one-shot adaptation over a `&[PixelFormat]` capability table (borrows zero-copy when compatible):
let (chosen, ready) = OutputPlan::adapt_for_encode(
    buf.as_view(),
    buf.origin(),
    &[PixelFormat::RGB8_SRGB, PixelFormat::RGBA8_SRGB],
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::Auto,
)?;

// Or build a reusable OutputPlan borrowing specs & policy (cloned internally into the plan):
let out_plan = OutputPlan::build(
    buf.format(),
    &formats::RGB8_SRGB,
    &ConvertPolicy::permissive(),
    PeakSource::Measured,
    OutputSignaling::Auto,
)?;

§Orientation Verb Table

Operation0.5 APIContract
Replace metadatawith_orientation(self, o) / set_orientation(&mut self, o)Sets pending orientation to o in O(1); no pixel movement
Compose metadatacompose_orientation(self, delta) (on all 9 carriers/views)Sets pending orientation to old.then(delta) in O(1) (includes flips)
Explicit physical transformapply_orientation(&view, o) / apply_orientation_owned(buf, o) / apply_orientation_banded(&bands, o, sizing)Physically transforms stored pixels by exactly o (does not compose pending orientation); output carries Orientation::Identity (apply_orientation_owned(_, Identity) stays zero-copy)
Explicit into caller sinkapply_orientation_into(&view, o, &mut dst) / apply_orientation_banded_into(...)Writes transformed pixels into caller-owned destination with zero allocation (does not change dst.orientation())
Bake pending orientationbake_orientation(&view) / bake_orientation_owned(buf) / bake_orientation_banded(&bands, sizing)Consumes pending orientation(), transforms pixels, emits Orientation::Identity (owned fast path is zero-copy on Identity)
Dual-layer physical bakegainmap::bake_dual_layer_orientation(&view) / gainmap::bake_dual_layer_orientation_after(&view, delta)Transforms both base & gain map by pending (or pending.then(delta)), emitting Orientation::Identity

§Pluggable CMS (MoxCms and Lcms)

use std::sync::Arc;
use zenpixels_convert::{ConvertPolicy, Lcms, MoxCms};

// Pure-Rust MoxCms (fast default; declines AbsoluteColorimetric, float D2B*/B2D* MPE,
// and unequal adjacent RGB TRCs so callers can fall back explicitly):
let mox_pol = ConvertPolicy::permissive().with_cms(Arc::new(MoxCms));

// Pure-Rust Lcms (full ICC.1 support including AbsoluteColorimetric, float MPE, Lab/XYZ, CMYK):
let lcms_pol = ConvertPolicy::permissive().with_cms(Arc::new(Lcms));

§Zero-Copy Planar Reconstruction, Compaction & Orientation

use zenpixels::{
    BandSizing, ChromaSiting, ColorSpace, MatrixCoefficients, PlanarView, PlaneFormat, PlaneRole,
    PlaneView, SampleLayout, SampleStride, SampleType,
};
use zenpixels_convert::{
    AlphaCompaction, PlanarReconstructionOptions, apply_orientation_banded,
    apply_orientation_banded_into, bake_orientation_owned, compact_in_place,
    PlanarConvertExt,
};

// Borrow codec-native typed planes zero-copy: tight 4-arg `from_samples(samples, w, h, spec)` or
// strided 5-arg `from_samples_strided(samples, w, h, SampleStride(stride_samples), spec)`.
// `plane.code_u32(x, y, 0)` takes component index `0` for 1-channel planes:
let py = PlaneView::from_samples_strided(y_slice, w, h, SampleStride(y_stride), PlaneFormat::new(PlaneRole::Y, SampleType::U8))?;
let pcb = PlaneView::from_samples_strided(cb_slice, cw, ch, SampleStride(c_stride), PlaneFormat::new(PlaneRole::Cb, SampleType::U8).with_subsampling(2, 2))?;
let pcr = PlaneView::from_samples_strided(cr_slice, cw, ch, SampleStride(c_stride), PlaneFormat::new(PlaneRole::Cr, SampleType::U8).with_subsampling(2, 2))?;
let planar = PlanarView::new(w, h, &[py, pcb, pcr])?
    .with_color(ColorSpace::SRGB)
    .with_matrix_coefficients(MatrixCoefficients::BT709)
    .with_chroma_siting(ChromaSiting::Center);

// Reconstruct directly to RGB8/RGBA8/BGR8/RGB16/RGBF32 with siting-exact Bilinear upsampling:
let rgb8 = planar.reconstruct_to_buf(SampleLayout::RGB8, &PlanarReconstructionOptions::bilinear())?;
let rgbf32 = planar.reconstruct_f32(&PlanarReconstructionOptions::bilinear())?;

// Bake pending buffer orientation (zero-copy when already Identity) or rotate banded buffers:
let mut display_buf = bake_orientation_owned(rgb8)?;
compact_in_place(&mut display_buf, AlphaCompaction::DropUnusedLanes)?;
let oriented = apply_orientation_banded(&src_bands, orient, BandSizing::DEFAULT)?;
apply_orientation_banded_into(&src_bands, orient, &mut dst_bands)?;

§Additional 0.5 Safety & Ergonomics Notes