1#[derive(Clone, Default)]
5pub(crate) struct Plane {
6 pub(crate) data: Vec<u8>,
7 pub(crate) w: usize,
8 pub(crate) h: usize,
9}
10
11impl Plane {
12 fn new(w: usize, h: usize) -> Self {
13 Plane {
14 data: vec![0; w * h],
15 w,
16 h,
17 }
18 }
19}
20
21#[derive(Clone, Default)]
23pub(crate) struct FrameBuf {
24 pub(crate) y: Plane,
25 pub(crate) u: Plane,
26 pub(crate) v: Plane,
27}
28
29impl FrameBuf {
30 pub(crate) fn new(mb_cols: usize, mb_rows: usize) -> Self {
31 FrameBuf {
32 y: Plane::new(mb_cols * 16, mb_rows * 16),
33 u: Plane::new(mb_cols * 8, mb_rows * 8),
34 v: Plane::new(mb_cols * 8, mb_rows * 8),
35 }
36 }
37}
38
39#[derive(Clone, Copy, Debug)]
44pub struct Picture<'a> {
45 pub width: u32,
47 pub height: u32,
49 pub y: &'a [u8],
51 pub u: &'a [u8],
53 pub v: &'a [u8],
55 pub y_stride: usize,
57 pub uv_stride: usize,
59}
60
61impl<'a> Picture<'a> {
62 pub fn chroma_width(&self) -> u32 {
64 self.width.div_ceil(2)
65 }
66
67 pub fn chroma_height(&self) -> u32 {
69 self.height.div_ceil(2)
70 }
71
72 pub fn from_i420(data: &'a [u8], width: u32, height: u32) -> Option<Picture<'a>> {
75 let (w, h) = (width as usize, height as usize);
76 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
77 let y_len = w * h;
78 let c_len = cw * ch;
79 if width == 0 || height == 0 || data.len() < y_len + 2 * c_len {
80 return None;
81 }
82 Some(Picture {
83 width,
84 height,
85 y: &data[..y_len],
86 u: &data[y_len..y_len + c_len],
87 v: &data[y_len + c_len..y_len + 2 * c_len],
88 y_stride: w,
89 uv_stride: cw,
90 })
91 }
92
93 pub fn write_i420(&self, out: &mut Vec<u8>) {
95 let (w, h) = (self.width as usize, self.height as usize);
96 let (cw, ch) = (self.chroma_width() as usize, self.chroma_height() as usize);
97 out.reserve(w * h + 2 * cw * ch);
98 for r in 0..h {
99 out.extend_from_slice(&self.y[r * self.y_stride..r * self.y_stride + w]);
100 }
101 for plane in [self.u, self.v] {
102 for r in 0..ch {
103 out.extend_from_slice(&plane[r * self.uv_stride..r * self.uv_stride + cw]);
104 }
105 }
106 }
107
108 pub fn to_i420(&self) -> Vec<u8> {
110 let mut v = Vec::new();
111 self.write_i420(&mut v);
112 v
113 }
114}