Skip to main content

VideoFrame

Struct VideoFrame 

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

An owned video frame with validated dimensions, format, stride, and buffer size.

Owned frames contain tightly packed active pixels: copies of borrowed or received frames omit their row padding. Use Self::builder to create one for sending. Cloning copies the pixels, readable metadata and metadata status, including when received text was withheld.

The allocation that holds the pixels also holds the room the SDK needs after a frame of this layout and scan type, so an owned frame is sent in place. Construction, copies, pixel replacement and scan-type changes preserve this invariant; sending requires no pixel copy or allocation growth.

Implementations§

Source§

impl VideoFrame

Source

pub fn width(&self) -> u32

Get the frame width in pixels.

Source

pub fn height(&self) -> u32

Get the frame height in pixels.

Source

pub fn pixel_format(&self) -> PixelFormat

Get the pixel format.

It is a supported uncompressed format, validated when the frame was constructed.

Source

pub fn frame_rate(&self) -> FrameRate

Get the frame rate.

Source

pub fn picture_aspect_ratio(&self) -> PictureAspectRatio

Get the picture aspect ratio, width over height as displayed; 0.0 means square pixels.

Source

pub fn scan_type(&self) -> ScanType

Get the scan type: progressive, interlaced, or a single field.

Source

pub fn timecode(&self) -> Timecode

Get the timecode.

A built frame starts with Timecode::SYNTHESIZE; a copy of a received frame keeps the timecode it arrived with.

Source

pub fn line_stride_bytes(&self) -> usize

Get the validated first-plane line stride in bytes: the distance between the starts of consecutive rows of the first plane.

An owned frame’s rows are tightly packed, so this is the packed stride.

Source

pub fn metadata(&self) -> Option<&str>

Get frame metadata as UTF-8 text, if present.

Empty metadata, Some(""), is distinct from none, None. Unreadable received text returns None; use Self::metadata_status to distinguish it from absent text.

Source

pub fn metadata_status(&self) -> FrameMetadataStatus

The metadata’s presence or the reason unreadable received text was withheld. Querying the cached status allocates nothing.

Source

pub fn color_info(&self) -> Result<Option<ColorInfo>>

Read the color description in the frame’s ndi_color_info metadata.

Returns Ok(None) when the frame has no metadata or no such element, which means BT.709 SDR with unknown primaries. See ColorInfo for what the element holds and how the SDK treats it. Image encoding reads the same description, so a program can check a frame, for an HDR transfer for example, before it encodes it.

§Errors

Error::InvalidFrame, naming the attribute and its value, when the element is malformed or truncated, gives a value outside the SDK’s list, or appears more than once with different values. Also returned when received metadata was withheld as FrameMetadataStatus::NotUtf8 or FrameMetadataStatus::Unterminated, including on an owned copy of that frame.

§Example
 match frame.color_info()? {
     Some(color) if color.is_hdr() => println!("HDR: {:?}", color.transfer()),
     Some(color) => println!("SDR, matrix {:?}", color.matrix()),
     None => println!("BT.709 SDR"),
 }
Source

pub fn plane(&self, index: usize) -> Option<VideoPlane<'_>>

Get one plane in SDK memory order, or None for an invalid index.

Plane order follows the pixel format, as for VideoPlane, whose rows exclude any row padding.

The rows of an owned frame have no padding.

Source

pub fn planes(&self) -> VideoPlanes<'_> ⓘ

Iterate planes in SDK memory order without allocating or copying.

Source

pub fn timestamp(&self) -> Option<ReceivedTimestamp>

The source-dependent timestamp of the received frame.

A frame has one only when it was copied from a received frame that carries one; frames built for sending have none.

Source

pub fn data(&self) -> &[u8] ⓘ

Get the frame data: every plane, tightly packed, in SDK plane order.

Source

pub fn to_owned(&self) -> VideoFrame

Copy this frame, its readable metadata and its metadata status into independent owned storage.

Source

pub fn copy_into(&self, destination: &mut VideoFrame)

Copy active pixels, header, timestamp and metadata into a reusable owned destination. Row padding is omitted; pixel and metadata capacity is reused.

let frame = VideoFrame::builder().resolution(2, 2).build()?;
let mut spare = VideoFrame::builder().resolution(2, 2).build()?;
frame.copy_into(&mut spare);
assert_eq!(frame.data(), spare.data());
Source

pub fn sends_in_place(&self) -> bool

Whether synchronous sending reads this frame directly without a wrapper pixel copy. This cached-layout query allocates nothing and makes no SDK call. Captured padding is never assumed initialized; captures needing row padding or extra SDK tail room use reusable staging.

Source

pub fn encode_image(&self, options: &ImageOptions) -> Result<Vec<u8>>

Encode the frame as an image, as options describe.

Every uncompressed pixel format encodes, as PNG, JPEG or lossless or lossy WebP. By default, YUV uses limited range, repeated chroma and the matrix in readable ndi_color_info, or BT.709 when untagged. RGB-received frames already hold the SDK’s BT.709 limited-range conversion, which ignores the tag; encoding cannot apply its matrix afterward. Tags still decide HDR refusal and the PNG cICP chunk. Receive YUV when the tagged matrix or original HDR code values matter. See ImageOptions for formats, color, HDR, bit depth, alpha, reduction, cost and memory.

Encoding is CPU work, tens to hundreds of milliseconds for a 1080p frame: async code runs it on a blocking thread with an owned frame.

§Errors

Returns Error::InvalidInput for unsuitable options, Error::InvalidFrame for frame or codec refusals, or Error::AllocationFailed for conversion scratch storage. The complete conditions are in the ImageOptions error table.

§Example
 use grafton_ndi::{image_encoding::{Downscale, ImageFormat, ImageOptions, PngCompression}};

 let options = ImageOptions::new(ImageFormat::Png)
     .png_compression(PngCompression::Fast)
     .downscale(Downscale::Half);
 let png = frame.encode_image(&options)?;
Source

pub fn encode_image_to<W: Write>( &self, options: &ImageOptions, out: W, ) -> Result<()>
where Self: Sized,

Encode the frame as an image, as options describe, writing it into out.

It encodes as encode_image does, into any writer, so a program that takes snapshots on a timer can reuse one output buffer. A file or socket should be wrapped in a BufWriter: the codecs write in small pieces. Both WebP formats buffer their complete encoded image before writing it; PNG and JPEG write as they encode. Success means every byte was written and out was flushed.

§Errors

As for encode_image, and Error::Io when out fails. Every check of the options and the frame happens before anything is written; after a later error, out may hold part of an image, which the caller discards.

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

 let options = ImageOptions::new(ImageFormat::Jpeg(85));
 let mut jpeg = Vec::new();
 for _ in 0..3 {
     jpeg.clear();
     frame.encode_image_to(&options, &mut jpeg)?;
     // Publish `jpeg`.
 }
Source

pub fn encode_image_data_url(&self, options: &ImageOptions) -> Result<String>

Encode the frame as an image, as options describe, in a base64 data URL for HTML or JSON: data:image/png;base64,, data:image/jpeg;base64, or data:image/webp;base64, and the image.

The string is allocated once, at its final length.

§Errors

As for encode_image.

§Example
 use grafton_ndi::{image_encoding::{Downscale, ImageFormat, ImageOptions}};

 let options = ImageOptions::new(ImageFormat::Jpeg(80)).downscale(Downscale::Quarter);
 let url = frame.encode_image_data_url(&options)?;
 println!("<img src=\"{url}\">");
Source§

impl VideoFrame

Source

pub fn builder() -> VideoFrameBuilder

Create a builder for a frame to send.

Its defaults are 1920x1080 BGRA at 60/1 frames per second, square pixels (picture aspect ratio 0.0), progressive scan, Timecode::SYNTHESIZE, no metadata and zero-filled pixels.

Source

pub fn set_timecode(&mut self, timecode: Timecode)

Set the timecode without reallocating the pixels.

Source

pub fn set_scan_type(&mut self, scan_type: ScanType)

Set the scan type without changing the frame’s validated layout.

Grows the pixel allocation if this scan type needs more SDK tail room. Existing capacity is reused and never shrunk, so switching among scan types allocates at most once after construction.

Source

pub fn set_frame_rate(&mut self, frame_rate: FrameRate)

Set the frame rate.

Source

pub fn set_picture_aspect_ratio(&mut self, ratio: PictureAspectRatio)

Set the picture aspect ratio, width over height as displayed; 0.0 means square pixels.

The validated ratio is stored without further checks.

Source

pub fn into_data(self) -> Vec<u8> ⓘ

Recover the original pixel vector, retaining its allocation and capacity.

The length covers pixels only; initialized SDK tail bytes remain in spare capacity and will be restored if the vector is built into a frame.

Source

pub fn swap_data(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Rejected<Vec<u8>>>

Replace pixels and recover the previous allocation for reuse.

The incoming vector follows the allocation rules of Self::replace_data.

§Errors

Returns data unchanged with Error::InvalidFrame when its length differs from the validated layout. The frame is unchanged.

Source

pub fn data_mut(&mut self) -> &mut [u8] ⓘ

Get mutable access to the frame data without changing the validated layout.

Source

pub fn replace_data(&mut self, data: Vec<u8>) -> Result<(), Rejected<Vec<u8>>>

Replace the owned frame data while preserving the validated layout.

The frame keeps data’s allocation when its spare capacity holds the layout and scan type’s room, which is nothing for most formats, and otherwise grows it once, which may move the pixels.

§Errors

Returns data, unused, with Error::InvalidFrame if it is not exactly the validated layout size. The frame is unchanged.

Source

pub fn set_metadata( &mut self, metadata: impl Into<String>, ) -> Result<(), Rejected<String>>

Replace frame metadata. Use Self::clear_metadata to remove it.

Valid replacement text sets FrameMetadataStatus::Text, including an empty string. Invalid replacement text leaves the existing metadata and its status unchanged.

§Errors

Returns the unchanged text in Rejected. Its reason is Error::InvalidCString if metadata contains an interior NUL byte, or Error::InvalidFrame if the emitted C string would exceed the metadata size cap. The NulError retains only the prefix through the first NUL; use Rejected::into_inner for the whole original string.

Source

pub fn clear_metadata(&mut self)

Remove frame metadata, setting FrameMetadataStatus::Absent and retaining its allocation for later copies.

Trait Implementations§

Source§

impl AvSyncFrame for VideoFrame

Source§

impl Clone for VideoFrame

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 VideoFrame

Source§

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

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

impl From<VideoFrame> for QueuedVideoFrame

Source§

fn from(v: VideoFrame) -> Self

Converts to this type from the input type.
Source§

impl VideoSource for VideoFrame

Source§

fn width(&self) -> u32

Frame width in pixels.
Source§

fn height(&self) -> u32

Frame height in pixels.
Source§

fn pixel_format(&self) -> PixelFormat

Validated uncompressed pixel format.
Source§

fn frame_rate(&self) -> FrameRate

Frame rate, including its rational representation.
Source§

fn picture_aspect_ratio(&self) -> PictureAspectRatio

Display width divided by height; zero means square pixels.
Source§

fn scan_type(&self) -> ScanType

Progressive, interlaced, or field scanning.
Source§

fn timecode(&self) -> Timecode

Frame timecode, or the sender’s synthesis sentinel.
Source§

fn line_stride_bytes(&self) -> usize

Distance in bytes between first-plane row starts.
Source§

fn metadata(&self) -> Option<&str>

UTF-8 frame metadata; an explicit empty string differs from no metadata. Unreadable received text is withheld; inspect Self::metadata_status.
Source§

fn metadata_status(&self) -> FrameMetadataStatus

Whether per-frame metadata is absent, readable, or withheld as unreadable.
Source§

fn color_info(&self) -> Result<Option<ColorInfo>>

Read the frame’s ndi_color_info description without copying metadata. Read more
Source§

fn plane(&self, index: usize) -> Option<VideoPlane<'_>>

One plane’s initialized active rows, excluding row padding.
Source§

fn planes(&self) -> VideoPlanes<'_> ⓘ

All initialized active planes in SDK order, without allocating.
Source§

fn timestamp(&self) -> Option<ReceivedTimestamp>

Source-dependent timestamp supplied by the SDK for a captured frame.
Source§

fn data(&self) -> Option<&[u8]>

Contiguous active pixels, or None when row/plane padding separates them. Padding and SDK trailing read room are never exposed through this slice.
Source§

fn to_owned(&self) -> VideoFrame

Copy active pixels and readable metadata into a new, tightly packed owned frame. Withheld metadata keeps its status without its text. Allocates pixel storage and, when present, readable metadata storage.
Source§

fn copy_into(&self, destination: &mut VideoFrame)

Copy active pixels and metadata into an owned destination, preserving the header and timestamp. Row padding is omitted. Pixel and metadata allocations are reused when their capacities/layouts permit; this has the same allocation behavior as a captured frame’s copy_into. A copy without metadata retains the destination’s text allocation.
Source§

fn sends_in_place(&self) -> bool

Whether synchronous sending can read this frame directly, without a wrapper pixel copy. The query allocates nothing and makes no SDK call. Read more
Source§

fn encode_image(&self, options: &ImageOptions) -> Result<Vec<u8>>

Encode this frame using the image format and conversion options.
Source§

fn encode_image_to<W: Write>( &self, options: &ImageOptions, out: W, ) -> Result<()>
where Self: Sized,

Encode into a writer, flushing it when encoding succeeds.
Source§

fn encode_image_data_url(&self, options: &ImageOptions) -> Result<String>

Encode this frame as a base64 data URL.

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.