pub struct BorrowedVideoFrame<'buf> { /* private fields */ }Expand description
A borrowed video frame that references external pixel data.
crate::Sender::send_video sends it synchronously; the buffer can be reused
as soon as the call returns. crate::Sender::submit_video_copy copies its
pixels and metadata into an owned frame for the asynchronous pipeline.
The x86 builds of the SDK read a little past the end of many UYVY and
UYVA frames. Where PixelFormat::send_tail_room is nonzero, borrowed
frames of these formats are copied into packed storage with a zeroed tail
by default, so caller padding and trailing bytes cannot affect the picture.
BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail opts into
direct sending when sufficient initialized memory follows the pixels.
Self::sends_in_place reports whether a copy is needed.
Create one with Self::builder. Construction borrows without
allocation and validates the entire supported uncompressed layout once.
Copying it copies only the borrows.
Implementations§
Source§impl<'buf> BorrowedVideoFrame<'buf>
impl<'buf> BorrowedVideoFrame<'buf>
Sourcepub fn pixel_format(&self) -> PixelFormat
pub fn pixel_format(&self) -> PixelFormat
Get the pixel format.
It is a supported uncompressed format, validated when the frame was constructed.
Sourcepub fn frame_rate(&self) -> FrameRate
pub fn frame_rate(&self) -> FrameRate
Get the frame rate.
Sourcepub fn picture_aspect_ratio(&self) -> PictureAspectRatio
pub fn picture_aspect_ratio(&self) -> PictureAspectRatio
Get the picture aspect ratio, width over height as displayed; 0.0
means square pixels.
Sourcepub fn scan_type(&self) -> ScanType
pub fn scan_type(&self) -> ScanType
Get the scan type: progressive, interlaced, or a single field.
Sourcepub fn line_stride_bytes(&self) -> usize
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.
It is the stride the frame was built with, which can include row padding.
Sourcepub fn metadata(&self) -> Option<&str>
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.
Sourcepub fn metadata_status(&self) -> FrameMetadataStatus
pub fn metadata_status(&self) -> FrameMetadataStatus
The metadata’s presence or the reason unreadable received text was withheld. Querying the cached status allocates nothing.
Sourcepub fn color_info(&self) -> Result<Option<ColorInfo>>
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"),
}Sourcepub fn plane(&self, index: usize) -> Option<VideoPlane<'_>>
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.
Its rows exclude the padding of the frame’s line stride, which
Self::storage includes, so the active pixels of a padded buffer
can be read in place.
Sourcepub fn planes(&self) -> VideoPlanes<'_> ⓘ
pub fn planes(&self) -> VideoPlanes<'_> ⓘ
Iterate planes in SDK memory order without allocating or copying.
Sourcepub fn timestamp(&self) -> Option<ReceivedTimestamp>
pub fn timestamp(&self) -> Option<ReceivedTimestamp>
The source-dependent timestamp of the received frame.
Application input has no received timestamp.
Sourcepub fn data(&self) -> Option<&[u8]>
pub fn data(&self) -> Option<&[u8]>
Contiguous active pixels, or None when row or plane padding separates
them. Use Self::plane and Self::planes for padded active rows, or
Self::storage for the validated storage including row padding.
Sourcepub fn to_owned(&self) -> VideoFrame
pub fn to_owned(&self) -> VideoFrame
Copy this borrowed frame into a validated owned frame.
Active pixels are copied into tightly packed planes; row padding is
skipped and the owned stride can shrink. Metadata is copied separately;
no reference to the source is retained. Self::copy_into makes the
same copy into an existing frame, reusing its allocations.
The copy cannot fail: building the frame validated everything it relies on, and the packed layout of a valid frame is valid.
Sourcepub fn copy_into(&self, destination: &mut VideoFrame)
pub fn copy_into(&self, destination: &mut VideoFrame)
Copy this borrowed frame into destination, reusing its allocations.
destination ends up exactly as Self::to_owned would have
returned it, whatever it held before: tightly packed active rows,
format, dimensions, frame rate, aspect ratio, scan type, timecode and
metadata, and no timestamp. No reference to the source is retained.
Its pixel buffer is reused when its capacity holds the packed frame and the SDK tail room required by its format and scan type, including extra strides for interlaced UYVY/UYVA when needed. Otherwise it is replaced by one allocation of exactly that size. Its metadata string is reused when its capacity holds the new text and its terminator; otherwise it grows once. With sufficient pixel and metadata capacity, subsequent copies allocate nothing. The copy makes no SDK call and can run on any thread. Copies without metadata retain the destination’s text allocation for later frames.
§Example
A copy-and-send loop that stops allocating once two frames exist.
crate::Sender::submit_video keeps the frame it is given until the next
send, and returns the previous one, which the SDK has finished with:
that frame is the destination of the next copy.
crate::Sender::submit_video_copy keeps its own reusable frames for
this copy instead.
let mut sender = Sender::new(&ndi, &SenderOptions::new("Copied"))?;
// 64 pixels per row, padded to a 512-byte stride.
let mut buffer = vec![0u8; 512 * 32];
let mut spare: Option<VideoFrame> = None;
for shade in 0..=255u8 {
buffer.fill(shade); // the application draws into its own buffer
let frame = BorrowedVideoFrame::builder(&buffer, 64, 32, PixelFormat::Bgra)
.line_stride_bytes(512)
.build()?;
let owned = match spare.take() {
Some(mut reused) => {
frame.copy_into(&mut reused); // no allocation
reused
}
None => frame.to_owned(), // the first two frames only
};
spare = sender.submit_video(owned)?;
}
sender.reclaim_video();Sourcepub fn sends_in_place(&self) -> bool
pub fn sends_in_place(&self) -> bool
Whether crate::Sender::send_video sends this frame from its buffer,
without copying its pixels.
UYVY and UYVA frames are copied by default wherever
PixelFormat::send_tail_room is nonzero. Opting in with
BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail allows
direct sending if enough room follows the last pixel. The last row’s
padding and the bytes of the builder’s buffer after the frame count
towards the room after that opt-in. An interlaced or single-field
frame of those formats whose height is not a multiple of four needs
two line strides more.
Where the SDK reads frames exactly, which is 64-bit ARM Linux, the room is zero and every frame sends in place.
§Example
let uyvy = PixelFormat::Uyvy;
let room = uyvy.send_tail_room();
let exact = vec![0u8; 720 * 480 * 2];
let frame = BorrowedVideoFrame::builder(&exact, 720, 480, uyvy).build()?;
// Copied wherever the SDK needs room after the frame.
assert_eq!(frame.sends_in_place(), room == 0);
let longer = vec![0u8; 720 * 480 * 2 + room];
let default = BorrowedVideoFrame::builder(&longer, 720, 480, uyvy).build()?;
assert_eq!(default.sends_in_place(), room == 0);
let in_place = BorrowedVideoFrame::builder(&longer, 720, 480, uyvy)
.allow_send_from_padding_and_tail(true)
.build()?;
assert!(in_place.sends_in_place());
assert_eq!(in_place.data().unwrap().len(), 720 * 480 * 2);
let owned = VideoFrame::builder()
.resolution(720, 480)
.pixel_format(uyvy)
.build()?;
assert!(owned.sends_in_place());Sourcepub fn encode_image(&self, options: &ImageOptions) -> Result<Vec<u8>>
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.
It encodes the application’s own buffer in place, padded rows included, so a program can keep a still of what it sends without copying the frame.
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)?;Sourcepub fn encode_image_to<W: Write>(
&self,
options: &ImageOptions,
out: W,
) -> Result<()>where
Self: Sized,
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`.
}Sourcepub fn encode_image_data_url(&self, options: &ImageOptions) -> Result<String>
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<'buf> BorrowedVideoFrame<'buf>
impl<'buf> BorrowedVideoFrame<'buf>
Sourcepub fn builder(
data: &'buf [u8],
width: u32,
height: u32,
pixel_format: PixelFormat,
) -> BorrowedVideoFrameBuilder<'buf>
pub fn builder( data: &'buf [u8], width: u32, height: u32, pixel_format: PixelFormat, ) -> BorrowedVideoFrameBuilder<'buf>
Configure a checked borrowed frame over data.
data may be longer than the frame: the frame is its start, and
Self::storage never includes the rest. For UYVY/UYVA where the SDK
needs tail room, the default send copies active rows only, even when
data includes extra room. Direct sending requires an explicit
BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail opt-in.
Its defaults are the packed line stride, 60/1 frames per second,
square pixels (picture aspect ratio 0.0), progressive scan, Timecode::SYNTHESIZE
and no metadata. All validation occurs in
BorrowedVideoFrameBuilder::build.
§Example
let buffer = vec![0u8; 1920 * 1080 * 4]; // BGRA buffer
let frame = BorrowedVideoFrame::builder(&buffer, 1920, 1080, PixelFormat::Bgra)
.frame_rate(FrameRate::new(30_000, 1_001)?)
.build()?;
assert_eq!(frame.line_stride_bytes(), 1920 * 4);Sourcepub fn storage(&self) -> &[u8] ⓘ
pub fn storage(&self) -> &[u8] ⓘ
Get the pixel data: exactly the frame’s validated storage, including
any row padding. Bytes of the source buffer beyond the frame are not
part of it. Self::plane and Self::planes borrow the active
rows alone.
Sourcepub fn with_timecode(self, timecode: Timecode) -> Self
pub fn with_timecode(self, timecode: Timecode) -> Self
Return this frame with timecode.
§Example
let buffer = vec![0u8; 1920 * 1080 * 2];
let frame = BorrowedVideoFrame::builder(&buffer, 1920, 1080, PixelFormat::Uyvy)
.build()?
.with_timecode(Timecode::from_ticks(10_000_000));
assert_eq!(frame.timecode().ticks(), 10_000_000);Trait Implementations§
Source§impl<'buf> Clone for BorrowedVideoFrame<'buf>
impl<'buf> Clone for BorrowedVideoFrame<'buf>
impl<'buf> Copy for BorrowedVideoFrame<'buf>
Source§impl<'buf> Debug for BorrowedVideoFrame<'buf>
impl<'buf> Debug for BorrowedVideoFrame<'buf>
Source§impl<'buf> VideoSource for BorrowedVideoFrame<'buf>
impl<'buf> VideoSource for BorrowedVideoFrame<'buf>
Source§fn pixel_format(&self) -> PixelFormat
fn pixel_format(&self) -> PixelFormat
Source§fn frame_rate(&self) -> FrameRate
fn frame_rate(&self) -> FrameRate
Source§fn picture_aspect_ratio(&self) -> PictureAspectRatio
fn picture_aspect_ratio(&self) -> PictureAspectRatio
Source§fn line_stride_bytes(&self) -> usize
fn line_stride_bytes(&self) -> usize
Source§fn metadata(&self) -> Option<&str>
fn metadata(&self) -> Option<&str>
Self::metadata_status.Source§fn metadata_status(&self) -> FrameMetadataStatus
fn metadata_status(&self) -> FrameMetadataStatus
Source§fn color_info(&self) -> Result<Option<ColorInfo>>
fn color_info(&self) -> Result<Option<ColorInfo>>
ndi_color_info description without copying metadata. Read moreSource§fn plane(&self, index: usize) -> Option<VideoPlane<'_>>
fn plane(&self, index: usize) -> Option<VideoPlane<'_>>
Source§fn planes(&self) -> VideoPlanes<'_> ⓘ
fn planes(&self) -> VideoPlanes<'_> ⓘ
Source§fn timestamp(&self) -> Option<ReceivedTimestamp>
fn timestamp(&self) -> Option<ReceivedTimestamp>
Source§fn data(&self) -> Option<&[u8]>
fn data(&self) -> Option<&[u8]>
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
fn to_owned(&self) -> VideoFrame
Source§fn copy_into(&self, destination: &mut VideoFrame)
fn copy_into(&self, destination: &mut VideoFrame)
copy_into. A copy
without metadata retains the destination’s text allocation.