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 { data: vec![0; w * h], w, h }
14 }
15}
16
17#[derive(Clone, Default)]
19pub(crate) struct FrameBuf {
20 pub(crate) y: Plane,
21 pub(crate) u: Plane,
22 pub(crate) v: Plane,
23}
24
25impl FrameBuf {
26 pub(crate) fn new(mb_cols: usize, mb_rows: usize) -> Self {
27 FrameBuf {
28 y: Plane::new(mb_cols * 16, mb_rows * 16),
29 u: Plane::new(mb_cols * 8, mb_rows * 8),
30 v: Plane::new(mb_cols * 8, mb_rows * 8),
31 }
32 }
33}
34
35#[derive(Clone, Copy, Debug)]
40pub struct Picture<'a> {
41 pub width: u32,
43 pub height: u32,
45 pub y: &'a [u8],
47 pub u: &'a [u8],
49 pub v: &'a [u8],
51 pub y_stride: usize,
53 pub uv_stride: usize,
55}
56
57impl<'a> Picture<'a> {
58 pub fn chroma_width(&self) -> u32 {
60 self.width.div_ceil(2)
61 }
62
63 pub fn chroma_height(&self) -> u32 {
65 self.height.div_ceil(2)
66 }
67
68 pub fn from_i420(data: &'a [u8], width: u32, height: u32) -> Option<Picture<'a>> {
71 let (w, h) = (width as usize, height as usize);
72 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
73 let y_len = w * h;
74 let c_len = cw * ch;
75 if width == 0 || height == 0 || data.len() < y_len + 2 * c_len {
76 return None;
77 }
78 Some(Picture {
79 width,
80 height,
81 y: &data[..y_len],
82 u: &data[y_len..y_len + c_len],
83 v: &data[y_len + c_len..y_len + 2 * c_len],
84 y_stride: w,
85 uv_stride: cw,
86 })
87 }
88
89 pub fn write_i420(&self, out: &mut Vec<u8>) {
91 let (w, h) = (self.width as usize, self.height as usize);
92 let (cw, ch) = (self.chroma_width() as usize, self.chroma_height() as usize);
93 out.reserve(w * h + 2 * cw * ch);
94 for r in 0..h {
95 out.extend_from_slice(&self.y[r * self.y_stride..r * self.y_stride + w]);
96 }
97 for plane in [self.u, self.v] {
98 for r in 0..ch {
99 out.extend_from_slice(&plane[r * self.uv_stride..r * self.uv_stride + cw]);
100 }
101 }
102 }
103
104 pub fn to_i420(&self) -> Vec<u8> {
106 let mut v = Vec::new();
107 self.write_i420(&mut v);
108 v
109 }
110}