grafton_ndi/frames/borrowed.rs
1//! Validated application media whose private fields retain their checked
2//! layouts, borrowed initialized storage and metadata together.
3
4use super::*;
5
6/// Validated planar floating-point audio borrowed from application storage.
7///
8/// Samples and optional NUL-terminated metadata are borrowed for the frame's
9/// lifetime. Synchronous sending and [`crate::audio_conversion::AudioConverter`]
10/// use the original channel stride without copying samples or allocating.
11/// Inspect channels with [`Self::channel_data`] or [`Self::channels`]; those
12/// slices exclude inter-channel padding.
13#[derive(Clone, Copy)]
14pub struct BorrowedAudioFrame<'buf> {
15 layout: ValidatedAudioLayout,
16 timecode: Timecode,
17 data: &'buf [f32],
18 metadata: Option<MetadataText<'buf>>,
19}
20
21// SAFETY: Private fields pair the f32 slice with its validated layout after
22// the builder checks its initialized extent. Its borrow keeps the slice and validated terminated
23// metadata alive and unchanged; the default descriptor uses only those parts.
24unsafe impl AudioParts for BorrowedAudioFrame<'_> {
25 fn layout(&self) -> &ValidatedAudioLayout {
26 &self.layout
27 }
28 fn audio_timecode(&self) -> Timecode {
29 self.timecode
30 }
31 fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> {
32 None
33 }
34 fn samples(&self) -> *const f32 {
35 self.data.as_ptr()
36 }
37 fn frame_metadata(&self) -> FrameMetadataRef<'_> {
38 FrameMetadataRef::from_text(self.metadata)
39 }
40}
41
42impl<'buf> BorrowedAudioFrame<'buf> {
43 /// Configure a borrowed planar frame with explicit sample rate and shape.
44 ///
45 /// Defaults to tightly packed channels, [`Timecode::SYNTHESIZE`] and no
46 /// metadata. A larger input slice is permitted; only the checked frame
47 /// extent is retained. All validation occurs in the builder's `build`.
48 ///
49 /// ```
50 /// use grafton_ndi::{AudioSource, BorrowedAudioFrame};
51 /// let samples = [1.0, 2.0, 99.0, 3.0, 4.0];
52 /// let frame = BorrowedAudioFrame::builder(&samples, 48_000, 2, 2)
53 /// .channel_stride_bytes(12)
54 /// .build()?;
55 /// let source: &dyn AudioSource = &frame;
56 /// assert_eq!(source.channels().collect::<Vec<_>>(), [&[1.0, 2.0][..], &[3.0, 4.0][..]]);
57 /// assert!(source.data().is_none());
58 /// # Ok::<(), grafton_ndi::Error>(())
59 /// ```
60 pub fn builder(
61 data: &'buf [f32],
62 sample_rate: u32,
63 num_channels: u32,
64 num_samples: u32,
65 ) -> BorrowedAudioFrameBuilder<'buf> {
66 BorrowedAudioFrameBuilder {
67 data,
68 sample_rate,
69 num_channels,
70 num_samples,
71 channel_stride_bytes: None,
72 timecode: Timecode::SYNTHESIZE,
73 metadata: None,
74 }
75 }
76
77 /// Return this frame with the supplied timecode; no samples are copied.
78 #[must_use]
79 pub fn with_timecode(mut self, timecode: Timecode) -> Self {
80 self.timecode = timecode;
81 self
82 }
83}
84
85/// Builder for [`BorrowedAudioFrame`]; no sample or metadata copies are made.
86#[derive(Clone, Copy)]
87pub struct BorrowedAudioFrameBuilder<'buf> {
88 data: &'buf [f32],
89 sample_rate: u32,
90 num_channels: u32,
91 num_samples: u32,
92 channel_stride_bytes: Option<usize>,
93 timecode: Timecode,
94 metadata: Option<&'buf CStr>,
95}
96
97impl fmt::Debug for BorrowedAudioFrameBuilder<'_> {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 f.debug_struct("BorrowedAudioFrameBuilder")
100 .field("sample_rate", &self.sample_rate)
101 .field("num_channels", &self.num_channels)
102 .field("num_samples", &self.num_samples)
103 .field("channel_stride_bytes", &self.channel_stride_bytes)
104 .field("timecode", &self.timecode)
105 .field("metadata", &self.metadata.map(CStr::to_string_lossy))
106 .field("data (samples)", &self.data.len())
107 .finish()
108 }
109}
110
111impl<'buf> BorrowedAudioFrameBuilder<'buf> {
112 /// Set the distance in bytes between consecutive channel starts.
113 /// Must be a positive multiple of `size_of::<f32>()`, at least one channel's
114 /// samples, and fit the SDK's signed 32-bit stride field.
115 #[must_use]
116 pub fn channel_stride_bytes(mut self, bytes: usize) -> Self {
117 self.channel_stride_bytes = Some(bytes);
118 self
119 }
120
121 /// Reset the stride override to tightly packed channels.
122 #[must_use]
123 pub fn clear_channel_stride_bytes(mut self) -> Self {
124 self.channel_stride_bytes = None;
125 self
126 }
127
128 /// Set the frame timecode; defaults to [`Timecode::SYNTHESIZE`].
129 #[must_use]
130 pub fn timecode(mut self, timecode: Timecode) -> Self {
131 self.timecode = timecode;
132 self
133 }
134
135 /// Borrow NUL-terminated UTF-8 metadata, validated when built.
136 /// An explicit empty C string differs from absent metadata.
137 #[must_use]
138 pub fn metadata(mut self, metadata: &'buf CStr) -> Self {
139 self.metadata = Some(metadata);
140 self
141 }
142
143 /// Remove the optional metadata override.
144 #[must_use]
145 pub fn clear_metadata(mut self) -> Self {
146 self.metadata = None;
147 self
148 }
149
150 /// Validate the rate, positive channel/sample counts, stride, sample extent
151 /// and optional UTF-8 metadata without allocating sample storage.
152 ///
153 /// # Errors
154 ///
155 /// [`Error::InvalidFrame`] for an invalid layout, insufficient storage,
156 /// exceeding the 64 MiB audio limit or the 4 MiB metadata cap;
157 /// [`Error::InvalidUtf8`] for metadata that is not UTF-8.
158 pub fn build(self) -> Result<BorrowedAudioFrame<'buf>> {
159 let layout = ValidatedAudioLayout::new_uncompressed(
160 AudioFormat::Fltp,
161 self.sample_rate,
162 self.num_channels,
163 self.num_samples,
164 self.channel_stride_bytes,
165 )?;
166 // The slice supplies alignment; the layout's extent establishes that
167 // every active channel is initialized and borrowed for 'buf.
168 let data = self.data.get(..layout.sample_count()).ok_or({
169 Error::InvalidFrame(crate::FrameDefect::AudioBufferTooSmall {
170 actual: self.data.len(),
171 minimum: layout.sample_count(),
172 })
173 })?;
174 let metadata = self.metadata.map(MetadataText::from_cstr).transpose()?;
175 Ok(BorrowedAudioFrame {
176 layout,
177 timecode: self.timecode,
178 data,
179 metadata,
180 })
181 }
182}
183
184audio_accessors! {
185 impl['buf] BorrowedAudioFrame<'buf>;
186 debug("BorrowedAudioFrame", "data (samples)" = sample_count);
187 timecode {}
188 timestamp {
189 /// Application input has no received timestamp.
190 }
191 channel_stride_bytes {
192 /// Includes any configured inter-channel padding.
193 }
194 channel_data {
195 /// Borrows the caller's active samples without reading padding.
196 }
197 data(self -> Option<&[f32]>) {
198 /// Contiguous active samples, or `None` when padding separates channels.
199 } {
200 self.contiguous_samples()
201 }
202 to_owned(self) {
203 /// Copy initialized samples and metadata into a new tightly packed frame.
204 /// The returned frame retains no borrow; padding is omitted.
205 } {
206 self.owned_copy()
207 }
208 copy_into {
209 /// Copy into an existing packed frame, reusing its sample and metadata
210 /// allocations when their capacity and lengths permit. A copy without
211 /// metadata retains the destination's text allocation.
212 }
213
214}
215
216/// A borrowed video frame that references external pixel data.
217///
218/// [`crate::Sender::send_video`] sends it synchronously; the buffer can be reused
219/// as soon as the call returns. [`crate::Sender::submit_video_copy`] copies its
220/// pixels and metadata into an owned frame for the asynchronous pipeline.
221///
222/// The x86 builds of the SDK read a little past the end of many UYVY and
223/// UYVA frames. Where [`PixelFormat::send_tail_room`] is nonzero, borrowed
224/// frames of these formats are copied into packed storage with a zeroed tail
225/// by default, so caller padding and trailing bytes cannot affect the picture.
226/// [`BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`] opts into
227/// direct sending when sufficient initialized memory follows the pixels.
228/// [`Self::sends_in_place`] reports whether a copy is needed.
229///
230/// Create one with [`Self::builder`]. Construction borrows without
231/// allocation and validates the entire supported uncompressed layout once.
232/// Copying it copies only the borrows.
233#[derive(Clone, Copy)]
234pub struct BorrowedVideoFrame<'buf> {
235 layout: ValidatedVideoLayout,
236 header: VideoHeader,
237 /// The whole initialized buffer, including any room after the frame.
238 data: &'buf [u8],
239 /// Readable bytes after the last active pixel, zero unless opted in.
240 room_after: usize,
241 /// The metadata text, validated with its terminator.
242 metadata: Option<MetadataText<'buf>>,
243}
244
245// SAFETY: Private fields pair the initialized byte slice with its validated
246// layout after the builder checks its extent; the borrow retains validated
247// terminated metadata unchanged.
248// pixels() derives from the whole borrowed buffer, so its provenance covers
249// the storage and, only after the caller opts in, the reported room after the
250// last pixel. Direct SDK reads are decided by the common rule over that room.
251unsafe impl crate::frames::VideoParts for BorrowedVideoFrame<'_> {
252 #[inline]
253 fn layout(&self) -> &ValidatedVideoLayout {
254 &self.layout
255 }
256 #[inline]
257 fn header(&self) -> VideoHeader {
258 self.header
259 }
260 #[inline]
261 fn pixels(&self) -> *const u8 {
262 self.data.as_ptr()
263 }
264 #[inline]
265 fn frame_metadata(&self) -> FrameMetadataRef<'_> {
266 FrameMetadataRef::from_text(self.metadata)
267 }
268 /// A frame built for sending carries no timestamp; [`Self::to_raw`]
269 /// sends none.
270 #[inline]
271 fn sdk_timestamp(&self) -> Option<crate::ReceivedTimestamp> {
272 None
273 }
274
275 fn initialized(&self) -> crate::frames::Initialized {
276 crate::frames::Initialized::Storage {
277 room_after: self.room_after,
278 }
279 }
280}
281
282crate::frames::video_accessors! {
283 impl['buf] BorrowedVideoFrame<'buf>;
284 debug("BorrowedVideoFrame", "data (bytes)" = data_len_bytes);
285 timecode {}
286 line_stride_bytes {
287 /// It is the stride the frame was built with, which can include row
288 /// padding.
289 }
290 plane {
291 /// Its rows exclude the padding of the frame's line stride, which
292 /// [`Self::storage`] includes, so the active pixels of a padded buffer
293 /// can be read in place.
294 }
295 timestamp {
296 /// Application input has no received timestamp.
297 }
298 data(self -> Option<&[u8]>) {
299 /// Contiguous active pixels, or `None` when row or plane padding separates
300 /// them. Use [`Self::plane`] and [`Self::planes`] for padded active rows, or
301 /// [`Self::storage`] for the validated storage including row padding.
302 } { crate::frames::VideoPartsExt::active_data(self) }
303 to_owned(self) {
304 /// Copy this borrowed frame into a validated owned frame.
305 ///
306 /// Active pixels are copied into tightly packed planes; row padding is
307 /// skipped and the owned stride can shrink. Metadata is copied separately;
308 /// no reference to the source is retained. [`Self::copy_into`] makes the
309 /// same copy into an existing frame, reusing its allocations.
310 ///
311 /// The copy cannot fail: building the frame validated everything it
312 /// relies on, and the packed layout of a valid frame is valid.
313 } {
314 crate::frames::VideoPartsExt::owned_copy(self)
315 }
316 copy_into {
317 /// Copy this borrowed frame into `destination`, reusing its allocations.
318 ///
319 /// `destination` ends up exactly as [`Self::to_owned`] would have
320 /// returned it, whatever it held before: tightly packed active rows,
321 /// format, dimensions, frame rate, aspect ratio, scan type, timecode and
322 /// metadata, and no timestamp. No reference to the source is retained.
323 ///
324 /// Its pixel buffer is reused when its capacity holds the packed frame
325 /// and the SDK tail room required by its format and scan type, including
326 /// extra strides for interlaced UYVY/UYVA when needed. Otherwise it is
327 /// replaced by one allocation of exactly that size. Its metadata string
328 /// is reused when its capacity holds the new text and its terminator;
329 /// otherwise it grows once. With sufficient pixel and metadata capacity,
330 /// subsequent copies allocate nothing. The copy makes no SDK call and can
331 /// run on any thread. Copies without metadata retain the destination's
332 /// text allocation for later frames.
333 ///
334 /// # Example
335 ///
336 /// A copy-and-send loop that stops allocating once two frames exist.
337 /// [`crate::Sender::submit_video`] keeps the frame it is given until the next
338 /// send, and returns the previous one, which the SDK has finished with:
339 /// that frame is the destination of the next copy.
340 /// [`crate::Sender::submit_video_copy`] keeps its own reusable frames for
341 /// this copy instead.
342 ///
343 /// ```no_run
344 /// # use grafton_ndi::{BorrowedVideoFrame, Ndi, PixelFormat, Sender, SenderOptions, VideoFrame};
345 /// # fn main() -> Result<(), grafton_ndi::Error> {
346 /// # let ndi = Ndi::new()?;
347 /// let mut sender = Sender::new(&ndi, &SenderOptions::new("Copied"))?;
348 /// // 64 pixels per row, padded to a 512-byte stride.
349 /// let mut buffer = vec![0u8; 512 * 32];
350 /// let mut spare: Option<VideoFrame> = None;
351 /// for shade in 0..=255u8 {
352 /// buffer.fill(shade); // the application draws into its own buffer
353 /// let frame = BorrowedVideoFrame::builder(&buffer, 64, 32, PixelFormat::Bgra)
354 /// .line_stride_bytes(512)
355 /// .build()?;
356 /// let owned = match spare.take() {
357 /// Some(mut reused) => {
358 /// frame.copy_into(&mut reused); // no allocation
359 /// reused
360 /// }
361 /// None => frame.to_owned(), // the first two frames only
362 /// };
363 /// spare = sender.submit_video(owned)?;
364 /// }
365 /// sender.reclaim_video();
366 /// # Ok(())
367 /// # }
368 /// ```
369 }
370 sends_in_place {
371 /// Whether [`crate::Sender::send_video`] sends this frame from its buffer,
372 /// without copying its pixels.
373 ///
374 /// UYVY and UYVA frames are copied by default wherever
375 /// [`PixelFormat::send_tail_room`] is nonzero. Opting in with
376 /// [`BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`] allows
377 /// direct sending if enough room follows the last pixel. The last row's
378 /// padding and the bytes of the builder's buffer after the frame count
379 /// towards the room after that opt-in. An interlaced or single-field
380 /// frame of those formats whose height is not a multiple of four needs
381 /// two line strides more.
382 ///
383 /// Where the SDK reads frames exactly, which is 64-bit ARM Linux, the
384 /// room is zero and every frame sends in place.
385 ///
386 /// # Example
387 ///
388 /// ```
389 /// # use grafton_ndi::{BorrowedVideoFrame, PixelFormat, VideoFrame};
390 /// # fn main() -> Result<(), grafton_ndi::Error> {
391 /// let uyvy = PixelFormat::Uyvy;
392 /// let room = uyvy.send_tail_room();
393 /// let exact = vec![0u8; 720 * 480 * 2];
394 /// let frame = BorrowedVideoFrame::builder(&exact, 720, 480, uyvy).build()?;
395 /// // Copied wherever the SDK needs room after the frame.
396 /// assert_eq!(frame.sends_in_place(), room == 0);
397 ///
398 /// let longer = vec![0u8; 720 * 480 * 2 + room];
399 /// let default = BorrowedVideoFrame::builder(&longer, 720, 480, uyvy).build()?;
400 /// assert_eq!(default.sends_in_place(), room == 0);
401 /// let in_place = BorrowedVideoFrame::builder(&longer, 720, 480, uyvy)
402 /// .allow_send_from_padding_and_tail(true)
403 /// .build()?;
404 /// assert!(in_place.sends_in_place());
405 /// assert_eq!(in_place.data().unwrap().len(), 720 * 480 * 2);
406 ///
407 /// let owned = VideoFrame::builder()
408 /// .resolution(720, 480)
409 /// .pixel_format(uyvy)
410 /// .build()?;
411 /// assert!(owned.sends_in_place());
412 /// # Ok(())
413 /// # }
414 /// ```
415 }
416 images("", "\
417 # use grafton_ndi::{BorrowedVideoFrame, PixelFormat};
418 # let pixels = vec![128; 64 * 36 * 2];
419 # let frame = BorrowedVideoFrame::builder(&pixels, 64, 36, PixelFormat::Uyvy).build()?;") {
420 /// It encodes the application's own buffer in place, padded rows
421 /// included, so a program can keep a still of what it sends without
422 /// copying the frame.
423 }
424}
425
426impl<'buf> BorrowedVideoFrame<'buf> {
427 /// Configure a checked borrowed frame over `data`.
428 ///
429 /// `data` may be longer than the frame: the frame is its start, and
430 /// [`Self::storage`] never includes the rest. For UYVY/UYVA where the SDK
431 /// needs tail room, the default send copies active rows only, even when
432 /// `data` includes extra room. Direct sending requires an explicit
433 /// [`BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`] opt-in.
434 ///
435 /// Its defaults are the packed line stride, 60/1 frames per second,
436 /// square pixels (picture aspect ratio `0.0`), progressive scan, [`Timecode::SYNTHESIZE`]
437 /// and no metadata. All validation occurs in
438 /// [`BorrowedVideoFrameBuilder::build`].
439 ///
440 /// # Example
441 ///
442 /// ```
443 /// # use grafton_ndi::{BorrowedVideoFrame, FrameRate, PixelFormat};
444 /// # fn main() -> Result<(), grafton_ndi::Error> {
445 /// let buffer = vec![0u8; 1920 * 1080 * 4]; // BGRA buffer
446 /// let frame = BorrowedVideoFrame::builder(&buffer, 1920, 1080, PixelFormat::Bgra)
447 /// .frame_rate(FrameRate::new(30_000, 1_001)?)
448 /// .build()?;
449 /// assert_eq!(frame.line_stride_bytes(), 1920 * 4);
450 /// # Ok(())
451 /// # }
452 /// ```
453 pub fn builder(
454 data: &'buf [u8],
455 width: u32,
456 height: u32,
457 pixel_format: PixelFormat,
458 ) -> BorrowedVideoFrameBuilder<'buf> {
459 BorrowedVideoFrameBuilder {
460 data,
461 width,
462 height,
463 pixel_format,
464 line_stride: None,
465 frame_rate: crate::media::DEFAULT_VIDEO_FRAME_RATE,
466 aspect_ratio_input: PictureAspectRatio::SQUARE_PIXELS,
467 scan_type: ScanType::Progressive,
468 timecode: Timecode::SYNTHESIZE,
469 metadata: None,
470 allow_padding_and_tail: false,
471 }
472 }
473
474 /// Get the pixel data: exactly the frame's validated storage, including
475 /// any row padding. Bytes of the source buffer beyond the frame are not
476 /// part of it. [`Self::plane`] and [`Self::planes`] borrow the active
477 /// rows alone.
478 pub fn storage(&self) -> &[u8] {
479 &self.data[..self.layout.data_len_bytes()]
480 }
481
482 /// Return this frame with `timecode`.
483 ///
484 /// # Example
485 ///
486 /// ```
487 /// # use grafton_ndi::{BorrowedVideoFrame, PixelFormat, Timecode};
488 /// # fn main() -> Result<(), grafton_ndi::Error> {
489 /// let buffer = vec![0u8; 1920 * 1080 * 2];
490 /// let frame = BorrowedVideoFrame::builder(&buffer, 1920, 1080, PixelFormat::Uyvy)
491 /// .build()?
492 /// .with_timecode(Timecode::from_ticks(10_000_000));
493 /// assert_eq!(frame.timecode().ticks(), 10_000_000);
494 /// # Ok(())
495 /// # }
496 /// ```
497 #[must_use]
498 pub fn with_timecode(mut self, timecode: Timecode) -> Self {
499 self.header = self.header.with_timecode(timecode);
500 self
501 }
502
503 #[cfg(test)]
504 pub(crate) fn to_raw(self) -> NDIlib_video_frame_v2_t {
505 self.video_descriptor()
506 }
507}
508
509/// Builder for a [`BorrowedVideoFrame`], reached through
510/// [`BorrowedVideoFrame::builder`]. No pixels or metadata are copied.
511#[derive(Clone, Copy)]
512pub struct BorrowedVideoFrameBuilder<'buf> {
513 data: &'buf [u8],
514 width: u32,
515 height: u32,
516 pixel_format: PixelFormat,
517 line_stride: Option<usize>,
518 frame_rate: FrameRate,
519 aspect_ratio_input: PictureAspectRatio,
520 scan_type: ScanType,
521 timecode: Timecode,
522 metadata: Option<&'buf CStr>,
523 allow_padding_and_tail: bool,
524}
525
526impl std::fmt::Debug for BorrowedVideoFrameBuilder<'_> {
527 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 f.debug_struct("BorrowedVideoFrameBuilder")
529 .field("width", &self.width)
530 .field("height", &self.height)
531 .field("pixel_format", &self.pixel_format)
532 .field("line_stride_bytes", &self.line_stride)
533 .field("frame_rate", &self.frame_rate)
534 .field("picture_aspect_ratio", &self.aspect_ratio_input)
535 .field("scan_type", &self.scan_type)
536 .field("timecode", &self.timecode)
537 .field("metadata", &self.metadata.map(CStr::to_string_lossy))
538 .field(
539 "allow_send_from_padding_and_tail",
540 &self.allow_padding_and_tail,
541 )
542 .field("data (bytes)", &self.data.len())
543 .finish()
544 }
545}
546
547impl<'buf> BorrowedVideoFrameBuilder<'buf> {
548 /// Set the first-plane stride in bytes, following the
549 /// [video stride rules](PixelFormat::buffer_len).
550 /// Use [`Self::clear_line_stride_bytes`] for the packed stride.
551 #[must_use]
552 pub fn line_stride_bytes(mut self, stride: usize) -> Self {
553 self.line_stride = Some(stride);
554 self
555 }
556
557 /// Reset the first-plane stride override to the packed stride.
558 #[must_use]
559 pub fn clear_line_stride_bytes(mut self) -> Self {
560 self.line_stride = None;
561 self
562 }
563 /// Set the frame rate.
564 #[must_use]
565 pub fn frame_rate(mut self, frame_rate: FrameRate) -> Self {
566 self.frame_rate = frame_rate;
567 self
568 }
569 /// Set a finite nonnegative aspect ratio; zero selects square pixels.
570 #[must_use]
571 pub fn picture_aspect_ratio(mut self, ratio: PictureAspectRatio) -> Self {
572 self.aspect_ratio_input = ratio;
573 self
574 }
575 /// Select progressive, interlaced, or field scanning.
576 #[must_use]
577 pub fn scan_type(mut self, scan_type: ScanType) -> Self {
578 self.scan_type = scan_type;
579 self
580 }
581 /// Set the timecode.
582 #[must_use]
583 pub fn timecode(mut self, timecode: Timecode) -> Self {
584 self.timecode = timecode;
585 self
586 }
587 /// Borrow NUL-terminated UTF-8 metadata, validated when built.
588 #[must_use]
589 pub fn metadata(mut self, metadata: &'buf CStr) -> Self {
590 self.metadata = Some(metadata);
591 self
592 }
593
594 /// Remove the optional metadata override.
595 #[must_use]
596 pub fn clear_metadata(mut self) -> Self {
597 self.metadata = None;
598 self
599 }
600
601 /// Allow direct sending from caller padding and trailing memory.
602 ///
603 /// Defaults to `false`. Where UYVY/UYVA sending needs tail room, the
604 /// default path packs active rows and zeroes the tail. Setting this to
605 /// `true` permits sending directly if the supplied buffer is large enough
606 /// to include the required room after the frame. The SDK may encode row
607 /// padding and trailing bytes into the picture: only opt in when their
608 /// contents are suitable for transmission. All such bytes must be
609 /// initialized and stable throughout the send. Insufficient room still
610 /// causes a packed copy. Formats with zero tail room send directly either way.
611 #[must_use]
612 pub fn allow_send_from_padding_and_tail(mut self, allow: bool) -> Self {
613 self.allow_padding_and_tail = allow;
614 self
615 }
616
617 /// Validate dimensions, stride, initialized slice extent, headers, and metadata.
618 ///
619 /// Successful construction allocates nothing and never loads or queries
620 /// an NDI runtime: whether the runtime can send the pixel format is
621 /// checked when the frame is sent. The input slices remain borrowed.
622 ///
623 /// # Errors
624 ///
625 /// Invalid layout/header values, a buffer smaller than the layout, or
626 /// metadata exceeding the 4 MiB cap return [`Error::InvalidFrame`];
627 /// invalid metadata UTF-8 returns [`Error::InvalidUtf8`].
628 pub fn build(self) -> Result<BorrowedVideoFrame<'buf>> {
629 let picture_aspect_ratio = self.aspect_ratio_input;
630 let layout = ValidatedVideoLayout::new_uncompressed(
631 self.pixel_format,
632 self.width,
633 self.height,
634 self.line_stride,
635 )?;
636 if self.data.len() < layout.data_len_bytes() {
637 return Err(Error::InvalidFrame(
638 crate::FrameDefect::VideoBufferTooSmall {
639 format: self.pixel_format,
640 actual: self.data.len(),
641 minimum: layout.data_len_bytes(),
642 },
643 ));
644 }
645 let metadata = self.metadata.map(MetadataText::from_cstr).transpose()?;
646 Ok(BorrowedVideoFrame {
647 layout,
648 header: VideoHeader::new(
649 self.frame_rate,
650 picture_aspect_ratio,
651 self.scan_type,
652 self.timecode,
653 ),
654 data: self.data,
655 room_after: if self.allow_padding_and_tail {
656 layout.trailing_padding() + (self.data.len() - layout.data_len_bytes())
657 } else {
658 0
659 },
660 metadata,
661 })
662 }
663}