Skip to main content

grafton_ndi/advanced/packets/
roles.rs

1//! The storage and constructors for each compressed-packet role.
2use super::*;
3use crate::{
4    capture::{AudioKind, FrameFree, Guard, VideoKind},
5    frames::{
6        descriptor_parts_sealed, DescriptorParts, FrameMetadataRef, MetadataText, SdkDescriptor,
7        ValidatedFrame,
8    },
9    FrameMetadataStatus,
10};
11use std::fmt::{self, Debug};
12
13use crate::advanced::send::ScatterStorage;
14#[cfg(doc)]
15use crate::advanced::MAX_SCATTER_BLOCKS;
16#[cfg(ndi_has_advanced_scatter_send)]
17use crate::sys::advanced::FrameScatter;
18
19/// A compressed packet's checked media format.
20///
21/// This trait is sealed and implemented by [`VideoPacketFormat`] and
22/// [`AudioPacketFormat`]. The format
23/// determines the SDK descriptor and which packets can be received or sent.
24#[allow(private_bounds)]
25pub trait PacketFormat: NativePacketFormat + Copy + Debug + Send + Sync {}
26
27impl PacketFormat for VideoPacketFormat {}
28impl PacketFormat for AudioPacketFormat {}
29
30/// The SDK representation and admission rules behind the public format bound.
31pub(crate) trait NativePacketFormat: Sized {
32    type Descriptor: SdkDescriptor;
33    type Kind: FrameFree<RawFrame = Self::Descriptor>;
34
35    const SIZE_DEFECT: crate::FrameDefect;
36
37    fn from_sdk(descriptor: &Self::Descriptor) -> Result<Self>;
38    fn descriptor(self, extras: &FrameExtras) -> Self::Descriptor;
39    fn payload(descriptor: &Self::Descriptor) -> (*mut u8, i32);
40    fn lend_payload(descriptor: &mut Self::Descriptor, data: *mut u8, size: i32);
41    fn timecode(descriptor: &Self::Descriptor) -> Timecode;
42    fn header_bytes(self) -> usize;
43    fn envelope_codec(self) -> Option<EnvelopeCodec>;
44    fn admit(self, packet: PacketContent<'_>, purpose: Use) -> Result<Option<EnvelopeExtents>>;
45}
46
47pub(crate) enum PacketContent<'a> {
48    Contiguous(PacketSlice<'a>),
49    Scatter {
50        first: &'a [u8],
51        total: PacketLen,
52        rest: &'a [Vec<u8>],
53    },
54}
55
56impl PacketContent<'_> {
57    fn first(&self) -> &[u8] {
58        match self {
59            Self::Contiguous(packet) => packet.as_slice(),
60            Self::Scatter { first, .. } => first,
61        }
62    }
63
64    fn len(&self) -> usize {
65        match self {
66            Self::Contiguous(packet) => packet.len(),
67            Self::Scatter { total, .. } => *total,
68        }
69        .to_usize()
70    }
71
72    fn bytes_at<const N: usize>(&self, offset: usize) -> Option<[u8; N]> {
73        match self {
74            Self::Contiguous(packet) => packet.as_slice().get(offset..)?.first_chunk().copied(),
75            Self::Scatter { first, rest, .. } => {
76                crate::advanced::send::bytes_at(first, rest, offset)
77            }
78        }
79    }
80}
81
82impl NativePacketFormat for VideoPacketFormat {
83    type Descriptor = NDIlib_video_frame_v2_t;
84    type Kind = VideoKind;
85
86    const SIZE_DEFECT: crate::FrameDefect = crate::FrameDefect::CompressedVideoSize;
87
88    fn from_sdk(descriptor: &Self::Descriptor) -> Result<Self> {
89        Self::from_sdk(descriptor)
90    }
91
92    fn descriptor(self, extras: &FrameExtras) -> Self::Descriptor {
93        self.descriptor(extras)
94    }
95
96    fn payload(descriptor: &Self::Descriptor) -> (*mut u8, i32) {
97        // SAFETY: callers classify the FourCC as compressed before reading
98        // the size, which is the member used by compressed descriptors.
99        (descriptor.p_data, unsafe {
100            descriptor.__bindgen_anon_1.data_size_in_bytes
101        })
102    }
103
104    fn lend_payload(descriptor: &mut Self::Descriptor, data: *mut u8, size: i32) {
105        descriptor.p_data = data;
106        descriptor.__bindgen_anon_1.data_size_in_bytes = size;
107    }
108
109    fn timecode(descriptor: &Self::Descriptor) -> Timecode {
110        Timecode::from_ticks(descriptor.timecode)
111    }
112
113    fn header_bytes(self) -> usize {
114        match self.envelope_codec() {
115            Some(_) => ENVELOPE_HEADER_BYTES,
116            None => SPEEDHQ_HEADER_BYTES,
117        }
118    }
119
120    fn envelope_codec(self) -> Option<EnvelopeCodec> {
121        self.codec().envelope_codec()
122    }
123
124    fn admit(self, packet: PacketContent<'_>, purpose: Use) -> Result<Option<EnvelopeExtents>> {
125        let Some(codec) = self.envelope_codec() else {
126            if packet.len() < SPEEDHQ_HEADER_BYTES {
127                return Err(invalid_frame(crate::FrameDefect::SpeedHqTruncated));
128            }
129            if purpose == Use::Send
130                && packet
131                    .first()
132                    .first()
133                    .is_none_or(|quality| *quality >= SPEEDHQ_QUALITY_LIMIT)
134            {
135                return Err(invalid_frame(crate::FrameDefect::SpeedHqQuality));
136            }
137            return Ok(None);
138        };
139        let header = EnvelopeHeader::read(packet.first())?;
140        let extents = header.validate(codec, packet.len(), purpose)?;
141        if purpose == Use::Send {
142            header.validate_video_configuration()?;
143            if self.tier() == StreamTier::Preview
144                && (self.width() > MAX_PREVIEW_DIMENSION || self.height() > MAX_PREVIEW_DIMENSION)
145            {
146                return Err(invalid_frame(crate::FrameDefect::PreviewVideoDimensions));
147            }
148        }
149        Ok(Some(extents))
150    }
151}
152
153impl NativePacketFormat for AudioPacketFormat {
154    type Descriptor = NDIlib_audio_frame_v3_t;
155    type Kind = AudioKind;
156
157    const SIZE_DEFECT: crate::FrameDefect = crate::FrameDefect::CompressedAudioSize;
158
159    fn from_sdk(descriptor: &Self::Descriptor) -> Result<Self> {
160        Self::from_sdk(descriptor)
161    }
162
163    fn descriptor(self, extras: &FrameExtras) -> Self::Descriptor {
164        self.descriptor(extras)
165    }
166
167    fn payload(descriptor: &Self::Descriptor) -> (*mut u8, i32) {
168        // SAFETY: callers classify the FourCC as compressed before reading
169        // the size, which is the member used by compressed descriptors.
170        (descriptor.p_data, unsafe {
171            descriptor.__bindgen_anon_1.data_size_in_bytes
172        })
173    }
174
175    fn lend_payload(descriptor: &mut Self::Descriptor, data: *mut u8, size: i32) {
176        descriptor.p_data = data;
177        descriptor.__bindgen_anon_1.data_size_in_bytes = size;
178    }
179
180    fn timecode(descriptor: &Self::Descriptor) -> Timecode {
181        Timecode::from_ticks(descriptor.timecode)
182    }
183
184    fn header_bytes(self) -> usize {
185        self.envelope_codec().map_or(0, |_| ENVELOPE_HEADER_BYTES)
186    }
187
188    fn envelope_codec(self) -> Option<EnvelopeCodec> {
189        match self.codec() {
190            AudioCodec::Aac => Some(EnvelopeCodec::Aac),
191            AudioCodec::Opus => None,
192        }
193    }
194
195    fn admit(self, packet: PacketContent<'_>, purpose: Use) -> Result<Option<EnvelopeExtents>> {
196        if purpose == Use::Send {
197            self.codec().validate_delivery(self)?;
198        }
199        let Some(codec) = self.envelope_codec() else {
200            return Ok(None);
201        };
202        let header = EnvelopeHeader::read(packet.first())?;
203        let extents = header.validate(codec, packet.len(), purpose)?;
204        if purpose == Use::Send {
205            header.validate_aac(packet.bytes_at(extents.extra_offset()), self)?;
206        }
207        Ok(Some(extents))
208    }
209}
210
211/// One owned compressed frame that has been admitted for sending.
212///
213/// Construction checks packet bounds and, where present, the envelope's codec
214/// fields. The application supplies a decodable codec bitstream. The SDK can
215/// write to the bytes, so sending takes the frame exclusively or by value.
216#[derive(Clone)]
217pub struct CompressedFrame<F: PacketFormat> {
218    format: F,
219    payload: PacketBytes,
220    extras: FrameExtras,
221}
222
223impl CompressedFrame<VideoPacketFormat> {
224    /// Take ownership of one frame's bytes: a packet envelope for H.264 and
225    /// HEVC (see [`PacketEnvelope::encode`]), a SpeedHQ frame otherwise.
226    ///
227    /// # Errors
228    ///
229    /// Returns the bytes with [`Error::InvalidFrame`] if their extent or
230    /// envelope is invalid, or for a frame the SDK does not deliver (see
231    /// [`VideoCodec`]).
232    pub fn new(
233        format: VideoPacketFormat,
234        bytes: Vec<u8>,
235    ) -> std::result::Result<Self, Rejected<Vec<u8>>> {
236        Self::admitted(format, bytes)
237    }
238
239    /// Bytes this frame keeps allocated.
240    pub(crate) fn retained_bytes(&self) -> usize {
241        self.payload.capacity() + self.extras.retained_bytes()
242    }
243}
244
245impl CompressedFrame<AudioPacketFormat> {
246    /// Take ownership of one audio frame's bytes: a packet envelope for AAC
247    /// (see [`PacketEnvelope::encode`]), one bare packet for Opus.
248    ///
249    /// # Errors
250    ///
251    /// Returns the bytes with [`Error::InvalidFrame`] if their extent is
252    /// invalid, the delivery parameters are unsupported (see [`AudioCodec`]),
253    /// or the AAC envelope is malformed or disagrees with those parameters.
254    pub fn new(
255        format: AudioPacketFormat,
256        bytes: Vec<u8>,
257    ) -> std::result::Result<Self, Rejected<Vec<u8>>> {
258        Self::admitted(format, bytes)
259    }
260}
261
262impl<F: PacketFormat> CompressedFrame<F> {
263    /// The timecode: [`crate::Timecode::SYNTHESIZE`] on a frame built for
264    /// sending without an explicit timecode.
265    pub fn timecode(&self) -> crate::Timecode {
266        self.extras.timecode()
267    }
268
269    /// Replace the frame's timecode.
270    pub fn set_timecode(&mut self, timecode: crate::Timecode) {
271        self.extras.set_timecode(timecode);
272    }
273
274    /// The per-frame metadata, if any. Unreadable received text is omitted.
275    pub fn metadata(&self) -> Option<&str> {
276        self.extras.metadata()
277    }
278
279    /// Cached metadata presence or the reason unreadable text was withheld.
280    pub fn metadata_status(&self) -> crate::FrameMetadataStatus {
281        self.extras.metadata_status()
282    }
283
284    /// Replace frame metadata. Use [`Self::clear_metadata`] to remove it.
285    ///
286    /// Invalid replacement text leaves the existing metadata unchanged.
287    ///
288    /// # Errors
289    ///
290    /// Returns the unchanged text in [`crate::Rejected`], with
291    /// [`crate::Error::InvalidCString`] for an interior NUL, or
292    /// [`crate::Error::InvalidFrame`] when the emitted C string would
293    /// exceed the metadata size cap. `NulError` retains only the prefix
294    /// through the first NUL; [`crate::Rejected::into_inner`] returns all text.
295    pub fn set_metadata(
296        &mut self,
297        metadata: impl Into<String>,
298    ) -> std::result::Result<(), crate::Rejected<String>> {
299        self.extras.set_metadata(metadata)
300    }
301
302    /// Remove the frame metadata.
303    pub fn clear_metadata(&mut self) {
304        self.extras.clear_metadata();
305    }
306
307    fn admitted(format: F, bytes: Vec<u8>) -> std::result::Result<Self, Rejected<Vec<u8>>> {
308        let payload = PacketBytes::new(bytes)
309            .map_err(|bytes| Rejected::new(invalid_frame(F::SIZE_DEFECT), bytes))?;
310        let extents = match format.admit(PacketContent::Contiguous(payload.view()), Use::Send) {
311            Ok(extents) => extents,
312            Err(error) => return Err(Rejected::new(error, payload.into_vec())),
313        };
314        Ok(Self {
315            format,
316            payload: payload.with_envelope(extents),
317            extras: FrameExtras::default(),
318        })
319    }
320
321    /// The codec bytes.
322    pub fn data(&self) -> &[u8] {
323        self.payload.as_slice()
324    }
325
326    /// The packet's codec and media format.
327    pub fn format(&self) -> F {
328        self.format
329    }
330
331    /// Source-dependent timestamp preserved when relaying a received frame.
332    pub fn timestamp(&self) -> Option<ReceivedTimestamp> {
333        self.extras.timestamp()
334    }
335
336    /// The validated envelope, if the codec uses one.
337    pub fn envelope(&self) -> Option<PacketEnvelope<'_>> {
338        self.payload
339            .extents()
340            .map(|extents| PacketEnvelope::from_validated(self.data(), extents))
341    }
342
343    /// Take the codec bytes, retaining the original allocation and capacity.
344    pub fn into_data(self) -> Vec<u8> {
345        self.payload.into_vec()
346    }
347
348    /// A native descriptor that lends this frame's bytes and metadata to the
349    /// SDK. The caller keeps the frame exclusively while the SDK can write.
350    pub(crate) fn raw(&mut self) -> F::Descriptor {
351        let mut raw = self.format.descriptor(&self.extras);
352        let (data, size) = self.payload.lend();
353        F::lend_payload(&mut raw, data, size);
354        raw
355    }
356}
357
358/// An owned compressed packet copied from a receiver without loss.
359///
360/// Later envelope versions, flags and trailing bytes remain intact. Convert
361/// with [`CompressedFrame::try_from`] before sending. A refusal returns this
362/// packet and its storage in [`Rejected`].
363#[derive(Clone)]
364pub struct ReceivedPacket<F: PacketFormat> {
365    format: F,
366    payload: PacketBytes,
367    extras: FrameExtras,
368}
369
370impl<F: PacketFormat> ReceivedPacket<F> {
371    /// The timecode: [`crate::Timecode::SYNTHESIZE`] on a frame built for
372    /// sending without an explicit timecode.
373    pub fn timecode(&self) -> crate::Timecode {
374        self.extras.timecode()
375    }
376
377    /// Replace the frame's timecode.
378    pub fn set_timecode(&mut self, timecode: crate::Timecode) {
379        self.extras.set_timecode(timecode);
380    }
381
382    /// The per-frame metadata, if any. Unreadable received text is omitted.
383    pub fn metadata(&self) -> Option<&str> {
384        self.extras.metadata()
385    }
386
387    /// Cached metadata presence or the reason unreadable text was withheld.
388    pub fn metadata_status(&self) -> crate::FrameMetadataStatus {
389        self.extras.metadata_status()
390    }
391
392    /// Replace frame metadata. Use [`Self::clear_metadata`] to remove it.
393    ///
394    /// Invalid replacement text leaves the existing metadata unchanged.
395    ///
396    /// # Errors
397    ///
398    /// Returns the unchanged text in [`crate::Rejected`], with
399    /// [`crate::Error::InvalidCString`] for an interior NUL, or
400    /// [`crate::Error::InvalidFrame`] when the emitted C string would
401    /// exceed the metadata size cap. `NulError` retains only the prefix
402    /// through the first NUL; [`crate::Rejected::into_inner`] returns all text.
403    pub fn set_metadata(
404        &mut self,
405        metadata: impl Into<String>,
406    ) -> std::result::Result<(), crate::Rejected<String>> {
407        self.extras.set_metadata(metadata)
408    }
409
410    /// Remove the frame metadata.
411    pub fn clear_metadata(&mut self) {
412        self.extras.clear_metadata();
413    }
414
415    /// The complete codec bytes, including retained envelope extensions.
416    pub fn data(&self) -> &[u8] {
417        self.payload.as_slice()
418    }
419
420    /// The packet's codec and media format.
421    pub fn format(&self) -> F {
422        self.format
423    }
424
425    /// Source-dependent timestamp supplied by the SDK at capture.
426    pub fn timestamp(&self) -> Option<ReceivedTimestamp> {
427        self.extras.timestamp()
428    }
429
430    /// The validated envelope, if the codec uses one.
431    pub fn envelope(&self) -> Option<PacketEnvelope<'_>> {
432        self.payload
433            .extents()
434            .map(|extents| PacketEnvelope::from_validated(self.data(), extents))
435    }
436
437    /// Take the original byte allocation and its capacity.
438    pub fn into_data(self) -> Vec<u8> {
439        self.payload.into_vec()
440    }
441
442    /// Check send admission without consuming or changing this packet.
443    ///
444    /// # Errors
445    ///
446    /// [`Error::InvalidFrame`] for unsupported codec parameters or envelope details.
447    pub fn validate_for_send(&self) -> Result<()> {
448        self.send_extents().map(drop)
449    }
450
451    fn send_extents(&self) -> Result<Option<EnvelopeExtents>> {
452        self.format
453            .admit(PacketContent::Contiguous(self.payload.view()), Use::Send)
454    }
455}
456
457impl<F: PacketFormat> TryFrom<ReceivedPacket<F>> for CompressedFrame<F> {
458    type Error = Rejected<ReceivedPacket<F>>;
459
460    fn try_from(packet: ReceivedPacket<F>) -> std::result::Result<Self, Self::Error> {
461        let extents = match packet.send_extents() {
462            Ok(extents) => extents,
463            Err(error) => return Err(Rejected::new(error, packet)),
464        };
465        let ReceivedPacket {
466            format,
467            payload,
468            extras,
469        } = packet;
470        Ok(Self {
471            format,
472            payload: payload.with_envelope(extents),
473            extras,
474        })
475    }
476}
477
478impl<F: PacketFormat> From<CompressedFrame<F>> for ReceivedPacket<F> {
479    fn from(frame: CompressedFrame<F>) -> Self {
480        let CompressedFrame {
481            format,
482            payload,
483            extras,
484        } = frame;
485        Self {
486            format,
487            payload,
488            extras,
489        }
490    }
491}
492
493/// A borrowed compressed packet captured by a [`PacketReceiver`](crate::advanced::PacketReceiver).
494///
495/// Capture validates once without allocating. The receive guard retains
496/// payload and metadata, including an application allocator's usage charge,
497/// until the reference drops. Copy into an owned frame before sending because
498/// the SDK can write to frames it sends.
499pub struct CompressedRef<'rx, F: PacketFormat> {
500    frame: ValidatedFrame<Guard<'rx, F::Kind>, PacketParts<F>>,
501}
502
503struct PacketParts<F: PacketFormat> {
504    format: F,
505    len: PacketLen,
506    extents: Option<EnvelopeExtents>,
507}
508
509impl<F: PacketFormat> descriptor_parts_sealed::Sealed for PacketParts<F> {}
510
511// SAFETY: the sealed format validates the codec and parameters from this exact
512// descriptor. PacketSlice validates its payload extent, and receive admission
513// validates any envelope within that extent.
514unsafe impl<F: PacketFormat> DescriptorParts<F::Descriptor> for PacketParts<F> {
515    unsafe fn validate(raw: &F::Descriptor) -> Result<Self> {
516        let format = F::from_sdk(raw)?;
517        let (data, size) = F::payload(raw);
518        // SAFETY: the guard retains the initialized allocation described by the
519        // checked compressed format. PacketSlice checks its declared extent.
520        let bytes = unsafe { PacketSlice::from_sdk(data, size)? };
521        let extents = format.admit(PacketContent::Contiguous(bytes), Use::Receive)?;
522        Ok(Self {
523            format,
524            len: bytes.len(),
525            extents,
526        })
527    }
528}
529
530impl<'rx, F: PacketFormat> CompressedRef<'rx, F> {
531    pub(crate) fn new(guard: Guard<'rx, F::Kind>) -> Result<Self> {
532        let frame = ValidatedFrame::validate(guard)?;
533        Ok(Self { frame })
534    }
535
536    /// The complete codec bytes, borrowed in place.
537    pub fn data(&self) -> &[u8] {
538        self.packet_slice().as_slice()
539    }
540
541    fn packet_slice(&self) -> PacketSlice<'_> {
542        let (data, _) = F::payload(self.frame.descriptor());
543        // SAFETY: the validated parts cover this descriptor's immutable
544        // payload, retained by the guard for the returned borrow.
545        unsafe { PacketSlice::from_validated(data, self.frame.parts().len) }
546    }
547
548    /// The packet's codec and media format.
549    pub fn format(&self) -> F {
550        self.frame.parts().format
551    }
552
553    /// The timecode supplied by the source.
554    pub fn timecode(&self) -> Timecode {
555        F::timecode(self.frame.descriptor())
556    }
557
558    /// Source-dependent timestamp supplied by the SDK at capture.
559    pub fn timestamp(&self) -> Option<ReceivedTimestamp> {
560        self.frame.timestamp()
561    }
562
563    /// Optional UTF-8 metadata. [`Self::metadata_status`] reports withheld text.
564    pub fn metadata(&self) -> Option<&str> {
565        self.frame_metadata().text().map(MetadataText::as_str)
566    }
567
568    /// Cached metadata presence or the reason unreadable text was withheld.
569    pub fn metadata_status(&self) -> FrameMetadataStatus {
570        self.frame_metadata().status()
571    }
572
573    fn frame_metadata(&self) -> FrameMetadataRef<'_> {
574        self.frame.frame_metadata()
575    }
576
577    /// The validated envelope, if the codec uses one.
578    pub fn envelope(&self) -> Option<PacketEnvelope<'_>> {
579        self.frame
580            .parts()
581            .extents
582            .map(|extents| PacketEnvelope::from_validated(self.data(), extents))
583    }
584
585    fn copy_extras(&self, extras: &mut FrameExtras) {
586        extras.copy_received(self.timecode(), self.timestamp(), self.frame_metadata());
587    }
588
589    /// Copy payload and readable metadata into independent storage, retaining
590    /// the status of any withheld metadata.
591    pub fn to_owned(&self) -> ReceivedPacket<F> {
592        let mut extras = FrameExtras::default();
593        self.copy_extras(&mut extras);
594        ReceivedPacket {
595            format: self.format(),
596            payload: PacketBytes::copied(self.packet_slice(), self.frame.parts().extents),
597            extras,
598        }
599    }
600
601    /// Make a lossless copy into existing storage. Once the destination has
602    /// sufficient capacity, repeated copies allocate nothing.
603    pub fn copy_into(&self, destination: &mut ReceivedPacket<F>) {
604        destination
605            .payload
606            .refill(self.packet_slice(), self.frame.parts().extents);
607        self.copy_extras(&mut destination.extras);
608        destination.format = self.format();
609    }
610
611    /// Admit this packet for sending, then copy it into existing storage.
612    /// A refusal leaves every destination field and allocation unchanged.
613    ///
614    /// # Errors
615    ///
616    /// [`Error::InvalidFrame`] when this packet cannot be sent.
617    pub fn try_copy_into(&self, destination: &mut CompressedFrame<F>) -> Result<()> {
618        let bytes = self.packet_slice();
619        let format = self.format();
620        let extents = format.admit(PacketContent::Contiguous(bytes), Use::Send)?;
621        destination.payload.refill(bytes, extents);
622        self.copy_extras(&mut destination.extras);
623        destination.format = format;
624        Ok(())
625    }
626}
627
628impl<F: PacketFormat> TryFrom<&CompressedRef<'_, F>> for CompressedFrame<F> {
629    type Error = Error;
630
631    fn try_from(packet: &CompressedRef<'_, F>) -> Result<Self> {
632        let bytes = packet.packet_slice();
633        let format = packet.format();
634        let extents = format.admit(PacketContent::Contiguous(bytes), Use::Send)?;
635        let mut extras = FrameExtras::default();
636        packet.copy_extras(&mut extras);
637        Ok(Self {
638            format,
639            payload: PacketBytes::copied(bytes, extents),
640            extras,
641        })
642    }
643}
644
645/// A sendable compressed frame held in ordered blocks, without joining them.
646///
647/// The first block holds the complete 44-byte envelope header for H.264, HEVC
648/// or AAC, or the first four bytes for SpeedHQ. Opus has no header.
649///
650/// # Examples
651///
652/// ```
653/// use grafton_ndi::advanced::{
654///     EnvelopeCodec, PacketEnvelope, ScatterFrame, VideoCodec, VideoPacketFormat,
655/// };
656///
657/// let packet =
658///     PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, true, &[0x65; 64], &[0x67; 8])?;
659/// let (header, rest) = packet.split_at(44);
660/// let frame = ScatterFrame::new(
661///     VideoPacketFormat::new(VideoCodec::H264, 1280, 720)?,
662///     vec![header.to_vec(), rest.to_vec()],
663/// )?;
664/// assert_eq!(frame.total_bytes(), packet.len());
665/// # Ok::<(), grafton_ndi::Error>(())
666/// ```
667#[derive(Clone)]
668pub struct ScatterFrame<F: PacketFormat> {
669    format: F,
670    storage: ScatterStorage,
671    extents: Option<EnvelopeExtents>,
672    extras: FrameExtras,
673}
674
675impl<F: PacketFormat> ScatterFrame<F> {
676    /// The timecode: [`crate::Timecode::SYNTHESIZE`] on a frame built for
677    /// sending without an explicit timecode.
678    pub fn timecode(&self) -> crate::Timecode {
679        self.extras.timecode()
680    }
681
682    /// Replace the frame's timecode.
683    pub fn set_timecode(&mut self, timecode: crate::Timecode) {
684        self.extras.set_timecode(timecode);
685    }
686
687    /// The per-frame metadata, if any. Unreadable received text is omitted.
688    pub fn metadata(&self) -> Option<&str> {
689        self.extras.metadata()
690    }
691
692    /// Cached metadata presence or the reason unreadable text was withheld.
693    pub fn metadata_status(&self) -> crate::FrameMetadataStatus {
694        self.extras.metadata_status()
695    }
696
697    /// Replace frame metadata. Use [`Self::clear_metadata`] to remove it.
698    ///
699    /// Invalid replacement text leaves the existing metadata unchanged.
700    ///
701    /// # Errors
702    ///
703    /// Returns the unchanged text in [`crate::Rejected`], with
704    /// [`crate::Error::InvalidCString`] for an interior NUL, or
705    /// [`crate::Error::InvalidFrame`] when the emitted C string would
706    /// exceed the metadata size cap. `NulError` retains only the prefix
707    /// through the first NUL; [`crate::Rejected::into_inner`] returns all text.
708    pub fn set_metadata(
709        &mut self,
710        metadata: impl Into<String>,
711    ) -> std::result::Result<(), crate::Rejected<String>> {
712        self.extras.set_metadata(metadata)
713    }
714
715    /// Remove the frame metadata.
716    pub fn clear_metadata(&mut self) {
717        self.extras.clear_metadata();
718    }
719
720    /// Take ownership of one frame's blocks, in order.
721    ///
722    /// # Errors
723    ///
724    /// Returns the original blocks with [`Error::InvalidFrame`] if the list is
725    /// empty or exceeds [`MAX_SCATTER_BLOCKS`], a block is empty, the frame
726    /// exceeds [`MAX_PACKET_BYTES`], or the packet is not sendable in this format.
727    pub fn new(
728        format: F,
729        mut blocks: Vec<Vec<u8>>,
730    ) -> std::result::Result<Self, Rejected<Vec<Vec<u8>>>> {
731        let mut check = || {
732            let checked = ScatterStorage::check(&mut blocks, format.header_bytes())?;
733            let packet = PacketContent::Scatter {
734                first: checked.first,
735                total: checked.total,
736                rest: checked.rest,
737            };
738            let extents = format.admit(packet, Use::Send)?;
739            Ok(Self {
740                format,
741                storage: checked.into_storage(),
742                extents,
743                extras: FrameExtras::default(),
744            })
745        };
746        match check() {
747            Ok(frame) => Ok(frame),
748            Err(error) => Err(Rejected::new(error, blocks)),
749        }
750    }
751
752    /// The packet's codec and media format.
753    pub fn format(&self) -> F {
754        self.format
755    }
756
757    /// The blocks, in order.
758    pub fn blocks(&self) -> impl ExactSizeIterator<Item = &[u8]> {
759        self.storage.blocks()
760    }
761
762    /// Recover each original block, preserving order, allocation and capacity.
763    /// The SDK's writes remain in those blocks.
764    pub fn into_blocks(self) -> Vec<Vec<u8>> {
765        self.storage.into_blocks()
766    }
767
768    /// The combined size of the blocks, in bytes.
769    pub fn total_bytes(&self) -> usize {
770        self.storage.total_bytes()
771    }
772
773    /// Join the blocks into one newly allocated contiguous frame.
774    pub fn into_contiguous_copy(self) -> CompressedFrame<F> {
775        CompressedFrame {
776            format: self.format,
777            payload: self.storage.copy_contiguous(self.extents),
778            extras: self.extras,
779        }
780    }
781
782    /// Lend the native scatter array and a descriptor whose data fields are unused.
783    #[cfg(ndi_has_advanced_scatter_send)]
784    pub(in crate::advanced) fn lend_scatter(&mut self) -> (F::Descriptor, *const FrameScatter) {
785        (
786            self.format.descriptor(&self.extras),
787            self.storage.descriptor(),
788        )
789    }
790
791    #[cfg(ndi_has_advanced_scatter_send)]
792    pub(in crate::advanced) fn lend_first_block(&mut self) -> (*mut u8, i32) {
793        self.storage.lend_first_block()
794    }
795
796    #[cfg(test)]
797    pub(in crate::advanced) fn storage_for_test(&self) -> &ScatterStorage {
798        &self.storage
799    }
800}
801
802impl ScatterFrame<VideoPacketFormat> {
803    pub(in crate::advanced) fn retained_bytes(&self) -> usize {
804        self.storage
805            .retained_bytes()
806            .saturating_add(self.extras.retained_bytes())
807    }
808}
809
810/// Format an owned or borrowed packet without traversing its payload.
811fn debug_packet(
812    f: &mut fmt::Formatter<'_>,
813    name: &str,
814    format: impl Debug,
815    bytes: usize,
816    timecode: Timecode,
817    timestamp: Option<ReceivedTimestamp>,
818    metadata_status: FrameMetadataStatus,
819) -> fmt::Result {
820    f.debug_struct(name)
821        .field("format", &format)
822        .field("bytes", &bytes)
823        .field("timecode", &timecode)
824        .field("timestamp", &timestamp)
825        .field("metadata_status", &metadata_status)
826        .finish()
827}
828
829impl<F: PacketFormat> Debug for CompressedFrame<F> {
830    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
831        debug_packet(
832            f,
833            "CompressedFrame",
834            self.format(),
835            self.data().len(),
836            self.timecode(),
837            self.timestamp(),
838            self.metadata_status(),
839        )
840    }
841}
842
843impl<F: PacketFormat> Debug for ReceivedPacket<F> {
844    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845        debug_packet(
846            f,
847            "ReceivedPacket",
848            self.format(),
849            self.data().len(),
850            self.timecode(),
851            self.timestamp(),
852            self.metadata_status(),
853        )
854    }
855}
856
857impl<F: PacketFormat> Debug for CompressedRef<'_, F> {
858    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
859        debug_packet(
860            f,
861            "CompressedRef",
862            self.format(),
863            self.data().len(),
864            self.timecode(),
865            self.timestamp(),
866            self.metadata_status(),
867        )
868    }
869}
870
871impl<F: PacketFormat> Debug for ScatterFrame<F> {
872    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873        f.debug_struct("ScatterFrame")
874            .field("format", &self.format())
875            .field("blocks", &self.blocks().len())
876            .field("bytes", &self.total_bytes())
877            .field("timecode", &self.timecode())
878            .field("timestamp", &self.extras.timestamp())
879            .field("metadata_status", &self.metadata_status())
880            .finish()
881    }
882}