1use 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#[derive(Debug, Clone, Copy)]
22pub(crate) struct ValidatedVideoLayout {
23 width: u32,
25 height: u32,
27 pixel_format: PixelFormat,
29 plane_layouts: [VideoPlaneLayout; MAX_VIDEO_PLANES],
32}
33
34const_assert!({
37 assert!(usize::BITS >= 32);
38 assert!(MAX_VIDEO_BYTES <= i32::MAX as usize);
39 assert!(MAX_VIDEO_BYTES <= usize::MAX / 8);
41 assert!(3 * MAX_VIDEO_BYTES + 64 < usize::MAX);
44 assert!(MAX_METADATA_BYTES < i32::MAX as usize);
45});
46
47#[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#[cfg(feature = "image-encoding")]
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub(crate) enum RgbOrder {
88 Rgb,
89 Bgr,
90}
91
92#[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 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 pub(crate) const fn width(&self) -> u32 {
121 self.width
122 }
123
124 pub(crate) const fn height(&self) -> u32 {
126 self.height
127 }
128
129 pub(crate) const fn pixel_format(&self) -> PixelFormat {
131 self.pixel_format
132 }
133
134 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 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 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 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 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 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 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 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 pub(crate) fn sdk_width(&self) -> i32 {
271 self.width as i32
272 }
273
274 pub(crate) fn sdk_height(&self) -> i32 {
276 self.height as i32
277 }
278
279 pub(crate) fn sdk_line_stride(&self) -> i32 {
281 self.line_stride_bytes() as i32
282 }
283
284 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 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 Some(unsafe { VideoPlane::new(data, layout) })
310 }
311
312 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 #[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 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 pub(super) unsafe fn view_data<'a>(&self, data: *const u8) -> Option<&'a [u8]> {
393 let span = VideoPlaneLayout::contiguous(self.planes())?;
394 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
410pub(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 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#[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 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 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
528const MAX_VIDEO_PLANES: usize = 4;
532
533fn 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 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 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 Ok(planes)
613}
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
625pub(crate) struct ValidatedAudioLayout {
626 format: AudioFormat,
628 sample_rate: SdkQuantity,
630 no_channels: SdkQuantity,
631 no_samples: SdkQuantity,
632 padded_stride: Option<SdkQuantity>,
635 sample_count: usize,
639}
640
641const_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#[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
668unsafe impl Send for AudioChannels<'_> {}
673unsafe 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 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 unsafe { self.layout.channel(self.data, channel) }
708 }
709}
710
711impl ExactSizeIterator for AudioChannels<'_> {}
712impl std::iter::FusedIterator for AudioChannels<'_> {}
713
714const_assert!(MAX_AUDIO_BYTES <= i32::MAX as usize);
718
719impl ValidatedAudioLayout {
720 pub(crate) const fn format(&self) -> AudioFormat {
722 self.format
723 }
724
725 pub(crate) const fn sample_rate(&self) -> u32 {
727 self.sample_rate.get()
728 }
729
730 pub(crate) const fn no_channels(&self) -> usize {
732 self.no_channels.to_usize()
733 }
734
735 pub(crate) const fn no_samples(&self) -> usize {
737 self.no_samples.to_usize()
738 }
739
740 pub(crate) fn channel_stride_samples(&self) -> usize {
742 self.channel_stride_bytes() / size_of::<f32>()
743 }
744
745 pub(super) fn active_sample_count(&self) -> usize {
747 self.no_channels() * self.no_samples()
748 }
749
750 pub(crate) const fn sample_count(&self) -> usize {
752 self.sample_count
753 }
754
755 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 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 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 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 #[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 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 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 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 pub(crate) fn sdk_sample_rate(self) -> i32 {
915 self.sample_rate.to_sdk()
916 }
917
918 pub(crate) fn sdk_num_channels(self) -> i32 {
920 self.no_channels.to_sdk()
921 }
922
923 pub(crate) fn sdk_num_samples(self) -> i32 {
925 self.no_samples.to_sdk()
926 }
927
928 pub(crate) fn sdk_channel_stride(self) -> i32 {
930 self.padded_stride.map_or_else(
931 || (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 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 pub(super) unsafe fn channel<'a>(self, data: *const f32, channel: usize) -> Option<&'a [f32]> {
959 let range = self.channel_range(channel)?;
960 Some(unsafe { slice::from_raw_parts(data.add(range.start), self.no_samples()) })
963 }
964
965 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 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 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#[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
1020pub(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
1026pub(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
1037pub(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
1050pub(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
1061pub(crate) fn checked_audio_extent(
1066 no_channels: SdkQuantity,
1067 no_samples: SdkQuantity,
1068 stride_samples: u64,
1069) -> LayoutResult<usize> {
1070 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#[derive(Clone, Copy)]
1105pub struct VideoPlane<'a> {
1106 data: *const u8,
1107 layout: VideoPlaneLayout,
1108 lifetime: PhantomData<&'a [u8]>,
1109}
1110
1111unsafe impl Send for VideoPlane<'_> {}
1122unsafe impl Sync for VideoPlane<'_> {}
1124
1125struct 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 unsafe fn new(data: *const u8, layout: VideoPlaneLayout) -> Self {
1148 Self {
1149 data,
1150 layout,
1151 lifetime: PhantomData,
1152 }
1153 }
1154
1155 pub fn row_stride_bytes(&self) -> usize {
1157 self.layout.row_stride
1158 }
1159
1160 pub fn active_row_bytes(&self) -> usize {
1162 self.layout.active_row_bytes
1163 }
1164
1165 pub fn row_count(&self) -> usize {
1167 self.layout.row_count
1168 }
1169
1170 pub fn row(&self, index: usize) -> Option<&'a [u8]> {
1172 if index >= self.layout.row_count {
1173 return None;
1174 }
1175 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 pub fn rows(&self) -> VideoRows<'a> {
1189 VideoRows {
1190 plane: *self,
1191 indices: 0..self.row_count(),
1192 }
1193 }
1194
1195 pub fn data(&self) -> Option<&'a [u8]> {
1198 let span = VideoPlaneLayout::contiguous(slice::from_ref(&self.layout))?;
1199 Some(unsafe { slice::from_raw_parts(self.data.add(span.offset), span.active_row_bytes) })
1203 }
1204}
1205
1206#[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#[derive(Clone)]
1244pub struct VideoPlanes<'a> {
1245 data: *const u8,
1246 layouts: slice::Iter<'a, VideoPlaneLayout>,
1247}
1248unsafe impl Send for VideoPlanes<'_> {}
1254unsafe 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 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<'_> {}