use std::{rc::Rc, sync::Arc, time::Duration};
use crate::{Engine, Error, Event, Image, Matrix, Result, Texture, runtime::NativeDecodedFrame};
use super::{
VideoPixelFormat,
plane::{DevicePlanar, plane_count, plane_extents},
};
pub use crate::video::types::VideoColorInfo;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoColorMatrix {
Unspecified,
Bt601,
Bt709,
Bt2020,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoColorRange {
Unspecified,
Limited,
Full,
}
impl VideoColorInfo {
pub const fn new(matrix: VideoColorMatrix, range: VideoColorRange) -> Self {
Self { matrix, range }
}
pub const fn unspecified() -> Self {
Self::new(VideoColorMatrix::Unspecified, VideoColorRange::Unspecified)
}
pub const fn matrix(self) -> VideoColorMatrix {
self.matrix
}
pub const fn range(self) -> VideoColorRange {
self.range
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VideoFrameTiming {
presentation_timestamp: Duration,
duration: Option<Duration>,
}
impl VideoFrameTiming {
pub fn new(presentation_timestamp: Duration, duration: Option<Duration>) -> Result<Self> {
if duration == Some(Duration::ZERO) {
return Err(Error::invalid_argument(
"video frame duration must be non-zero when specified",
));
}
Ok(Self {
presentation_timestamp,
duration,
})
}
pub fn new_from_microseconds(
presentation_timestamp_microseconds: u64,
duration_microseconds: u64,
) -> Self {
Self {
presentation_timestamp: Duration::from_micros(presentation_timestamp_microseconds),
duration: (duration_microseconds != 0)
.then_some(Duration::from_micros(duration_microseconds)),
}
}
pub const fn presentation_timestamp(self) -> Duration {
self.presentation_timestamp
}
pub const fn duration(self) -> Option<Duration> {
self.duration
}
}
#[derive(Clone)]
pub struct VideoFrame {
backing: VideoFrameBacking,
timing: VideoFrameTiming,
color: VideoColorInfo,
}
#[derive(Clone, Copy)]
pub(crate) struct CanvasYuvLayout {
pub extent: super::VideoExtent,
pub format: VideoPixelFormat,
pub sample_bits: u32,
pub cb_offset: u32,
pub cr_offset: u32,
pub interleaved: bool,
}
impl VideoFrame {
pub(crate) const fn native_backing(&self) -> Option<&NativeDecodedFrame> {
match &self.backing {
VideoFrameBacking::Native(frame) => Some(frame),
_ => None,
}
}
pub(crate) fn from_native(
frame: NativeDecodedFrame,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Self {
Self {
backing: VideoFrameBacking::Native(frame),
timing,
color,
}
}
pub(crate) fn from_texture(
texture: Texture,
timing: VideoFrameTiming,
color: VideoColorInfo,
ready: Option<Event>,
) -> Self {
Self {
backing: VideoFrameBacking::Texture { texture, ready },
timing,
color,
}
}
pub(crate) fn with_canvas_planes(
&self,
storage: crate::runtime::Storage,
layout: CanvasYuvLayout,
) -> Self {
Self {
backing: VideoFrameBacking::CanvasYuv { storage, layout },
timing: self.timing,
color: self.color,
}
}
pub(crate) fn canvas_planes(&self) -> Option<(&crate::runtime::Storage, CanvasYuvLayout)> {
match &self.backing {
VideoFrameBacking::CanvasYuv { storage, layout } => Some((storage, *layout)),
_ => None,
}
}
pub fn new_from_image(
image: Image,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
if image.batch_size() != 1 {
return Err(Error::invalid_argument(format!(
"video frame requires one image, but the batch extent is {}",
image.batch_size()
)));
}
if image.width() == 0 || image.height() == 0 {
return Err(Error::invalid_argument(
"video frame width and height must be non-zero",
));
}
Ok(Self {
backing: VideoFrameBacking::PackedImage(image),
timing,
color,
})
}
pub fn upload_planes(
format: VideoPixelFormat,
planes: Vec<Vec<u8>>,
width: usize,
height: usize,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
Self::upload_planes_on(
&Engine::current()?,
format,
planes,
width,
height,
timing,
color,
)
}
pub fn upload_planes_on(
engine: &Engine,
format: VideoPixelFormat,
planes: Vec<Vec<u8>>,
width: usize,
height: usize,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
if planes.len() != plane_count(format) {
return Err(Error::invalid_argument(format!(
"{format:?} requires {} planes, but {} were provided",
plane_count(format),
planes.len()
)));
}
let extents = plane_extents(format, width, height)?;
let mut matrices = Vec::with_capacity(planes.len());
for (bytes, extent) in planes.iter().zip(extents.iter()) {
let expected = extent
.width
.checked_mul(extent.height)
.ok_or_else(|| Error::out_of_range("plane byte extent overflows usize"))?;
if bytes.len() != expected {
return Err(Error::invalid_argument(format!(
"plane requires {expected} bytes, but {} were provided",
bytes.len()
)));
}
matrices.push(Matrix::new_from_slice_on(
engine,
[extent.height, extent.width],
bytes,
)?);
}
Ok(Self {
backing: VideoFrameBacking::DevicePlanar(DevicePlanar {
planes: Rc::new(matrices),
format,
width,
height,
}),
timing,
color,
})
}
pub fn upload(&self) -> Result<VideoFrame> {
self.upload_on(&Engine::current()?)
}
pub fn upload_on(&self, engine: &Engine) -> Result<VideoFrame> {
match &self.backing {
VideoFrameBacking::DevicePlanar(_) => Ok(self.clone()),
VideoFrameBacking::PlanarYuv420 {
bytes,
width,
height,
} => {
let width = *width;
let height = *height;
let luma = width * height;
let chroma = luma / 4;
let planes = vec![
bytes[..luma].to_vec(),
bytes[luma..luma + chroma].to_vec(),
bytes[luma + chroma..].to_vec(),
];
Self::upload_planes_on(
engine,
VideoPixelFormat::Yuv420Planar8,
planes,
width,
height,
self.timing,
self.color,
)
}
VideoFrameBacking::PackedImage(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::Texture { .. }
| VideoFrameBacking::PlanarYuv420P10 { .. }
| VideoFrameBacking::Native(_) => Err(Error::failed_precondition(
"upload applies to 8-bit host-planar or device-planar video frames",
)),
}
}
pub(crate) fn from_device_planar(
planar: DevicePlanar,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Self {
Self {
backing: VideoFrameBacking::DevicePlanar(planar),
timing,
color,
}
}
pub fn new_from_yuv420p(
bytes: Vec<u8>,
width: usize,
height: usize,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
Self::from_host_planes(
VideoHostPlanes::U8(Arc::new(bytes)),
width,
height,
timing,
color,
)
}
pub fn new_from_yuv420p10(
bytes: Vec<u16>,
width: usize,
height: usize,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
Self::from_host_planes(
VideoHostPlanes::U16(Arc::new(bytes)),
width,
height,
timing,
color,
)
}
pub(super) fn from_host_planes(
planes: VideoHostPlanes,
width: usize,
height: usize,
timing: VideoFrameTiming,
color: VideoColorInfo,
) -> Result<Self> {
if width == 0 || height == 0 || !width.is_multiple_of(2) || !height.is_multiple_of(2) {
return Err(Error::invalid_argument(
"planar YUV420 video frames require non-zero even dimensions",
));
}
let expected = width
.checked_mul(height)
.and_then(|y| y.checked_add(y / 2))
.ok_or_else(|| Error::out_of_range("planar YUV420 frame size overflows usize"))?;
let actual = match &planes {
VideoHostPlanes::U8(bytes) => bytes.len(),
VideoHostPlanes::U16(words) => words.len(),
};
if expected != actual {
return Err(Error::invalid_argument(format!(
"planar YUV420 frame requires {expected} samples, but received {actual}"
)));
}
let backing = match planes {
VideoHostPlanes::U8(bytes) => VideoFrameBacking::PlanarYuv420 {
bytes,
width,
height,
},
VideoHostPlanes::U16(bytes) => VideoFrameBacking::PlanarYuv420P10 {
bytes,
width,
height,
},
};
Ok(Self {
backing,
timing,
color,
})
}
pub fn width(&self) -> usize {
self.backing.width()
}
pub fn height(&self) -> usize {
self.backing.height()
}
pub const fn timing(&self) -> VideoFrameTiming {
self.timing
}
pub const fn color_info(&self) -> VideoColorInfo {
self.color
}
pub const fn as_image(&self) -> Option<&Image> {
match &self.backing {
VideoFrameBacking::PackedImage(image) => Some(image),
VideoFrameBacking::Texture { .. }
| VideoFrameBacking::Native(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420 { .. }
| VideoFrameBacking::PlanarYuv420P10 { .. } => None,
}
}
pub const fn as_texture(&self) -> Option<&Texture> {
match &self.backing {
VideoFrameBacking::Texture { texture, .. } => Some(texture),
VideoFrameBacking::PackedImage(_)
| VideoFrameBacking::Native(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420 { .. }
| VideoFrameBacking::PlanarYuv420P10 { .. } => None,
}
}
pub fn as_yuv420p(&self) -> Option<&[u8]> {
match &self.backing {
VideoFrameBacking::PlanarYuv420 { bytes, .. } => Some(bytes.as_slice()),
VideoFrameBacking::PackedImage(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::Texture { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420P10 { .. }
| VideoFrameBacking::Native(_) => None,
}
}
pub fn as_yuv420p10(&self) -> Option<&[u16]> {
match &self.backing {
VideoFrameBacking::PlanarYuv420P10 { bytes, .. } => Some(bytes.as_slice()),
VideoFrameBacking::PackedImage(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::Texture { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420 { .. }
| VideoFrameBacking::Native(_) => None,
}
}
pub const fn native_format(&self) -> Option<VideoPixelFormat> {
match &self.backing {
VideoFrameBacking::Native(frame) => Some(frame.format()),
_ => None,
}
}
pub fn pixel_format(&self) -> Option<VideoPixelFormat> {
match &self.backing {
VideoFrameBacking::DevicePlanar(planar) => Some(planar.format),
VideoFrameBacking::CanvasYuv { layout, .. } => Some(layout.format),
VideoFrameBacking::Native(frame) => Some(frame.format()),
VideoFrameBacking::PlanarYuv420 { .. } => Some(VideoPixelFormat::Yuv420Planar8),
VideoFrameBacking::PlanarYuv420P10 { .. } => Some(VideoPixelFormat::Yuv420Planar10),
VideoFrameBacking::PackedImage(_) | VideoFrameBacking::Texture { .. } => None,
}
}
pub fn planes(&self) -> Option<&[Matrix]> {
match &self.backing {
VideoFrameBacking::DevicePlanar(planar) => Some(planar.planes.as_slice()),
_ => None,
}
}
pub(crate) fn device_planar(&self) -> Option<&DevicePlanar> {
match &self.backing {
VideoFrameBacking::DevicePlanar(planar) => Some(planar),
_ => None,
}
}
pub const fn ready_event(&self) -> Option<&Event> {
match &self.backing {
VideoFrameBacking::Native(frame) => Some(frame.ready()),
VideoFrameBacking::Texture { ready, .. } => ready.as_ref(),
_ => None,
}
}
pub fn mark_consumed(&self, event: &Event) -> Result<()> {
match &self.backing {
VideoFrameBacking::Native(frame) => frame.mark_consumed(event),
VideoFrameBacking::Texture { texture, .. } => texture.mark_consumed(event),
_ => Err(Error::failed_precondition(
"consumer completion applies only to native decoded or render-target video frames",
)),
}
}
pub fn into_image(self) -> Option<Image> {
match self.backing {
VideoFrameBacking::PackedImage(image) => Some(image),
VideoFrameBacking::Texture { .. }
| VideoFrameBacking::Native(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420 { .. }
| VideoFrameBacking::PlanarYuv420P10 { .. } => None,
}
}
pub fn into_texture(self) -> Option<Texture> {
match self.backing {
VideoFrameBacking::Texture { texture, .. } => Some(texture),
VideoFrameBacking::PackedImage(_)
| VideoFrameBacking::Native(_)
| VideoFrameBacking::CanvasYuv { .. }
| VideoFrameBacking::DevicePlanar(_)
| VideoFrameBacking::PlanarYuv420 { .. }
| VideoFrameBacking::PlanarYuv420P10 { .. } => None,
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum VideoHostPlanes {
U8(Arc<Vec<u8>>),
U16(Arc<Vec<u16>>),
}
#[derive(Clone)]
enum VideoFrameBacking {
PackedImage(Image),
Texture {
texture: Texture,
ready: Option<Event>,
},
Native(NativeDecodedFrame),
CanvasYuv {
storage: crate::runtime::Storage,
layout: CanvasYuvLayout,
},
DevicePlanar(DevicePlanar),
PlanarYuv420 {
bytes: Arc<Vec<u8>>,
width: usize,
height: usize,
},
PlanarYuv420P10 {
bytes: Arc<Vec<u16>>,
width: usize,
height: usize,
},
}
impl VideoFrameBacking {
fn width(&self) -> usize {
match self {
Self::PackedImage(image) => image.width(),
Self::Texture { texture, .. } => texture.width(),
Self::Native(frame) => frame.extent().width as usize,
Self::CanvasYuv { layout, .. } => layout.extent.width as usize,
Self::DevicePlanar(planar) => planar.width,
Self::PlanarYuv420 { width, .. } | Self::PlanarYuv420P10 { width, .. } => *width,
}
}
fn height(&self) -> usize {
match self {
Self::PackedImage(image) => image.height(),
Self::Texture { texture, .. } => texture.height(),
Self::Native(frame) => frame.extent().height as usize,
Self::CanvasYuv { layout, .. } => layout.extent.height as usize,
Self::DevicePlanar(planar) => planar.height,
Self::PlanarYuv420 { height, .. } | Self::PlanarYuv420P10 { height, .. } => *height,
}
}
}