1use std::{rc::Rc, sync::Arc, time::Duration};
4
5use crate::{Engine, Error, Event, Image, Matrix, Result, Texture, runtime::NativeDecodedFrame};
6
7use super::{
8 VideoPixelFormat,
9 plane::{DevicePlanar, plane_count, plane_extents},
10};
11pub use crate::video::types::VideoColorInfo;
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum VideoColorMatrix {
20 Unspecified,
22 Bt601,
24 Bt709,
26 Bt2020,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum VideoColorRange {
33 Unspecified,
35 Limited,
37 Full,
39}
40
41impl VideoColorInfo {
42 pub const fn new(matrix: VideoColorMatrix, range: VideoColorRange) -> Self {
44 Self { matrix, range }
45 }
46
47 pub const fn unspecified() -> Self {
49 Self::new(VideoColorMatrix::Unspecified, VideoColorRange::Unspecified)
50 }
51
52 pub const fn matrix(self) -> VideoColorMatrix {
54 self.matrix
55 }
56
57 pub const fn range(self) -> VideoColorRange {
59 self.range
60 }
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct VideoFrameTiming {
69 presentation_timestamp: Duration,
70 duration: Option<Duration>,
71}
72
73impl VideoFrameTiming {
74 pub fn new(presentation_timestamp: Duration, duration: Option<Duration>) -> Result<Self> {
80 if duration == Some(Duration::ZERO) {
81 return Err(Error::invalid_argument(
82 "video frame duration must be non-zero when specified",
83 ));
84 }
85 Ok(Self {
86 presentation_timestamp,
87 duration,
88 })
89 }
90
91 pub fn new_from_microseconds(
95 presentation_timestamp_microseconds: u64,
96 duration_microseconds: u64,
97 ) -> Self {
98 Self {
99 presentation_timestamp: Duration::from_micros(presentation_timestamp_microseconds),
100 duration: (duration_microseconds != 0)
101 .then_some(Duration::from_micros(duration_microseconds)),
102 }
103 }
104
105 pub const fn presentation_timestamp(self) -> Duration {
107 self.presentation_timestamp
108 }
109
110 pub const fn duration(self) -> Option<Duration> {
112 self.duration
113 }
114}
115
116#[derive(Clone)]
123pub struct VideoFrame {
124 backing: VideoFrameBacking,
125 timing: VideoFrameTiming,
126 color: VideoColorInfo,
127}
128
129#[derive(Clone, Copy)]
131pub(crate) struct CanvasYuvLayout {
132 pub extent: super::VideoExtent,
133 pub format: VideoPixelFormat,
134 pub sample_bits: u32,
135 pub cb_offset: u32,
136 pub cr_offset: u32,
137 pub interleaved: bool,
138}
139
140impl VideoFrame {
141 pub(crate) const fn native_backing(&self) -> Option<&NativeDecodedFrame> {
142 match &self.backing {
143 VideoFrameBacking::Native(frame) => Some(frame),
144 _ => None,
145 }
146 }
147
148 pub(crate) fn from_native(
149 frame: NativeDecodedFrame,
150 timing: VideoFrameTiming,
151 color: VideoColorInfo,
152 ) -> Self {
153 Self {
154 backing: VideoFrameBacking::Native(frame),
155 timing,
156 color,
157 }
158 }
159
160 pub(crate) fn from_texture(
161 texture: Texture,
162 timing: VideoFrameTiming,
163 color: VideoColorInfo,
164 ready: Option<Event>,
165 ) -> Self {
166 Self {
167 backing: VideoFrameBacking::Texture { texture, ready },
168 timing,
169 color,
170 }
171 }
172
173 pub(crate) fn with_canvas_planes(
174 &self,
175 storage: crate::runtime::Storage,
176 layout: CanvasYuvLayout,
177 ) -> Self {
178 Self {
179 backing: VideoFrameBacking::CanvasYuv { storage, layout },
180 timing: self.timing,
181 color: self.color,
182 }
183 }
184
185 pub(crate) fn canvas_planes(&self) -> Option<(&crate::runtime::Storage, CanvasYuvLayout)> {
186 match &self.backing {
187 VideoFrameBacking::CanvasYuv { storage, layout } => Some((storage, *layout)),
188 _ => None,
189 }
190 }
191
192 pub fn new_from_image(
203 image: Image,
204 timing: VideoFrameTiming,
205 color: VideoColorInfo,
206 ) -> Result<Self> {
207 if image.batch_size() != 1 {
208 return Err(Error::invalid_argument(format!(
209 "video frame requires one image, but the batch extent is {}",
210 image.batch_size()
211 )));
212 }
213 if image.width() == 0 || image.height() == 0 {
214 return Err(Error::invalid_argument(
215 "video frame width and height must be non-zero",
216 ));
217 }
218 Ok(Self {
219 backing: VideoFrameBacking::PackedImage(image),
220 timing,
221 color,
222 })
223 }
224
225 pub fn upload_planes(
245 format: VideoPixelFormat,
246 planes: Vec<Vec<u8>>,
247 width: usize,
248 height: usize,
249 timing: VideoFrameTiming,
250 color: VideoColorInfo,
251 ) -> Result<Self> {
252 Self::upload_planes_on(
253 &Engine::current()?,
254 format,
255 planes,
256 width,
257 height,
258 timing,
259 color,
260 )
261 }
262
263 pub fn upload_planes_on(
273 engine: &Engine,
274 format: VideoPixelFormat,
275 planes: Vec<Vec<u8>>,
276 width: usize,
277 height: usize,
278 timing: VideoFrameTiming,
279 color: VideoColorInfo,
280 ) -> Result<Self> {
281 if planes.len() != plane_count(format) {
282 return Err(Error::invalid_argument(format!(
283 "{format:?} requires {} planes, but {} were provided",
284 plane_count(format),
285 planes.len()
286 )));
287 }
288 let extents = plane_extents(format, width, height)?;
289 let mut matrices = Vec::with_capacity(planes.len());
290 for (bytes, extent) in planes.iter().zip(extents.iter()) {
291 let expected = extent
292 .width
293 .checked_mul(extent.height)
294 .ok_or_else(|| Error::out_of_range("plane byte extent overflows usize"))?;
295 if bytes.len() != expected {
296 return Err(Error::invalid_argument(format!(
297 "plane requires {expected} bytes, but {} were provided",
298 bytes.len()
299 )));
300 }
301 matrices.push(Matrix::new_from_slice_on(
302 engine,
303 [extent.height, extent.width],
304 bytes,
305 )?);
306 }
307 Ok(Self {
308 backing: VideoFrameBacking::DevicePlanar(DevicePlanar {
309 planes: Rc::new(matrices),
310 format,
311 width,
312 height,
313 }),
314 timing,
315 color,
316 })
317 }
318
319 pub fn upload(&self) -> Result<VideoFrame> {
331 self.upload_on(&Engine::current()?)
332 }
333
334 pub fn upload_on(&self, engine: &Engine) -> Result<VideoFrame> {
344 match &self.backing {
345 VideoFrameBacking::DevicePlanar(_) => Ok(self.clone()),
346 VideoFrameBacking::PlanarYuv420 {
347 bytes,
348 width,
349 height,
350 } => {
351 let width = *width;
352 let height = *height;
353 let luma = width * height;
354 let chroma = luma / 4;
355 let planes = vec![
356 bytes[..luma].to_vec(),
357 bytes[luma..luma + chroma].to_vec(),
358 bytes[luma + chroma..].to_vec(),
359 ];
360 Self::upload_planes_on(
361 engine,
362 VideoPixelFormat::Yuv420Planar8,
363 planes,
364 width,
365 height,
366 self.timing,
367 self.color,
368 )
369 }
370 VideoFrameBacking::PackedImage(_)
371 | VideoFrameBacking::CanvasYuv { .. }
372 | VideoFrameBacking::Texture { .. }
373 | VideoFrameBacking::PlanarYuv420P10 { .. }
374 | VideoFrameBacking::Native(_) => Err(Error::failed_precondition(
375 "upload applies to 8-bit host-planar or device-planar video frames",
376 )),
377 }
378 }
379
380 pub(crate) fn from_device_planar(
382 planar: DevicePlanar,
383 timing: VideoFrameTiming,
384 color: VideoColorInfo,
385 ) -> Self {
386 Self {
387 backing: VideoFrameBacking::DevicePlanar(planar),
388 timing,
389 color,
390 }
391 }
392
393 pub fn new_from_yuv420p(
405 bytes: Vec<u8>,
406 width: usize,
407 height: usize,
408 timing: VideoFrameTiming,
409 color: VideoColorInfo,
410 ) -> Result<Self> {
411 Self::from_host_planes(
412 VideoHostPlanes::U8(Arc::new(bytes)),
413 width,
414 height,
415 timing,
416 color,
417 )
418 }
419
420 pub fn new_from_yuv420p10(
432 bytes: Vec<u16>,
433 width: usize,
434 height: usize,
435 timing: VideoFrameTiming,
436 color: VideoColorInfo,
437 ) -> Result<Self> {
438 Self::from_host_planes(
439 VideoHostPlanes::U16(Arc::new(bytes)),
440 width,
441 height,
442 timing,
443 color,
444 )
445 }
446
447 pub(super) fn from_host_planes(
448 planes: VideoHostPlanes,
449 width: usize,
450 height: usize,
451 timing: VideoFrameTiming,
452 color: VideoColorInfo,
453 ) -> Result<Self> {
454 if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
455 return Err(Error::invalid_argument(
456 "planar YUV420 video frames require non-zero even dimensions",
457 ));
458 }
459 let expected = width
460 .checked_mul(height)
461 .and_then(|y| y.checked_add(y / 2))
462 .ok_or_else(|| Error::out_of_range("planar YUV420 frame size overflows usize"))?;
463 let actual = match &planes {
464 VideoHostPlanes::U8(bytes) => bytes.len(),
465 VideoHostPlanes::U16(words) => words.len(),
466 };
467 if expected != actual {
468 return Err(Error::invalid_argument(format!(
469 "planar YUV420 frame requires {expected} samples, but received {actual}"
470 )));
471 }
472 let backing = match planes {
473 VideoHostPlanes::U8(bytes) => VideoFrameBacking::PlanarYuv420 {
474 bytes,
475 width,
476 height,
477 },
478 VideoHostPlanes::U16(bytes) => VideoFrameBacking::PlanarYuv420P10 {
479 bytes,
480 width,
481 height,
482 },
483 };
484 Ok(Self {
485 backing,
486 timing,
487 color,
488 })
489 }
490
491 pub fn width(&self) -> usize {
493 self.backing.width()
494 }
495
496 pub fn height(&self) -> usize {
498 self.backing.height()
499 }
500
501 pub const fn timing(&self) -> VideoFrameTiming {
503 self.timing
504 }
505
506 pub const fn color_info(&self) -> VideoColorInfo {
508 self.color
509 }
510
511 pub const fn as_image(&self) -> Option<&Image> {
516 match &self.backing {
517 VideoFrameBacking::PackedImage(image) => Some(image),
518 VideoFrameBacking::Texture { .. }
519 | VideoFrameBacking::Native(_)
520 | VideoFrameBacking::CanvasYuv { .. }
521 | VideoFrameBacking::DevicePlanar(_)
522 | VideoFrameBacking::PlanarYuv420 { .. }
523 | VideoFrameBacking::PlanarYuv420P10 { .. } => None,
524 }
525 }
526
527 pub const fn as_texture(&self) -> Option<&Texture> {
533 match &self.backing {
534 VideoFrameBacking::Texture { texture, .. } => Some(texture),
535 VideoFrameBacking::PackedImage(_)
536 | VideoFrameBacking::Native(_)
537 | VideoFrameBacking::CanvasYuv { .. }
538 | VideoFrameBacking::DevicePlanar(_)
539 | VideoFrameBacking::PlanarYuv420 { .. }
540 | VideoFrameBacking::PlanarYuv420P10 { .. } => None,
541 }
542 }
543
544 pub fn as_yuv420p(&self) -> Option<&[u8]> {
546 match &self.backing {
547 VideoFrameBacking::PlanarYuv420 { bytes, .. } => Some(bytes.as_slice()),
548 VideoFrameBacking::PackedImage(_)
549 | VideoFrameBacking::CanvasYuv { .. }
550 | VideoFrameBacking::Texture { .. }
551 | VideoFrameBacking::DevicePlanar(_)
552 | VideoFrameBacking::PlanarYuv420P10 { .. }
553 | VideoFrameBacking::Native(_) => None,
554 }
555 }
556
557 pub fn as_yuv420p10(&self) -> Option<&[u16]> {
562 match &self.backing {
563 VideoFrameBacking::PlanarYuv420P10 { bytes, .. } => Some(bytes.as_slice()),
564 VideoFrameBacking::PackedImage(_)
565 | VideoFrameBacking::CanvasYuv { .. }
566 | VideoFrameBacking::Texture { .. }
567 | VideoFrameBacking::DevicePlanar(_)
568 | VideoFrameBacking::PlanarYuv420 { .. }
569 | VideoFrameBacking::Native(_) => None,
570 }
571 }
572
573 pub const fn native_format(&self) -> Option<VideoPixelFormat> {
575 match &self.backing {
576 VideoFrameBacking::Native(frame) => Some(frame.format()),
577 _ => None,
578 }
579 }
580
581 pub fn pixel_format(&self) -> Option<VideoPixelFormat> {
583 match &self.backing {
584 VideoFrameBacking::DevicePlanar(planar) => Some(planar.format),
585 VideoFrameBacking::CanvasYuv { layout, .. } => Some(layout.format),
586 VideoFrameBacking::Native(frame) => Some(frame.format()),
587 VideoFrameBacking::PlanarYuv420 { .. } => Some(VideoPixelFormat::Yuv420Planar8),
588 VideoFrameBacking::PlanarYuv420P10 { .. } => Some(VideoPixelFormat::Yuv420Planar10),
589 VideoFrameBacking::PackedImage(_) | VideoFrameBacking::Texture { .. } => None,
590 }
591 }
592
593 pub fn planes(&self) -> Option<&[Matrix]> {
601 match &self.backing {
602 VideoFrameBacking::DevicePlanar(planar) => Some(planar.planes.as_slice()),
603 _ => None,
604 }
605 }
606
607 pub(crate) fn device_planar(&self) -> Option<&DevicePlanar> {
609 match &self.backing {
610 VideoFrameBacking::DevicePlanar(planar) => Some(planar),
611 _ => None,
612 }
613 }
614
615 pub const fn ready_event(&self) -> Option<&Event> {
621 match &self.backing {
622 VideoFrameBacking::Native(frame) => Some(frame.ready()),
623 VideoFrameBacking::Texture { ready, .. } => ready.as_ref(),
624 _ => None,
625 }
626 }
627
628 pub fn mark_consumed(&self, event: &Event) -> Result<()> {
639 match &self.backing {
640 VideoFrameBacking::Native(frame) => frame.mark_consumed(event),
641 VideoFrameBacking::Texture { texture, .. } => texture.mark_consumed(event),
642 _ => Err(Error::failed_precondition(
643 "consumer completion applies only to native decoded or render-target video frames",
644 )),
645 }
646 }
647
648 pub fn into_image(self) -> Option<Image> {
650 match self.backing {
651 VideoFrameBacking::PackedImage(image) => Some(image),
652 VideoFrameBacking::Texture { .. }
653 | VideoFrameBacking::Native(_)
654 | VideoFrameBacking::CanvasYuv { .. }
655 | VideoFrameBacking::DevicePlanar(_)
656 | VideoFrameBacking::PlanarYuv420 { .. }
657 | VideoFrameBacking::PlanarYuv420P10 { .. } => None,
658 }
659 }
660
661 pub fn into_texture(self) -> Option<Texture> {
663 match self.backing {
664 VideoFrameBacking::Texture { texture, .. } => Some(texture),
665 VideoFrameBacking::PackedImage(_)
666 | VideoFrameBacking::Native(_)
667 | VideoFrameBacking::CanvasYuv { .. }
668 | VideoFrameBacking::DevicePlanar(_)
669 | VideoFrameBacking::PlanarYuv420 { .. }
670 | VideoFrameBacking::PlanarYuv420P10 { .. } => None,
671 }
672 }
673}
674
675#[derive(Clone, Debug)]
681pub(crate) enum VideoHostPlanes {
682 U8(Arc<Vec<u8>>),
683 U16(Arc<Vec<u16>>),
684}
685
686#[derive(Clone)]
687enum VideoFrameBacking {
688 PackedImage(Image),
689 Texture {
690 texture: Texture,
691 ready: Option<Event>,
692 },
693 Native(NativeDecodedFrame),
694 CanvasYuv {
695 storage: crate::runtime::Storage,
696 layout: CanvasYuvLayout,
697 },
698 DevicePlanar(DevicePlanar),
699 PlanarYuv420 {
700 bytes: Arc<Vec<u8>>,
701 width: usize,
702 height: usize,
703 },
704 PlanarYuv420P10 {
705 bytes: Arc<Vec<u16>>,
706 width: usize,
707 height: usize,
708 },
709}
710
711impl VideoFrameBacking {
712 fn width(&self) -> usize {
713 match self {
714 Self::PackedImage(image) => image.width(),
715 Self::Texture { texture, .. } => texture.width(),
716 Self::Native(frame) => frame.extent().width as usize,
717 Self::CanvasYuv { layout, .. } => layout.extent.width as usize,
718 Self::DevicePlanar(planar) => planar.width,
719 Self::PlanarYuv420 { width, .. } | Self::PlanarYuv420P10 { width, .. } => *width,
720 }
721 }
722
723 fn height(&self) -> usize {
724 match self {
725 Self::PackedImage(image) => image.height(),
726 Self::Texture { texture, .. } => texture.height(),
727 Self::Native(frame) => frame.extent().height as usize,
728 Self::CanvasYuv { layout, .. } => layout.extent.height as usize,
729 Self::DevicePlanar(planar) => planar.height,
730 Self::PlanarYuv420 { height, .. } | Self::PlanarYuv420P10 { height, .. } => *height,
731 }
732 }
733}