Skip to main content

grafton_ndi/frames/
layout.rs

1//! Validated layouts and borrowed active-element views.
2
3use super::*;
4
5#[cfg(all(test, feature = "advanced"))]
6pub(crate) mod layout_validation_counts {
7    use std::cell::Cell;
8
9    thread_local! {
10        pub(crate) static VIDEO: Cell<usize> = const { Cell::new(0) };
11        pub(crate) static AUDIO: Cell<usize> = const { Cell::new(0) };
12    }
13}
14
15/// Validated video frame layout information.
16///
17/// This struct holds pre-validated layout information for a video frame,
18/// with a plane table that determines every storage and payload quantity.
19/// Creating this struct performs all necessary bounds checking, so
20/// consumers can derive those quantities without re-validation.
21#[derive(Debug, Clone, Copy)]
22pub(crate) struct ValidatedVideoLayout {
23    /// The validated width in pixels.
24    width: u32,
25    /// The validated height in pixels.
26    height: u32,
27    /// The validated pixel format.
28    pixel_format: PixelFormat,
29    /// The authority for plane offsets, active rows and storage strides.
30    /// Unused trailing entries are zero; every extent and sum is validated.
31    plane_layouts: [VideoPlaneLayout; MAX_VIDEO_PLANES],
32}
33
34// The width, height and line stride of a valid layout are each at most its
35// storage extent, so every one of them fits the SDK's signed 32-bit fields.
36const_assert!({
37    assert!(usize::BITS >= 32);
38    assert!(MAX_VIDEO_BYTES <= i32::MAX as usize);
39    // An image row has at most eight bytes per validated source pixel.
40    assert!(MAX_VIDEO_BYTES <= usize::MAX / 8);
41    // Send room is at most 64 bytes plus two strides. A validated stride is
42    // at most the complete data size, even for a one-row frame.
43    assert!(3 * MAX_VIDEO_BYTES + 64 < usize::MAX);
44    assert!(MAX_METADATA_BYTES < i32::MAX as usize);
45});
46
47/// Plane views whose names carry the format's component ordering.
48#[cfg(feature = "image-encoding")]
49#[derive(Debug, Clone, Copy)]
50pub(crate) enum PlaneRoles<'a> {
51    PackedRgb {
52        pixels: VideoPlane<'a>,
53        order: RgbOrder,
54    },
55    Packed422 {
56        pixels: VideoPlane<'a>,
57    },
58    PackedAlpha {
59        pixels: VideoPlane<'a>,
60        alpha: VideoPlane<'a>,
61    },
62    SemiPlanar420 {
63        luma: VideoPlane<'a>,
64        chroma: VideoPlane<'a>,
65    },
66    Planar420 {
67        luma: VideoPlane<'a>,
68        cb: VideoPlane<'a>,
69        cr: VideoPlane<'a>,
70    },
71    SemiPlanar422 {
72        luma: VideoPlane<'a>,
73        chroma: VideoPlane<'a>,
74        alpha: Option<VideoPlane<'a>>,
75    },
76    Planar444 {
77        luma: VideoPlane<'a>,
78        cb: VideoPlane<'a>,
79        cr: VideoPlane<'a>,
80        alpha: Option<VideoPlane<'a>>,
81    },
82}
83
84/// Component order in a packed RGB plane.
85#[cfg(feature = "image-encoding")]
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) enum RgbOrder {
88    Rgb,
89    Bgr,
90}
91
92/// A video layout with contiguous active pixels and no row or plane padding.
93#[derive(Clone, Copy, Debug)]
94pub(crate) struct PackedVideoLayout(ValidatedVideoLayout);
95
96impl PackedVideoLayout {
97    pub(crate) fn new(format: PixelFormat, width: u32, height: u32) -> Result<Self> {
98        ValidatedVideoLayout::new_uncompressed(format, width, height, None).map(Self)
99    }
100
101    pub(crate) const fn as_layout(&self) -> &ValidatedVideoLayout {
102        &self.0
103    }
104}
105
106impl ValidatedVideoLayout {
107    /// Initialized active payload, excluding padding.
108    pub(crate) const fn payload_len_bytes(&self) -> usize {
109        let mut payload = 0;
110        let mut index = 0;
111        while index < self.plane_count() {
112            let plane = self.plane_layouts[index];
113            payload += plane.active_row_bytes * plane.row_count;
114            index += 1;
115        }
116        payload
117    }
118
119    /// The validated `width` value.
120    pub(crate) const fn width(&self) -> u32 {
121        self.width
122    }
123
124    /// The validated `height` value.
125    pub(crate) const fn height(&self) -> u32 {
126        self.height
127    }
128
129    /// The validated `pixel_format` value.
130    pub(crate) const fn pixel_format(&self) -> PixelFormat {
131        self.pixel_format
132    }
133
134    /// Complete storage extent in bytes; SDK padding need not be initialized.
135    pub(crate) const fn data_len_bytes(&self) -> usize {
136        let last = self.plane_layouts[self.plane_count() - 1];
137        last.offset + last.row_stride * last.row_count
138    }
139
140    /// The validated first-plane line stride in bytes.
141    pub(crate) const fn line_stride_bytes(&self) -> usize {
142        self.plane_layouts[0].row_stride
143    }
144
145    pub(super) const fn plane_count(&self) -> usize {
146        self.pixel_format.info().plane_count()
147    }
148
149    /// Validate an uncompressed layout. Only `None` selects the packed stride;
150    /// an explicit stride must be positive and hold the active row.
151    pub(crate) fn new_uncompressed(
152        pixel_format: PixelFormat,
153        width: u32,
154        height: u32,
155        line_stride: Option<usize>,
156    ) -> Result<Self> {
157        Self::new_uncompressed_checked(pixel_format, width, height, line_stride).map_err(Into::into)
158    }
159
160    pub(crate) fn new_uncompressed_checked(
161        pixel_format: PixelFormat,
162        width: u32,
163        height: u32,
164        line_stride: Option<usize>,
165    ) -> LayoutResult<Self> {
166        #[cfg(all(test, feature = "advanced"))]
167        layout_validation_counts::VIDEO.set(layout_validation_counts::VIDEO.get() + 1);
168
169        validate_video_dimensions(width.into(), height.into())?;
170
171        let minimum = min_video_line_stride(pixel_format, width);
172        // A row larger than the cap cannot describe a frame, even with a
173        // shorter explicit stride. Compute its full extent before narrowing
174        // so the refusal and byte count are identical on every target.
175        if minimum > MAX_VIDEO_BYTES as u64 {
176            let stride = line_stride.map_or(minimum, |stride| (stride as u64).max(minimum));
177            let info = pixel_format.info();
178            let dimensions = video_plane_dimensions(info, stride, minimum, height as u64)?;
179            let storage = video_storage_extent(&dimensions[..info.plane_count()]);
180            return Err(crate::LayoutDefect::VideoBytes(storage.into()));
181        }
182        let min_stride = minimum as usize;
183        let line_stride = match line_stride {
184            None => min_stride,
185            Some(0) => return Err(crate::LayoutDefect::VideoZeroStride),
186            Some(stride) if stride < min_stride => {
187                return Err(crate::LayoutDefect::VideoShortStride {
188                    stride,
189                    minimum: min_stride,
190                    format: pixel_format,
191                    width,
192                });
193            }
194            Some(stride) => stride,
195        };
196
197        let plane_layouts = video_plane_layouts(
198            pixel_format.info(),
199            line_stride as u64,
200            minimum,
201            height as u64,
202        )?;
203
204        Ok(Self {
205            width,
206            height,
207            pixel_format,
208            plane_layouts,
209        })
210    }
211
212    /// Validate the layout of an uncompressed SDK frame: `width`, `height`
213    /// and `line_stride` are the SDK's signed fields, and a zero stride
214    /// selects the packed stride.
215    pub(crate) fn from_sdk(
216        pixel_format: PixelFormat,
217        width: i32,
218        height: i32,
219        line_stride: i32,
220    ) -> Result<Self> {
221        Self::from_sdk_checked(pixel_format, width, height, line_stride).map_err(Into::into)
222    }
223
224    /// Validate SDK geometry without allocating even when it is rejected.
225    /// Allocator callbacks use this before any pixel storage exists.
226    pub(crate) fn from_sdk_checked(
227        pixel_format: PixelFormat,
228        width: i32,
229        height: i32,
230        line_stride: i32,
231    ) -> LayoutResult<Self> {
232        validate_video_dimensions(width.into(), height.into())?;
233        let line_stride = usize::try_from(line_stride)
234            .map_err(|_| crate::LayoutDefect::VideoSdkStride(line_stride))?;
235        // Both dimensions were just checked positive.
236        Self::new_uncompressed_checked(
237            pixel_format,
238            width.unsigned_abs(),
239            height.unsigned_abs(),
240            (line_stride != 0).then_some(line_stride),
241        )
242    }
243
244    /// This layout with every plane's rows packed, without padding: the
245    /// layout of an owned copy of the frame.
246    ///
247    /// It keeps each validated plane's active rows and closes the gaps: a
248    /// plane's stride becomes its active row and its offset the payload of
249    /// the planes before it, so the storage is exactly the active payload.
250    /// Nothing is computed that validation did not already bound: every
251    /// partial payload sum is at most the storage extent validation checked against
252    /// [`MAX_VIDEO_BYTES`]. It is the layout [`video_plane_layouts`] gives
253    /// the packed stride, `width` times the bytes per pixel, which a test
254    /// checks for every format.
255    pub(crate) fn packed(&self) -> PackedVideoLayout {
256        let mut plane_layouts = self.plane_layouts;
257        let mut offset = 0;
258        for plane in &mut plane_layouts[..self.plane_count()] {
259            plane.offset = offset;
260            plane.row_stride = plane.active_row_bytes;
261            offset += plane.active_row_bytes * plane.row_count;
262        }
263        PackedVideoLayout(Self {
264            plane_layouts,
265            ..*self
266        })
267    }
268
269    /// The SDK's `xres`.
270    pub(crate) fn sdk_width(&self) -> i32 {
271        self.width as i32
272    }
273
274    /// The SDK's `yres`.
275    pub(crate) fn sdk_height(&self) -> i32 {
276        self.height as i32
277    }
278
279    /// The SDK's `line_stride_in_bytes`.
280    pub(crate) fn sdk_line_stride(&self) -> i32 {
281        self.line_stride_bytes() as i32
282    }
283
284    /// The storage after the frame's last active byte: the padding of the
285    /// last row of the last plane, where the storage ends.
286    pub(crate) fn trailing_padding(&self) -> usize {
287        let last = self.plane_layouts[self.plane_count() - 1];
288        last.row_stride - last.active_row_bytes
289    }
290
291    pub(super) fn planes(&self) -> &[VideoPlaneLayout] {
292        &self.plane_layouts[..self.plane_count()]
293    }
294
295    /// One plane of the frame stored at `data`, or `None` for an invalid
296    /// index. Owned, borrowed and received frames share this view.
297    ///
298    /// # Safety
299    ///
300    /// `data` must point to storage this layout describes, with every active
301    /// row initialized and immutable for `'a`.
302    pub(super) unsafe fn view_plane<'a>(
303        &'a self,
304        data: *const u8,
305        index: usize,
306    ) -> Option<VideoPlane<'a>> {
307        let layout = *self.planes().get(index)?;
308        // SAFETY: forwarded to the caller.
309        Some(unsafe { VideoPlane::new(data, layout) })
310    }
311
312    /// Every plane of the frame stored at `data`, in SDK memory order.
313    ///
314    /// # Safety
315    ///
316    /// As for [`Self::view_plane`].
317    pub(crate) unsafe fn view_planes<'a>(&'a self, data: *const u8) -> VideoPlanes<'a> {
318        VideoPlanes {
319            data,
320            layouts: self.planes().iter(),
321        }
322    }
323
324    /// Every plane identified by its component role, including YV12's Cr/Cb order.
325    ///
326    /// # Safety
327    ///
328    /// As for [`Self::view_plane`].
329    #[cfg(feature = "image-encoding")]
330    pub(super) unsafe fn plane_roles<'a>(&'a self, data: *const u8) -> PlaneRoles<'a> {
331        let info = self.pixel_format.info();
332        // SAFETY: validation constructs the complete fixed plane table for the
333        // category; each constant index below names one of its active planes.
334        // The caller retains and initializes its storage for the returned borrow.
335        let plane = |index| unsafe { VideoPlane::new(data, self.plane_layouts[index]) };
336        match self.pixel_format {
337            PixelFormat::Rgba | PixelFormat::Rgbx => PlaneRoles::PackedRgb {
338                pixels: plane(0),
339                order: RgbOrder::Rgb,
340            },
341            PixelFormat::Bgra | PixelFormat::Bgrx => PlaneRoles::PackedRgb {
342                pixels: plane(0),
343                order: RgbOrder::Bgr,
344            },
345            PixelFormat::Uyvy => PlaneRoles::Packed422 { pixels: plane(0) },
346            PixelFormat::Uyva => PlaneRoles::PackedAlpha {
347                pixels: plane(0),
348                alpha: plane(1),
349            },
350            PixelFormat::Nv12 => PlaneRoles::SemiPlanar420 {
351                luma: plane(0),
352                chroma: plane(1),
353            },
354            PixelFormat::I420 | PixelFormat::Yv12 => {
355                let (cb, cr) = match info.chroma_order() {
356                    ChromaOrder::CbCr => (plane(1), plane(2)),
357                    ChromaOrder::CrCb => (plane(2), plane(1)),
358                };
359                PlaneRoles::Planar420 {
360                    luma: plane(0),
361                    cb,
362                    cr,
363                }
364            }
365            PixelFormat::P216 | PixelFormat::Pa16 => PlaneRoles::SemiPlanar422 {
366                luma: plane(0),
367                chroma: plane(1),
368                alpha: info.has_alpha().then(|| plane(2)),
369            },
370            PixelFormat::Na48 | PixelFormat::Nb48 | PixelFormat::Na4g | PixelFormat::Nb4g => {
371                PlaneRoles::Planar444 {
372                    luma: plane(0),
373                    cb: plane(1),
374                    cr: plane(2),
375                    alpha: info.has_alpha().then(|| plane(3)),
376                }
377            }
378        }
379    }
380
381    /// Every active byte of the frame stored at `data`, in SDK plane order,
382    /// or `None` when padding separates rows or planes. A single row may
383    /// have padding after it, which is not part of the bytes.
384    ///
385    /// The bytes are the one row of the span [`VideoPlaneLayout::contiguous`]
386    /// finds, read as [`VideoPlane::data`] reads a plane's, so a frame and
387    /// each of its planes share one contiguity rule and one slice.
388    ///
389    /// # Safety
390    ///
391    /// As for [`Self::view_plane`].
392    pub(super) unsafe fn view_data<'a>(&self, data: *const u8) -> Option<&'a [u8]> {
393        let span = VideoPlaneLayout::contiguous(self.planes())?;
394        // SAFETY: the span is one row of active bytes, from the first plane's
395        // offset to the end of the last plane's last active row, within the
396        // storage this layout describes. The caller keeps every active row
397        // initialized and immutable for `'a`.
398        unsafe { VideoPlane::new(data, span) }.data()
399    }
400}
401
402pub(crate) type LayoutResult<T> = std::result::Result<T, crate::LayoutDefect>;
403
404impl From<crate::LayoutDefect> for Error {
405    fn from(reason: crate::LayoutDefect) -> Self {
406        Self::InvalidFrame(crate::FrameDefect::Layout(reason))
407    }
408}
409
410/// The one dimension check, for values from the API and from the SDK.
411pub(super) fn validate_video_dimensions(width: i64, height: i64) -> LayoutResult<()> {
412    validate_video_width(width)?;
413    validate_video_height(height)
414}
415
416pub(super) fn validate_video_height(height: i64) -> LayoutResult<()> {
417    if height <= 0 {
418        return Err(crate::LayoutDefect::VideoHeight(height.into()));
419    }
420
421    Ok(())
422}
423
424pub(super) fn validate_video_width(width: i64) -> LayoutResult<()> {
425    if width <= 0 {
426        return Err(crate::LayoutDefect::VideoWidth(width.into()));
427    }
428
429    // The SDK uses 4:2:2 internally, including for RGB input/output.
430    // https://docs.ndi.video/all/developing-with-ndi/sdk/frame-types
431    if width % 2 != 0 {
432        return Err(crate::LayoutDefect::VideoOddWidth(width.into()));
433    }
434
435    Ok(())
436}
437
438pub(super) fn validate_video_data_len(data_len_bytes: u64) -> LayoutResult<()> {
439    debug_invariant!(
440        data_len_bytes > 0,
441        "validated dimensions and stride are positive"
442    );
443    if data_len_bytes > MAX_VIDEO_BYTES as u64 {
444        return Err(crate::LayoutDefect::VideoBytes(data_len_bytes.into()));
445    }
446    Ok(())
447}
448
449pub(super) fn min_video_line_stride(pixel_format: PixelFormat, width: u32) -> u64 {
450    u64::from(width) * u64::from(pixel_format.info().bytes_per_pixel())
451}
452
453/// Calculate buffer length with checked arithmetic.
454#[cfg(test)]
455pub(super) fn calculate_buffer_len_checked(
456    pixel_format: PixelFormat,
457    y_stride: usize,
458    height: usize,
459) -> Result<usize> {
460    calculate_buffer_len_for_info_checked(pixel_format.info(), y_stride, height)
461}
462
463#[cfg(test)]
464pub(super) fn calculate_buffer_len_for_info_checked(
465    info: PixelFormatInfo,
466    y_stride: usize,
467    height: usize,
468) -> Result<usize> {
469    video_plane_layouts(info, y_stride as u64, y_stride as u64, height as u64)
470        .map(|planes| {
471            let last = planes[info.plane_count() - 1];
472            last.offset + last.row_stride * last.row_count
473        })
474        .map_err(Into::into)
475}
476
477#[derive(Debug, Clone, Copy, Default)]
478pub(super) struct VideoPlaneLayout {
479    offset: usize,
480    row_stride: usize,
481    active_row_bytes: usize,
482    row_count: usize,
483}
484
485impl VideoPlaneLayout {
486    #[cfg(test)]
487    pub(super) fn offset(&self) -> usize {
488        self.offset
489    }
490    #[cfg(test)]
491    pub(super) fn row_stride(&self) -> usize {
492        self.row_stride
493    }
494    #[cfg(test)]
495    pub(super) fn active_row_bytes(&self) -> usize {
496        self.active_row_bytes
497    }
498    #[cfg(test)]
499    pub(super) fn row_count(&self) -> usize {
500        self.row_count
501    }
502
503    /// The active rows of `planes`, consecutive planes of one validated
504    /// frame, as one row, or `None` when padding separates their rows or the
505    /// planes: the one contiguity rule, for a frame and for each of its
506    /// planes. Padding after the last row is not part of the span.
507    pub(super) fn contiguous(planes: &[Self]) -> Option<Self> {
508        let start = planes.first()?.offset;
509        let mut end = start;
510        for plane in planes {
511            let rows_adjacent = plane.row_count == 1 || plane.row_stride == plane.active_row_bytes;
512            if plane.offset != end || !rows_adjacent {
513                return None;
514            }
515            // At most the plane's storage, which validation bounded.
516            end = plane.offset + plane.row_count * plane.active_row_bytes;
517        }
518        let len = end - start;
519        Some(Self {
520            offset: start,
521            row_stride: len,
522            active_row_bytes: len,
523            row_count: 1,
524        })
525    }
526}
527
528/// Derive SDK plane offsets and active row sizes together. See
529/// https://docs.ndi.video/all/developing-with-ndi/sdk/frame-types .
530/// Plane offsets include preceding storage padding; payload lengths do not.
531const MAX_VIDEO_PLANES: usize = 4;
532
533// Rows are (storage stride, active row bytes, row count). Keep them wide
534// until their complete storage extent has passed the frame size bound.
535fn video_plane_dimensions(
536    info: PixelFormatInfo,
537    stride: u64,
538    active: u64,
539    height: u64,
540) -> LayoutResult<[(u64, u64, u64); MAX_VIDEO_PLANES]> {
541    let mut dimensions = [(stride, active, height); MAX_VIDEO_PLANES];
542    match info.category() {
543        FormatCategory::Packed => {}
544        FormatCategory::Planar420 => {
545            if !height.is_multiple_of(2) || !stride.is_multiple_of(2) {
546                return Err(crate::LayoutDefect::VideoPlanar420 {
547                    height: height as usize,
548                    stride: stride as usize,
549                });
550            }
551            dimensions[1] = (stride / 2, active / 2, height / 2);
552            dimensions[2] = dimensions[1];
553        }
554        FormatCategory::SemiPlanar420 => {
555            if !height.is_multiple_of(2) {
556                return Err(crate::LayoutDefect::VideoSemiPlanar420(height as usize));
557            }
558            dimensions[1] = (stride, active, height / 2);
559        }
560        FormatCategory::PackedAlpha => {
561            if !stride.is_multiple_of(2) {
562                return Err(crate::LayoutDefect::VideoUyvaStride(stride as usize));
563            }
564            dimensions[1] = (stride / 2, active / 2, height);
565        }
566        FormatCategory::SemiPlanar422 => {}
567        FormatCategory::SemiPlanar422Alpha | FormatCategory::Planar444 => {}
568        FormatCategory::Planar444Alpha => {}
569    }
570    Ok(dimensions)
571}
572
573fn video_storage_extent(dimensions: &[(u64, u64, u64)]) -> u64 {
574    // Saturation retains one size cause even when an explicit stride near
575    // usize::MAX makes the mathematical extent exceed u64::MAX.
576    dimensions.iter().fold(0, |total, &(stride, _, rows)| {
577        total.saturating_add(stride.saturating_mul(rows))
578    })
579}
580
581fn video_plane_layouts(
582    info: PixelFormatInfo,
583    stride: u64,
584    active: u64,
585    height: u64,
586) -> LayoutResult<[VideoPlaneLayout; MAX_VIDEO_PLANES]> {
587    let dimensions = video_plane_dimensions(info, stride, active, height)?;
588    let dimensions = &dimensions[..info.plane_count()];
589    validate_video_data_len(video_storage_extent(dimensions))?;
590    let mut planes = [VideoPlaneLayout::default(); MAX_VIDEO_PLANES];
591    let mut offset = 0usize;
592    for (plane, &(row_stride, active_row_bytes, row_count)) in planes.iter_mut().zip(dimensions) {
593        // Each plane and partial sum fits the cap, which fits usize.
594        let (row_stride, active_row_bytes, row_count) = (
595            row_stride as usize,
596            active_row_bytes as usize,
597            row_count as usize,
598        );
599        *plane = VideoPlaneLayout {
600            offset,
601            row_stride,
602            active_row_bytes,
603            row_count,
604        };
605        offset += row_stride * row_count;
606        debug_invariant!(active_row_bytes <= row_stride);
607    }
608    // The complete storage extent and each partial sum fit MAX_VIDEO_BYTES.
609    // Active rows fit their strides, so payload products and sums fit too.
610    // Layout accessors and packed() can therefore derive either extent using
611    // ordinary usize arithmetic without overflow on any supported target.
612    Ok(planes)
613}
614
615/// Validated audio frame layout information.
616///
617/// This struct holds pre-validated layout information for a frame of audio
618/// samples, including the channel stride and computed backing sample count.
619/// Every layout describes at least one sample in at least one channel; audio
620/// the SDK returns without samples is classified by
621/// [`validate_returned_audio`] instead. Creating this struct performs all
622/// necessary bounds checking, so consumers can safely use the cached values
623/// without re-validation.
624#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
625pub(crate) struct ValidatedAudioLayout {
626    /// The validated audio format.
627    format: AudioFormat,
628    /// Quantities whose construction proves the SDK's signed range.
629    sample_rate: SdkQuantity,
630    no_channels: SdkQuantity,
631    no_samples: SdkQuantity,
632    /// An explicit padded stride in bytes, checked against the SDK range.
633    /// `None` stores channels back to back.
634    padded_stride: Option<SdkQuantity>,
635    /// The validated backing sample count. For strided planar audio this may be
636    /// larger than `no_channels * no_samples` because it includes inter-channel
637    /// padding up to the last channel's final sample.
638    sample_count: usize,
639}
640
641// Keep the layout no larger than the previous representation on every target.
642const_assert!({
643    #[allow(dead_code)]
644    struct PreviousLayout {
645        format: AudioFormat,
646        sample_rate: u32,
647        no_channels: usize,
648        no_samples: usize,
649        channel_stride_samples: usize,
650        sample_count: usize,
651    }
652    assert!(size_of::<ValidatedAudioLayout>() <= size_of::<PreviousLayout>());
653});
654
655/// Initialized audio channel slices in channel order, without allocation.
656///
657/// Inter-channel padding is never included. The iterator borrows the frame and
658/// keeps its sample storage alive; its immutable views support scoped thread
659/// transfer even when the owning capture must be freed on its original thread.
660#[derive(Clone)]
661pub struct AudioChannels<'a> {
662    data: *const f32,
663    layout: ValidatedAudioLayout,
664    indices: std::ops::Range<usize>,
665    lifetime: PhantomData<&'a [f32]>,
666}
667
668// SAFETY: Private fields restrict construction to validated channel views.
669// Its borrow keeps their aligned allocation alive for 'a. Each yielded slice
670// covers active initialized samples only. No operation accesses a native handle,
671// mutates samples or frees storage; frame destruction still follows owner rules.
672unsafe impl Send for AudioChannels<'_> {}
673// SAFETY: Sharing exposes only immutable samples and independent iterator state.
674unsafe impl Sync for AudioChannels<'_> {}
675
676impl fmt::Debug for AudioChannels<'_> {
677    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678        f.debug_struct("AudioChannels")
679            .field("remaining_channels", &self.len())
680            .field("samples_per_channel", &self.layout.no_samples())
681            .field(
682                "channel_stride_bytes",
683                &(self.layout.channel_stride_samples() * size_of::<f32>()),
684            )
685            .finish()
686    }
687}
688
689impl<'a> Iterator for AudioChannels<'a> {
690    type Item = &'a [f32];
691
692    fn next(&mut self) -> Option<Self::Item> {
693        let channel = self.indices.next()?;
694        // SAFETY: Construction retains validated immutable samples for 'a.
695        unsafe { self.layout.channel(self.data, channel) }
696    }
697
698    fn size_hint(&self) -> (usize, Option<usize>) {
699        self.indices.size_hint()
700    }
701}
702
703impl DoubleEndedIterator for AudioChannels<'_> {
704    fn next_back(&mut self) -> Option<Self::Item> {
705        let channel = self.indices.next_back()?;
706        // SAFETY: As for Iterator::next.
707        unsafe { self.layout.channel(self.data, channel) }
708    }
709}
710
711impl ExactSizeIterator for AudioChannels<'_> {}
712impl std::iter::FusedIterator for AudioChannels<'_> {}
713
714// Packed channel strides are bounded by the audio byte cap. Explicit padded
715// strides retain their own SDK-range proof, including for a single channel
716// whose stride does not contribute to its byte extent.
717const_assert!(MAX_AUDIO_BYTES <= i32::MAX as usize);
718
719impl ValidatedAudioLayout {
720    /// The validated `format` value.
721    pub(crate) const fn format(&self) -> AudioFormat {
722        self.format
723    }
724
725    /// The validated `sample_rate` value.
726    pub(crate) const fn sample_rate(&self) -> u32 {
727        self.sample_rate.get()
728    }
729
730    /// The validated `no_channels` value.
731    pub(crate) const fn no_channels(&self) -> usize {
732        self.no_channels.to_usize()
733    }
734
735    /// The validated `no_samples` value.
736    pub(crate) const fn no_samples(&self) -> usize {
737        self.no_samples.to_usize()
738    }
739
740    /// The validated `channel_stride_samples` value.
741    pub(crate) fn channel_stride_samples(&self) -> usize {
742        self.channel_stride_bytes() / size_of::<f32>()
743    }
744
745    /// Initialized samples only, excluding inter-channel padding.
746    pub(super) fn active_sample_count(&self) -> usize {
747        self.no_channels() * self.no_samples()
748    }
749
750    /// The validated `sample_count` value.
751    pub(crate) const fn sample_count(&self) -> usize {
752        self.sample_count
753    }
754
755    /// Validate caller-supplied audio geometry without constructing a descriptor.
756    /// Only `None` selects packed channels; an explicit stride must be positive.
757    pub(crate) fn new_uncompressed(
758        format: AudioFormat,
759        sample_rate: u32,
760        no_channels: u32,
761        no_samples: u32,
762        channel_stride: Option<usize>,
763    ) -> Result<Self> {
764        Self::new_uncompressed_checked(format, sample_rate, no_channels, no_samples, channel_stride)
765            .map_err(Into::into)
766    }
767
768    /// As `new_uncompressed`, retaining the cause for reusable input values.
769    pub(crate) fn new_uncompressed_checked(
770        format: AudioFormat,
771        sample_rate: u32,
772        no_channels: u32,
773        no_samples: u32,
774        channel_stride: Option<usize>,
775    ) -> LayoutResult<Self> {
776        Self::checked(
777            format,
778            sample_rate.into(),
779            no_channels.into(),
780            no_samples.into(),
781            channel_stride,
782        )
783    }
784
785    /// Validate signed SDK geometry. This does not examine a sample pointer;
786    /// capture validates that separately, while allocators have no storage yet.
787    pub(super) fn from_sdk(
788        format: AudioFormat,
789        sample_rate: i32,
790        no_channels: i32,
791        no_samples: i32,
792        channel_stride: Option<i32>,
793    ) -> Result<Self> {
794        Self::from_sdk_checked(format, sample_rate, no_channels, no_samples, channel_stride)
795            .map_err(Into::into)
796    }
797
798    /// As `from_sdk`, retaining an allocation-free failure for SDK callbacks.
799    pub(crate) fn from_sdk_checked(
800        format: AudioFormat,
801        sample_rate: i32,
802        no_channels: i32,
803        no_samples: i32,
804        channel_stride: Option<i32>,
805    ) -> LayoutResult<Self> {
806        let stride = channel_stride
807            .map(|stride| {
808                usize::try_from(stride).map_err(|_| crate::LayoutDefect::AudioStride(stride.into()))
809            })
810            .transpose()?;
811        Self::checked(
812            format,
813            sample_rate.into(),
814            no_channels.into(),
815            no_samples.into(),
816            stride,
817        )
818    }
819
820    /// Replace the stride through the same rule used for delivered audio.
821    #[cfg(feature = "advanced")]
822    pub(crate) fn with_channel_stride_bytes(self, stride: usize) -> LayoutResult<Self> {
823        Self::from_quantities(
824            self.format,
825            self.sample_rate,
826            self.no_channels,
827            self.no_samples,
828            Some(stride),
829        )
830    }
831
832    pub(super) fn checked(
833        format: AudioFormat,
834        sample_rate: i64,
835        no_channels: i64,
836        no_samples: i64,
837        channel_stride: Option<usize>,
838    ) -> LayoutResult<Self> {
839        let sample_rate = validate_audio_sample_rate(sample_rate)?;
840        let (no_channels, no_samples) = validate_positive_audio_counts(no_channels, no_samples)?;
841        Self::from_quantities(format, sample_rate, no_channels, no_samples, channel_stride)
842    }
843
844    /// Check only the extent and stride of quantities already in the SDK range.
845    pub(crate) fn from_quantities(
846        format: AudioFormat,
847        sample_rate: SdkQuantity,
848        no_channels: SdkQuantity,
849        no_samples: SdkQuantity,
850        channel_stride: Option<usize>,
851    ) -> LayoutResult<Self> {
852        #[cfg(all(test, feature = "advanced"))]
853        layout_validation_counts::AUDIO.set(layout_validation_counts::AUDIO.get() + 1);
854
855        let minimum = u64::from(no_samples.get()) * size_of::<f32>() as u64;
856        let stride = channel_stride.map_or(minimum, |stride| stride as u64);
857        let sample_count =
858            checked_audio_extent(no_channels, no_samples, stride / size_of::<f32>() as u64)?;
859        // The extent bounds the packed minimum even for a single channel.
860        let minimum = minimum as usize;
861        let stride = stride as usize;
862        let checked_stride = i64::try_from(stride)
863            .ok()
864            .and_then(SdkQuantity::new)
865            .ok_or_else(|| {
866                if stride == 0 {
867                    crate::LayoutDefect::AudioStride(0.into())
868                } else {
869                    crate::LayoutDefect::AudioStrideRange
870                }
871            })?;
872        if !stride.is_multiple_of(size_of::<f32>()) {
873            return Err(crate::LayoutDefect::AudioStrideAlignment(stride));
874        }
875        if stride < minimum {
876            return Err(crate::LayoutDefect::AudioShortStride { stride, minimum });
877        }
878        let padded_stride = (stride != minimum).then_some(checked_stride);
879        Ok(Self {
880            format,
881            sample_rate,
882            no_channels,
883            no_samples,
884            padded_stride,
885            sample_count,
886        })
887    }
888
889    /// The same frame with channels stored back to back, without padding.
890    pub(crate) fn packed(self) -> PackedAudioLayout {
891        PackedAudioLayout(Self {
892            padded_stride: None,
893            sample_count: self.no_channels() * self.no_samples(),
894            ..self
895        })
896    }
897
898    pub(crate) fn num_channels(self) -> u32 {
899        self.no_channels.get()
900    }
901
902    pub(crate) fn num_samples(self) -> u32 {
903        self.no_samples.get()
904    }
905
906    pub(crate) fn channel_stride_bytes(self) -> usize {
907        self.padded_stride.map_or_else(
908            || self.no_samples() * size_of::<f32>(),
909            SdkQuantity::to_usize,
910        )
911    }
912
913    /// The SDK's `sample_rate`.
914    pub(crate) fn sdk_sample_rate(self) -> i32 {
915        self.sample_rate.to_sdk()
916    }
917
918    /// The SDK's `no_channels`.
919    pub(crate) fn sdk_num_channels(self) -> i32 {
920        self.no_channels.to_sdk()
921    }
922
923    /// The SDK's `no_samples`.
924    pub(crate) fn sdk_num_samples(self) -> i32 {
925        self.no_samples.to_sdk()
926    }
927
928    /// The SDK's `channel_stride_in_bytes`.
929    pub(crate) fn sdk_channel_stride(self) -> i32 {
930        self.padded_stride.map_or_else(
931            // Packed stride fits the audio byte cap, which is at most i32::MAX.
932            || (self.no_samples() * size_of::<f32>()) as i32,
933            SdkQuantity::to_sdk,
934        )
935    }
936
937    pub(crate) fn channel_range(self, channel: usize) -> Option<std::ops::Range<usize>> {
938        if channel >= self.no_channels() {
939            return None;
940        }
941
942        // checked_audio_extent proved the last channel's offset plus its
943        // samples fits usize and sample_count; every earlier channel fits too.
944        // packed() preserves that proof when removing inter-channel padding.
945        let start = channel * self.channel_stride_samples();
946        let end = start + self.no_samples();
947        debug_invariant!(end <= self.sample_count);
948        Some(start..end)
949    }
950
951    /// One channel's samples of the frame stored at `data`, or `None` for an
952    /// invalid channel. Owned and received frames share this view.
953    ///
954    /// # Safety
955    ///
956    /// `data` must point to `f32`-aligned storage this layout describes, with
957    /// every channel's samples initialized and immutable for `'a`.
958    pub(super) unsafe fn channel<'a>(self, data: *const f32, channel: usize) -> Option<&'a [f32]> {
959        let range = self.channel_range(channel)?;
960        // SAFETY: checked_audio_extent and packed() prove every channel's
961        // range fits the initialized storage the caller keeps borrowed.
962        Some(unsafe { slice::from_raw_parts(data.add(range.start), self.no_samples()) })
963    }
964
965    /// Every channel's samples of the frame stored at `data`, in order,
966    /// without reading inter-channel padding.
967    ///
968    /// # Safety
969    ///
970    /// As for [`Self::channel`].
971    pub(crate) unsafe fn channels<'a>(self, data: *const f32) -> AudioChannels<'a> {
972        AudioChannels {
973            data,
974            layout: self,
975            indices: 0..self.no_channels(),
976            lifetime: PhantomData,
977        }
978    }
979
980    /// Every sample of the frame stored at `data`, channels back to back, or
981    /// `None` when padding separates channels: the one contiguity rule for
982    /// audio, beside the channel views. An owned frame's channels are always
983    /// back to back.
984    ///
985    /// # Safety
986    ///
987    /// As for [`Self::channel`].
988    pub(super) unsafe fn view_samples<'a>(self, data: *const f32) -> Option<&'a [f32]> {
989        if self.no_channels() > 1 && self.padded_stride.is_some() {
990            return None;
991        }
992        // SAFETY: with one channel, or channels back to back, the
993        // `sample_count` samples from `data` are every channel's samples and
994        // nothing else, which the caller keeps aligned, initialized and
995        // immutable for `'a`.
996        Some(unsafe { slice::from_raw_parts(data, self.sample_count) })
997    }
998}
999
1000pub(super) fn validate_outbound_audio_layout(
1001    sample_rate: u32,
1002    no_channels: u32,
1003    no_samples: u32,
1004    format: AudioFormat,
1005) -> Result<PackedAudioLayout> {
1006    ValidatedAudioLayout::new_uncompressed(format, sample_rate, no_channels, no_samples, None)
1007        .map(PackedAudioLayout)
1008}
1009
1010/// An audio layout whose planar channels are stored back to back.
1011#[derive(Clone, Copy, Debug)]
1012pub(crate) struct PackedAudioLayout(ValidatedAudioLayout);
1013
1014impl PackedAudioLayout {
1015    pub(crate) const fn as_layout(&self) -> &ValidatedAudioLayout {
1016        &self.0
1017    }
1018}
1019
1020/// The one sample-rate check for every audio path, for values from the API
1021/// and from the SDK: `1..=i32::MAX` Hz.
1022pub(crate) fn validate_audio_sample_rate(sample_rate: i64) -> LayoutResult<SdkQuantity> {
1023    SdkQuantity::new(sample_rate).ok_or(crate::LayoutDefect::AudioRate(sample_rate.into()))
1024}
1025
1026/// The one audio count rule for channels and samples: `1..=i32::MAX`.
1027pub(crate) fn validate_audio_count(
1028    value: i64,
1029    kind: crate::AudioCountKind,
1030) -> LayoutResult<SdkQuantity> {
1031    SdkQuantity::new(value).ok_or(crate::LayoutDefect::AudioCount {
1032        value: value.into(),
1033        kind,
1034    })
1035}
1036
1037/// A zero SDK field means the source quantity is not known yet. Every known
1038/// quantity follows the same rule as a frame that contains samples.
1039pub(super) fn optional_audio_quantity(
1040    value: i64,
1041    check: impl FnOnce(i64) -> LayoutResult<SdkQuantity>,
1042) -> LayoutResult<Option<SdkQuantity>> {
1043    if value == 0 {
1044        Ok(None)
1045    } else {
1046        check(value).map(Some)
1047    }
1048}
1049
1050/// Retain the signed-range proof for channel and sample counts.
1051pub(crate) fn validate_positive_audio_counts(
1052    no_channels: i64,
1053    no_samples: i64,
1054) -> LayoutResult<(SdkQuantity, SdkQuantity)> {
1055    Ok((
1056        validate_audio_count(no_channels, crate::AudioCountKind::Channels)?,
1057        validate_audio_count(no_samples, crate::AudioCountKind::Samples)?,
1058    ))
1059}
1060
1061/// The one audio extent calculation. Returns the backing sample count from the
1062/// first sample of the first channel to the last sample of the last channel
1063/// when channels start `stride_samples` apart, enforcing `MAX_AUDIO_BYTES`.
1064/// Packed audio is the case `stride_samples == no_samples`.
1065pub(crate) fn checked_audio_extent(
1066    no_channels: SdkQuantity,
1067    no_samples: SdkQuantity,
1068    stride_samples: u64,
1069) -> LayoutResult<usize> {
1070    // The retained nonzero count proof makes this subtraction infallible.
1071    let sample_count = u64::from(no_channels.get() - 1)
1072        .saturating_mul(stride_samples)
1073        .saturating_add(u64::from(no_samples.get()));
1074    let byte_size = sample_count.saturating_mul(size_of::<f32>() as u64);
1075    if byte_size > MAX_AUDIO_BYTES as u64 {
1076        return Err(crate::LayoutDefect::AudioBytes(byte_size.into()));
1077    }
1078    Ok(sample_count as usize)
1079}
1080
1081/// An allocation-free view of one video plane's initialized active bytes.
1082///
1083/// Plane order follows the pixel format: packed pixels; UYVY/A for UYVA;
1084/// Y/CbCr[/A] for P216/PA16; Y/V/U for YV12; Y/U/V for I420; Y/UV for NV12;
1085/// Y/U/V[/A] for the planar 4:4:4 formats. The view borrows its frame, owned
1086/// or captured, which keeps the allocation alive.
1087/// Immutable pixel views are `Send + Sync`, including views borrowed from
1088/// FrameSync. Scoped workers must finish before the frame is freed. This does
1089/// not transfer the SDK-owning frame reference or change its freeing thread.
1090///
1091/// ```no_run
1092/// # fn read(frame: &grafton_ndi::FrameSyncVideoRef<'_>) {
1093/// let plane = frame.plane(0).unwrap();
1094/// let rows = plane.rows();
1095/// std::thread::scope(|scope| {
1096///     let worker = scope.spawn(move || {
1097///         rows.flatten().map(|&byte| u64::from(byte)).sum::<u64>()
1098///     });
1099///     assert_eq!(worker.join().unwrap(),
1100///         plane.rows().flatten().map(|&byte| u64::from(byte)).sum::<u64>());
1101/// });
1102/// # }
1103/// ```
1104#[derive(Clone, Copy)]
1105pub struct VideoPlane<'a> {
1106    data: *const u8,
1107    layout: VideoPlaneLayout,
1108    lifetime: PhantomData<&'a [u8]>,
1109}
1110
1111// SAFETY: Every private construction site retains one allocation for 'a and
1112// validates all offsets, strides, and active lengths before constructing views.
1113// Active bytes are initialized and immutable for 'a; padding is never sliced.
1114// Reads require only u8 alignment (1) and expose the same &'a [u8] already
1115// returned by row/data. Copying or sharing a view grants no mutation or SDK
1116// access. Views have no destructor/free operation. Their borrow retains the
1117// captured guard until all workers finish, so FrameSync still frees its frame
1118// on the capture thread. Owned-slice construction likewise retains its borrow.
1119// SDK ownership/free boundary: Processing.NDI.Recv.h (capture_v3/free_video_v2)
1120// and Processing.NDI.FrameSync.h (capture_video/free_video).
1121unsafe impl Send for VideoPlane<'_> {}
1122// SAFETY: Same immutable access and lifetime proof as Send above.
1123unsafe impl Sync for VideoPlane<'_> {}
1124
1125// This formatter reads only validated extents, never the plane's allocation.
1126struct PlaneExtent<'a>(&'a VideoPlaneLayout);
1127
1128impl fmt::Debug for PlaneExtent<'_> {
1129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1130        f.debug_struct("VideoPlane")
1131            .field("row_stride_bytes", &self.0.row_stride)
1132            .field("active_row_bytes", &self.0.active_row_bytes)
1133            .field("row_count", &self.0.row_count)
1134            .finish()
1135    }
1136}
1137
1138impl fmt::Debug for VideoPlane<'_> {
1139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1140        PlaneExtent(&self.layout).fmt(f)
1141    }
1142}
1143
1144impl<'a> VideoPlane<'a> {
1145    /// Caller must retain an allocation covering the validated layout for 'a,
1146    /// with every active row readable, initialized, and immutable for that lifetime.
1147    unsafe fn new(data: *const u8, layout: VideoPlaneLayout) -> Self {
1148        Self {
1149            data,
1150            layout,
1151            lifetime: PhantomData,
1152        }
1153    }
1154
1155    /// Distance between row starts in bytes, including padding.
1156    pub fn row_stride_bytes(&self) -> usize {
1157        self.layout.row_stride
1158    }
1159
1160    /// Number of initialized bytes in each row.
1161    pub fn active_row_bytes(&self) -> usize {
1162        self.layout.active_row_bytes
1163    }
1164
1165    /// Number of rows in this plane.
1166    pub fn row_count(&self) -> usize {
1167        self.layout.row_count
1168    }
1169
1170    /// Get an active row, excluding padding, or `None` for an invalid index.
1171    pub fn row(&self, index: usize) -> Option<&'a [u8]> {
1172        if index >= self.layout.row_count {
1173            return None;
1174        }
1175        // SAFETY: Construction ties the allocation to 'a. Checked plane/row
1176        // arithmetic bounds this range within storage. The SDK initializes the
1177        // active bytes; padding is never included. The guard prevents freeing.
1178        Some(unsafe {
1179            slice::from_raw_parts(
1180                self.data
1181                    .add(self.layout.offset + index * self.layout.row_stride),
1182                self.layout.active_row_bytes,
1183            )
1184        })
1185    }
1186
1187    /// Iterate active rows without allocating or copying pixels.
1188    pub fn rows(&self) -> VideoRows<'a> {
1189        VideoRows {
1190            plane: *self,
1191            indices: 0..self.row_count(),
1192        }
1193    }
1194
1195    /// Borrow all active bytes when contiguous, excluding trailing padding.
1196    /// Returns `None` when padding separates rows.
1197    pub fn data(&self) -> Option<&'a [u8]> {
1198        let span = VideoPlaneLayout::contiguous(slice::from_ref(&self.layout))?;
1199        // SAFETY: Construction ties the allocation to 'a. The span is this
1200        // plane's rows, adjacent and active, so every byte is initialized and
1201        // within its checked storage; the final row's padding is excluded.
1202        Some(unsafe { slice::from_raw_parts(self.data.add(span.offset), span.active_row_bytes) })
1203    }
1204}
1205
1206/// Active video rows, borrowing the frame that owns the allocation.
1207/// `Send + Sync` through its immutable plane; iteration never calls the SDK.
1208#[derive(Clone)]
1209pub struct VideoRows<'a> {
1210    plane: VideoPlane<'a>,
1211    indices: std::ops::Range<usize>,
1212}
1213
1214impl fmt::Debug for VideoRows<'_> {
1215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216        f.debug_struct("VideoRows")
1217            .field("remaining_rows", &self.len())
1218            .field("row_stride_bytes", &self.plane.row_stride_bytes())
1219            .field("active_row_bytes", &self.plane.active_row_bytes())
1220            .finish()
1221    }
1222}
1223
1224impl<'a> Iterator for VideoRows<'a> {
1225    type Item = &'a [u8];
1226    fn next(&mut self) -> Option<Self::Item> {
1227        self.plane.row(self.indices.next()?)
1228    }
1229    fn size_hint(&self) -> (usize, Option<usize>) {
1230        self.indices.size_hint()
1231    }
1232}
1233impl DoubleEndedIterator for VideoRows<'_> {
1234    fn next_back(&mut self) -> Option<Self::Item> {
1235        self.plane.row(self.indices.next_back()?)
1236    }
1237}
1238impl ExactSizeIterator for VideoRows<'_> {}
1239impl std::iter::FusedIterator for VideoRows<'_> {}
1240
1241/// Video planes in SDK memory order, with no allocation or pixel copies.
1242/// `Send + Sync` for scoped reads; the owning frame's thread rules still apply.
1243#[derive(Clone)]
1244pub struct VideoPlanes<'a> {
1245    data: *const u8,
1246    layouts: slice::Iter<'a, VideoPlaneLayout>,
1247}
1248// SAFETY: Private fields restrict construction to the validated layout
1249// view constructors for a live frame. The shared layout slice and data borrow last for 'a; each yielded plane
1250// satisfies VideoPlane's immutable, initialized, bounded u8 access proof above.
1251// Iterator state is exclusively mutated, clones are independent, and neither
1252// iteration nor dropping it accesses an SDK handle or frees the allocation.
1253unsafe impl Send for VideoPlanes<'_> {}
1254// SAFETY: Sharing the iterator exposes only immutable layouts and bytes.
1255unsafe impl Sync for VideoPlanes<'_> {}
1256impl fmt::Debug for VideoPlanes<'_> {
1257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258        let mut summary = f.debug_struct("VideoPlanes");
1259        summary.field("remaining_planes", &self.len());
1260        for layout in self.layouts.as_slice() {
1261            summary.field("plane", &PlaneExtent(layout));
1262        }
1263        summary.finish()
1264    }
1265}
1266
1267impl<'a> Iterator for VideoPlanes<'a> {
1268    type Item = VideoPlane<'a>;
1269    fn next(&mut self) -> Option<Self::Item> {
1270        let layout = *self.layouts.next()?;
1271        // SAFETY: Private iterator fields retain a live frame with validated rows.
1272        Some(unsafe { VideoPlane::new(self.data, layout) })
1273    }
1274    fn size_hint(&self) -> (usize, Option<usize>) {
1275        self.layouts.size_hint()
1276    }
1277}
1278impl ExactSizeIterator for VideoPlanes<'_> {}
1279impl std::iter::FusedIterator for VideoPlanes<'_> {}