forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

picture.rs455 lines, 14.7 KiBHistoryRawDownload
1//! Pixel buffers and conversions that need no VA-API: planar I420 and its
2//! 10-bit sibling, the colour metadata, and the NV12 conversions.
3
4use ec_core::color::{ColorDescription, ContentLight, Matrix};
5
6use crate::error::{Error, Result};
7
8/// A stream's colour metadata, resolved from its own headers: VUI tags for the
9/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
10/// messages for the peak the mastering grade and the content itself declared.
11/// No container tier here: ec-hw only ever sees the elementary stream, so a
12/// caller that also holds the container's tags resolves those over this.
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct Colour {
15 /// Matrix/transfer/range, resolved from the bitstream's own VUI.
16 pub description: ColorDescription,
17 /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
18 /// the stream carried them (HEVC prefix SEI only).
19 pub light: ContentLight,
20}
21
22/// 8-bit planar 4:2:0, the currency edith's software path speaks.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct I420 {
25 /// Luma plane, `width * height`.
26 pub y: Vec<u8>,
27 /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`.
28 pub u: Vec<u8>,
29 /// Cr plane, same size as `u`.
30 pub v: Vec<u8>,
31 /// Width in luma samples.
32 pub width: u32,
33 /// Height in luma samples.
34 pub height: u32,
35}
36
37/// A packed 32-bit RGB picture, alpha 255, `stride` bytes per row.
38#[derive(Debug, Clone, Default, PartialEq, Eq)]
39pub struct RgbPicture {
40 /// Pixels, `stride * height` bytes.
41 pub data: Vec<u8>,
42 /// Width in pixels.
43 pub width: u32,
44 /// Height in pixels.
45 pub height: u32,
46 /// Row stride in bytes: `width * 4`.
47 pub stride: u32,
48}
49
50impl RgbPicture {
51 pub(crate) fn new(data: Vec<u8>, width: u32, height: u32) -> Self {
52 RgbPicture {
53 data,
54 width,
55 height,
56 stride: width * 4,
57 }
58 }
59}
60
61/// A decoded picture as DMA-BUF file descriptors: NV12 or P010, Y then UV, in an exportable layout.
62#[cfg(target_os = "linux")]
63#[derive(Debug)]
64pub struct DmaBufPicture {
65 /// The DMA-BUF objects. Each is closed when the picture drops.
66 pub fds: Vec<std::os::fd::OwnedFd>,
67 /// DRM fourcc: NV12 or P010.
68 pub fourcc: u32,
69 /// DRM format modifier, 0 for linear.
70 pub modifier: u64,
71 /// Width in luma samples.
72 pub width: u32,
73 /// Height in luma samples.
74 pub height: u32,
75 /// Y plane then UV plane.
76 pub planes: [ec_vk::DmaBufPlane; 2],
77}
78
79#[cfg(target_os = "linux")]
80impl From<ec_vk::DmaBufExport> for DmaBufPicture {
81 fn from(export: ec_vk::DmaBufExport) -> DmaBufPicture {
82 let fourcc = if export.p010 {
83 u32::from_le_bytes(*b"P010")
84 } else {
85 u32::from_le_bytes(*b"NV12")
86 };
87 DmaBufPicture {
88 fds: vec![export.fd],
89 fourcc,
90 modifier: export.modifier,
91 width: export.width,
92 height: export.height,
93 planes: export.planes,
94 }
95 }
96}
97
98#[cfg(target_os = "linux")]
99impl DmaBufPicture {
100 /// A second handle on the same memory, for a picture shown again from a reference.
101 pub fn try_clone(&self) -> std::io::Result<DmaBufPicture> {
102 Ok(DmaBufPicture {
103 fds: self
104 .fds
105 .iter()
106 .map(|fd| fd.try_clone())
107 .collect::<std::io::Result<_>>()?,
108 fourcc: self.fourcc,
109 modifier: self.modifier,
110 width: self.width,
111 height: self.height,
112 planes: self.planes,
113 })
114 }
115}
116
117/// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here.
118pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb {
119 match matrix {
120 Matrix::Bt601 => ec_dsp::rgb::BT601_LIMITED,
121 Matrix::Bt709 | Matrix::Bt2020Ncl => ec_dsp::rgb::BT709_LIMITED,
122 }
123}
124
125/// Packed RGB of an 8-bit I420 picture, scaled into `bound`, converted on the CPU with the coefficients of `matrix`.
126pub(crate) fn i420_to_rgb(
127 frame: &I420,
128 bound: (Option<u32>, Option<u32>),
129 bgra: bool,
130 matrix: Matrix,
131) -> RgbPicture {
132 let (w, h) = rgb_size(frame.width, frame.height, bound);
133 let data = ec_dsp::rgb::i420_to_packed(
134 &frame.y,
135 &frame.u,
136 &frame.v,
137 (frame.width as usize, frame.height as usize),
138 (w as usize, h as usize),
139 bgra,
140 &yuv_to_rgb(matrix),
141 );
142 RgbPicture::new(data, w, h)
143}
144
145/// Output size of an RGB picture of `width` x `height` fit inside `(max_width, max_height)` keeping the aspect; a scaled height is even.
146pub(crate) fn rgb_size(width: u32, height: u32, bound: (Option<u32>, Option<u32>)) -> (u32, u32) {
147 let (w, h) = (u64::from(width), u64::from(height));
148 let limit = |max: Option<u32>, full: u64| max.filter(|&m| m > 0).map_or(full, u64::from).min(full);
149 let (mw, mh) = (limit(bound.0, w), limit(bound.1, h));
150 if mw == w && mh == h {
151 return (width, height);
152 }
153 if mw * h <= mh * w {
154 let even = 2 * ((h * mw + w) / (2 * w));
155 (mw as u32, even.clamp(2, h) as u32)
156 } else {
157 let even = (mh & !1).max(2);
158 let scaled = (w * even + h / 2) / h;
159 (scaled.clamp(1, w) as u32, even as u32)
160 }
161}
162
163/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct I420_16 {
166 /// Luma plane.
167 pub y: Vec<u16>,
168 /// Cb plane.
169 pub u: Vec<u16>,
170 /// Cr plane.
171 pub v: Vec<u16>,
172 /// Width in luma samples.
173 pub width: u32,
174 /// Height in luma samples.
175 pub height: u32,
176 /// Luma bit depth: always 10 for this format.
177 pub bit_depth: u8,
178}
179
180/// Deinterleave an NV12 chroma plane into I420 U and V planes.
181///
182/// The same conversion the software path in edith expects on the way out of a
183/// hardware frame; kept as a free function because an encoder's input path
184/// needs it in reverse.
185pub fn nv12_to_i420(
186 y_plane: &[u8],
187 y_pitch: usize,
188 uv_plane: &[u8],
189 uv_pitch: usize,
190 width: usize,
191 height: usize,
192) -> I420 {
193 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
194 let mut out = I420 {
195 y: vec![0; width * height],
196 u: vec![0; cw * ch],
197 v: vec![0; cw * ch],
198 width: width as u32,
199 height: height as u32,
200 };
201 for row in 0..height {
202 let src = row * y_pitch;
203 if src + width > y_plane.len() {
204 break;
205 }
206 out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]);
207 }
208 for row in 0..ch {
209 let src = row * uv_pitch;
210 if src + cw * 2 > uv_plane.len() {
211 break;
212 }
213 for col in 0..cw {
214 out.u[row * cw + col] = uv_plane[src + col * 2];
215 out.v[row * cw + col] = uv_plane[src + col * 2 + 1];
216 }
217 }
218 out
219}
220
221pub(crate) fn semi_planar_to_i420(
222 bit_depth: u8,
223 y: &[u8],
224 uv: &[u8],
225 pitch: usize,
226 origin: (usize, usize),
227 size: (u32, u32),
228) -> Result<I420> {
229 let bytes = if bit_depth == 8 { 1 } else { 2 };
230 let pitch = pitch * bytes;
231 let (x, top) = (origin.0 * bytes, origin.1);
232 let y = y.get(top * pitch + x..).unwrap_or(&[]);
233 let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]);
234 let (width, height) = size;
235 let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2));
236 let mut out = I420 {
237 y: vec![0; width as usize * height as usize],
238 u: vec![0; cw * ch],
239 v: vec![0; cw * ch],
240 width,
241 height,
242 };
243 fill_i420(&mut out, bit_depth, y, pitch, uv, pitch)?;
244 Ok(out)
245}
246
247/// Copy NV12/P010 planes into `out`, after validating every plane against it.
248pub(crate) fn fill_i420_16(
249 out: &mut I420_16,
250 bit_depth: u8,
251 y_plane: &[u8],
252 y_pitch: usize,
253 uv_plane: &[u8],
254 uv_pitch: usize,
255) -> Result<()> {
256 let (w, h) = (out.width as usize, out.height as usize);
257 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
258 let bytes = if bit_depth == 8 { 1 } else { 2 };
259 check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
260 check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
261 let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
262 match bit_depth {
263 8 => {
264 for row in 0..h {
265 let src = row * y_pitch;
266 row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
267 for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w]) {
268 *dst = u16::from(sample) << 2;
269 }
270 }
271 for row in 0..ch {
272 let src = row * uv_pitch;
273 let line = &mut row_buf[..cw * 2];
274 line.copy_from_slice(&uv_plane[src..src + cw * 2]);
275 for col in 0..cw {
276 out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
277 out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
278 }
279 }
280 }
281 _ => {
282 // P010 is 16-bit little endian with the sample in the top ten
283 // bits; the low six are zero padding.
284 for row in 0..h {
285 let src = row * y_pitch;
286 let line = &mut row_buf[..w * 2];
287 line.copy_from_slice(&y_plane[src..src + w * 2]);
288 for col in 0..w {
289 out.y[row * w + col] =
290 u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
291 }
292 }
293 for row in 0..ch {
294 let src = row * uv_pitch;
295 let line = &mut row_buf[..cw * 4];
296 line.copy_from_slice(&uv_plane[src..src + cw * 4]);
297 for col in 0..cw {
298 out.u[row * cw + col] =
299 u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
300 out.v[row * cw + col] =
301 u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6;
302 }
303 }
304 }
305 }
306 Ok(())
307}
308
309pub(crate) fn semi_planar_to_i420_16(
310 bit_depth: u8,
311 y: &[u8],
312 uv: &[u8],
313 pitch: usize,
314 origin: (usize, usize),
315 size: (u32, u32),
316) -> Result<I420_16> {
317 let bytes = if bit_depth == 8 { 1 } else { 2 };
318 let pitch = pitch * bytes;
319 let (x, top) = (origin.0 * bytes, origin.1);
320 let y = y.get(top * pitch + x..).unwrap_or(&[]);
321 let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]);
322 let (width, height) = size;
323 let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2));
324 let mut out = I420_16 {
325 y: vec![0; width as usize * height as usize],
326 u: vec![0; cw * ch],
327 v: vec![0; cw * ch],
328 width,
329 height,
330 bit_depth: 10,
331 };
332 fill_i420_16(&mut out, bit_depth, y, pitch, uv, pitch)?;
333 Ok(out)
334}
335
336/// Copy NV12/P010 planes into `out`, after validating every plane against it.
337pub(crate) fn fill_i420(
338 out: &mut I420,
339 bit_depth: u8,
340 y_plane: &[u8],
341 y_pitch: usize,
342 uv_plane: &[u8],
343 uv_pitch: usize,
344) -> Result<()> {
345 let (w, h) = (out.width as usize, out.height as usize);
346 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
347 let bytes = if bit_depth == 8 { 1 } else { 2 };
348 check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?;
349 check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?;
350 let mut row_buf = vec![0u8; uv_pitch.max(y_pitch).max(w * 2)];
351 match bit_depth {
352 8 => {
353 for row in 0..h {
354 let src = row * y_pitch;
355 out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
356 }
357 for row in 0..ch {
358 let src = row * uv_pitch;
359 let line = &mut row_buf[..cw * 2];
360 line.copy_from_slice(&uv_plane[src..src + cw * 2]);
361 for col in 0..cw {
362 out.u[row * cw + col] = line[col * 2];
363 out.v[row * cw + col] = line[col * 2 + 1];
364 }
365 }
366 }
367 _ => {
368 // P010 keeps the sample in the *high* bits of each u16, so the
369 // 8-bit value is the high byte — a shift by 8, not by 2.
370 for row in 0..h {
371 let src = row * y_pitch;
372 let line = &mut row_buf[..w * 2];
373 line.copy_from_slice(&y_plane[src..src + w * 2]);
374 for col in 0..w {
375 out.y[row * w + col] = line[col * 2 + 1];
376 }
377 }
378 for row in 0..ch {
379 let src = row * uv_pitch;
380 let line = &mut row_buf[..cw * 4];
381 line.copy_from_slice(&uv_plane[src..src + cw * 4]);
382 for col in 0..cw {
383 out.u[row * cw + col] = line[col * 4 + 1];
384 out.v[row * cw + col] = line[col * 4 + 3];
385 }
386 }
387 }
388 }
389 Ok(())
390}
391
392/// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of
393/// `len` bytes. A lost or half-initialised GPU context can hand back a short
394/// or odd mapping; this turns what would be a slice panic into an error.
395pub(crate) fn check_plane(
396 name: &str,
397 len: usize,
398 pitch: usize,
399 rows: usize,
400 row_bytes: usize,
401) -> Result<()> {
402 if rows == 0 || row_bytes == 0 {
403 return Ok(());
404 }
405 let need = (rows - 1)
406 .checked_mul(pitch)
407 .and_then(|n| n.checked_add(row_bytes));
408 match need {
409 Some(need) if pitch >= row_bytes && need <= len => Ok(()),
410 _ => Err(Error::config(format!(
411 "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes"
412 ))),
413 }
414}
415
416pub(crate) fn i420_16_to_p010(src: &I420_16) -> (Vec<u8>, Vec<u8>) {
417 let le = |v: &u16| (v << 6).to_le_bytes();
418 let y = src.y.iter().flat_map(le).collect();
419 let uv = src
420 .u
421 .iter()
422 .zip(&src.v)
423 .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten())
424 .collect();
425 (y, uv)
426}
427
428/// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
429pub fn i420_to_nv12(
430 src: &I420,
431 y_out: &mut [u8],
432 y_pitch: usize,
433 uv_out: &mut [u8],
434 uv_pitch: usize,
435) {
436 let (w, h) = (src.width as usize, src.height as usize);
437 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
438 for row in 0..h {
439 let dst = row * y_pitch;
440 if dst + w > y_out.len() {
441 break;
442 }
443 y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]);
444 }
445 for row in 0..ch {
446 let dst = row * uv_pitch;
447 if dst + cw * 2 > uv_out.len() {
448 break;
449 }
450 for col in 0..cw {
451 uv_out[dst + col * 2] = src.u[row * cw + col];
452 uv_out[dst + col * 2 + 1] = src.v[row * cw + col];
453 }
454 }
455}