Skip to main content

ImageOptions

Struct ImageOptions 

Source
pub struct ImageOptions { /* private fields */ }
Expand description

How a video frame is encoded as a still image: its format, color handling, bit depth, alpha, HDR policy, size and codec effort.

Every video frame type encodes with it, whether owned, captured or borrowed for sending, through encode_image, encode_image_to and encode_image_data_url, for example VideoFrame::encode_image. Construct these settings with ImageOptions::new(format).

use grafton_ndi::{PixelFormat, VideoFrame, YuvMatrix, image_encoding::{ColorPolicy, Downscale, ImageFormat, ImageOptions, YuvRange}};

let frame = VideoFrame::builder()
    .resolution(64, 36)
    .pixel_format(PixelFormat::Uyvy)
    .data([128, 16, 128, 16].repeat(64 * 36 / 2))
    .build()?;

// A quarter-size JPEG thumbnail.
let thumbnail = ImageOptions::new(ImageFormat::Jpeg(85)).downscale(Downscale::Quarter);
let jpeg = frame.encode_image(&thumbnail)?;

// A source known to label its color wrongly.
let options = ImageOptions::new(ImageFormat::Png)
    .color(ColorPolicy::Override { matrix: YuvMatrix::Bt601, range: YuvRange::Limited });
let png = frame.encode_image(&options)?;

PNG and JPEG preserve picture aspect in relative pixel-density tags (PNG pHYs and JPEG JFIF) whenever the output needs non-square pixels. This includes square-pixel sources whose partial downscale blocks change the stored width/height ratio. Pixel dimensions and samples are unchanged. Outputs needing square pixels retain their default density behavior; equivalent implicit and explicit square-pixel sources produce identical bytes. Viewers may ignore these tags. WebP carries no pixel-shape tag. PNG and JPEG choose the positive u16 density pair whose vertical-to-horizontal ratio is closest to the required pixel aspect.

§Formats

Every uncompressed PixelFormat encodes: the four 8-bit RGB formats, and the YUV formats UYVY, UYVA, P216, PA16, NV12, I420, YV12, NA48, NB48, NA4G and NB4G, which are converted to RGB. Rows are read in place, skipping any row padding.

OutputChannelsBits a channel
PNG, AlphaMode::KeepRGBA if the source has alpha, otherwise RGB8 or 16
PNG, AlphaMode::DiscardRGB8 or 16
JPEGYCbCr; alpha is dropped8
Lossless WebPRGBA if the source has alpha and it is kept, otherwise RGB8
Lossy WebPLossy color, exact alpha unless discarded8

§Color

By default, YUV frames use limited range and repeated chroma, with the matrix in readable ndi_color_info metadata (ColorInfo), or BT.709 when untagged. ColorPolicy::Override replaces the matrix and range. See ColorPolicy for malformed metadata handling.

The SDK’s own YUV-to-RGB conversion always uses BT.709 limited range, whatever the tag says. RGB-received frames already carry that conversion: encoding keeps their RGB pixels, so the tag’s matrix can no longer be applied. Readable tags still govern color admission and the PNG cICP chunk. ReceiverColorFormat::UyvyBgra and UyvyRgba keep opaque sources in YUV, but deliver BGRA or RGBA for sources with alpha. When a tagged source may carry alpha, use ReceiverColorFormat::Fastest for UYVA or Best for UYVA or PA16. Best also retains high bit depth and HDR code values. Both deliver individual fields even with allow_video_fields(false), so interlaced snapshots may need field assembly.

§HDR

A frame tagged with the PQ or HLG transfer function is refused unless HdrPolicy::CodeValues asks for its code values, which only PNG can carry, tagged so that an HDR-aware viewer shows them correctly. Nothing is tone-mapped. Receive YUV with ReceiverColorFormat::Best to retain high bit depth and HDR code values: an RGB-received frame already holds the SDK’s BT.709 limited-range conversion, which encoding at 16 bits cannot undo. The passed-through tag still governs color admission and the PNG cICP chunk. Frames with BT.2020 primaries also require tagged PNG output. See HdrPolicy.

§Performance

Encoding is synchronous CPU work. Compare formats, PNG compression and lossy WebP effort on representative content at acceptable visual quality. Lower Self::webp_effort and disable Self::webp_sharp_yuv when prioritizing latency independently of quality; measure the result and bound concurrent encoding jobs. Neither setting provides a time or memory limit.

Async code runs the encoder on a blocking thread, with an owned frame:

use grafton_ndi::{image_encoding::{ImageFormat, ImageOptions}};

let options = ImageOptions::new(ImageFormat::WebpLossless);
let webp = tokio::task::spawn_blocking(move || frame.encode_image(&options)).await??;

§Memory

PNG and JPEG convert one output row at a time, so conversion scratch does not grow with frame height. PNG borrows contiguous full-size 8-bit RGBA rows or retains one row; JPEG converts into the codec’s rows and retains its final component row to avoid converting padding requests again. WebP encodes from one buffer, so it holds the whole converted image, unless full-size contiguous RGBA can be borrowed with alpha kept. Lossless WebP uses three channels when the source has no alpha or alpha is discarded. Lossy WebP uses four channels, with opaque alpha in those cases. Both WebP formats buffer the complete encoded image before writing it. Codec state and encoded output take memory besides. Each concurrent encode owns its own buffers, so worker and queue limits matter alongside compressed image size.

§Errors

Setters never fail; the encoding methods check the options with the frame, before anything is written.

ProblemError
A JPEG quality outside 1 to 100Error::InvalidInput
A lossy WebP quality outside 0 to 100Error::InvalidInput
A lossy WebP effort outside 0 to 6Error::InvalidInput
JPEG or WebP with SampleDepth::SixteenError::InvalidInput
JPEG or WebP for a frame that needs a color tag (BT.2020 primaries, or PQ or HLG with HdrPolicy::CodeValues)Error::InvalidInput
A PQ or HLG frame with HdrPolicy::RefuseError::InvalidFrame
Unreadable ndi_color_info with ColorPolicy::SdkError::InvalidFrame
An image wider or taller than JPEG’s 65,535, lossless WebP’s 16,384 or lossy WebP’s 16,383 pixelsError::InvalidFrame
Writing or flushing the writer given to encode_image_to failsError::Io
Conversion scratch cannot be allocatedError::AllocationFailed
The lossy WebP encoder cannot allocate its working storageError::InvalidFrame (crate::FrameDefect::EncodingFailed)
The codec fails for another reasonError::InvalidFrame

ImageOptions holds settings only, no buffers, so one value serves any number of threads.

Implementations§

Source§

impl ImageOptions

Source

pub fn format(self, format: ImageFormat) -> Self

Replace the output format, preserving every other encoding setting.

Source

pub fn configured_format(&self) -> ImageFormat

Requested encoded image format.

Source

pub fn configured_color(&self) -> ColorPolicy

Requested color conversion policy.

Source

pub fn configured_depth(&self) -> SampleDepth

Requested bits per channel.

Source

pub fn configured_alpha(&self) -> AlphaMode

Requested alpha handling.

Source

pub fn configured_hdr(&self) -> HdrPolicy

Requested HDR handling.

Source

pub fn configured_downscale(&self) -> Downscale

Requested image downscale factor.

Source

pub fn configured_png_compression(&self) -> PngCompression

Requested PNG compression level.

Source

pub fn configured_webp_effort(&self) -> u8

Requested lossy WebP compression effort (default 4).

Source

pub fn configured_webp_sharp_yuv(&self) -> bool

Whether lossy WebP uses SharpYUV color conversion (default true).

Source

pub fn new(format: ImageFormat) -> Self

Options for format, with every other setting at its default: ColorPolicy::Sdk, SampleDepth::Eight, AlphaMode::Keep, HdrPolicy::Refuse, Downscale::Off, PngCompression::Balanced, lossy WebP effort 4 and SharpYUV enabled.

Source

pub fn color(self, policy: ColorPolicy) -> Self

Choose how YUV frames are converted to RGB. The default is ColorPolicy::Sdk.

Source

pub fn depth(self, depth: SampleDepth) -> Self

Choose the bits a channel of the image: SampleDepth::Sixteen needs ImageFormat::Png. The default is SampleDepth::Eight.

Source

pub fn alpha(self, alpha: AlphaMode) -> Self

Choose whether a PNG or WebP image has an alpha channel. JPEG never has one. The default is AlphaMode::Keep.

Source

pub fn hdr(self, hdr: HdrPolicy) -> Self

Choose what happens to a frame tagged PQ or HLG. The default is HdrPolicy::Refuse.

Source

pub fn downscale(self, by: Downscale) -> Self

Reduce the image by 2, 4 or 8 in each direction. The default is Downscale::Off.

Source

pub fn png_compression(self, level: PngCompression) -> Self

Choose how hard PNG compresses. It has no effect on JPEG or WebP. The default is PngCompression::Balanced.

Source

pub fn webp_effort(self, effort: u8) -> Self

Choose lossy WebP’s compression effort, independently of color quality: 0 is fastest, 6 spends the most effort, and the default is 4. Higher effort generally trades CPU time for smaller output; measure your content. Alpha remains exact at every effort.

Values outside 0 to 6 return Error::InvalidInput when encoding lossy WebP, before anything is written. This setting has no effect on PNG, JPEG or lossless WebP.

Source

pub fn webp_sharp_yuv(self, enabled: bool) -> Self

Choose lossy WebP’s RGB-to-YUV conversion. The default, true, uses SharpYUV for sharper chroma edges at an additional CPU cost. False uses the faster standard conversion; alpha remains exact.

Combine webp_effort(0) and webp_sharp_yuv(false) when prioritizing encoding latency. Neither setting imposes a time or memory limit. This setting has no effect on PNG, JPEG or lossless WebP.

Trait Implementations§

Source§

impl Clone for ImageOptions

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ImageOptions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for ImageOptions

Source§

impl Hash for ImageOptions

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for ImageOptions

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ImageOptions

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.