forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

output.rs454 lines, 14.1 KiBHistoryRawDownload
1//! What a decoder hands out: a picture held in its GPU ring slot (Vulkan) or
2//! a VA-API frame, converted on request to I420, 10-bit I420, packed RGB or a
3//! DMA-BUF.
4
5use std::cell::RefCell;
6use std::rc::Rc;
7
8use ec_av1_syntax::{FilmGrainParams, SequenceHeader};
9use ec_core::color::Matrix;
10#[cfg(target_os = "linux")]
11use ec_core::color::{ColorDescription, Tags};
12use ec_vk::{
13 Av1DecodeSession, H264DecodeSession, H265DecodeSession, Vp9DecodeSession,
14};
15
16use crate::error::{Error, Result};
17use crate::hw::{RgbOrder, RgbOutput};
18use crate::picture::{
19 Colour, I420, I420_16, RgbPicture, i420_16_to_p010, i420_to_rgb, i420_to_nv12, rgb_size,
20 semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb,
21};
22use crate::vkdec_av1::{synthesize, synthesize16};
23#[cfg(target_os = "linux")]
24use crate::frame::Frame;
25#[cfg(target_os = "linux")]
26use crate::picture::DmaBufPicture;
27
28/// One decoded picture, as a handle on its ring slot in the decode session.
29pub struct HwPicture {
30 /// Presentation timestamp of the access unit the picture came from.
31 pub timestamp: i64,
32 /// Display width in luma samples.
33 pub width: u32,
34 /// Display height in luma samples.
35 pub height: u32,
36 /// Luma bit depth: 8 or 10.
37 pub bit_depth: u8,
38 /// Colour metadata, when the decoder resolved some.
39 pub colour: Option<Colour>,
40 source: Source,
41}
42
43enum Source {
44 Vk(VkPicture),
45 #[cfg(target_os = "linux")]
46 Va(Frame),
47}
48
49impl HwPicture {
50 pub(crate) fn vk(timestamp: i64, picture: VkPicture) -> HwPicture {
51 HwPicture {
52 timestamp,
53 width: picture.width,
54 height: picture.height,
55 bit_depth: picture.bit_depth,
56 colour: None,
57 source: Source::Vk(picture),
58 }
59 }
60
61 #[cfg(target_os = "linux")]
62 pub(crate) fn va(frame: Frame) -> HwPicture {
63 HwPicture {
64 timestamp: frame.timestamp,
65 width: frame.display_size.0,
66 height: frame.display_size.1,
67 bit_depth: frame.bit_depth,
68 colour: frame.colour,
69 source: Source::Va(frame),
70 }
71 }
72
73 /// 8-bit I420 at display size. A 10-bit picture is truncated to 8 bits.
74 pub fn to_i420(&self) -> Result<I420> {
75 match &self.source {
76 Source::Vk(picture) => picture.i420(),
77 #[cfg(target_os = "linux")]
78 Source::Va(frame) => frame.to_i420(),
79 }
80 }
81
82 /// 10-bit I420 at display size. An 8-bit picture is widened to 10 bits.
83 pub fn to_i420_16(&self) -> Result<I420_16> {
84 match &self.source {
85 Source::Vk(picture) => picture.i420_16(),
86 #[cfg(target_os = "linux")]
87 Source::Va(frame) => frame.to_i420_16(),
88 }
89 }
90
91 /// Packed RGB, scaled and byte-ordered as `output` asks.
92 pub fn to_rgb(&self, output: &RgbOutput) -> Result<RgbPicture> {
93 let mut dst = RgbPicture::default();
94 self.rgb_into(output, &mut dst)?;
95 Ok(dst)
96 }
97
98 /// [`HwPicture::to_rgb`] into `dst`, reusing its allocation.
99 pub fn rgb_into(&self, output: &RgbOutput, dst: &mut RgbPicture) -> Result<()> {
100 match &self.source {
101 Source::Vk(picture) => picture.rgb(output, dst),
102 #[cfg(target_os = "linux")]
103 Source::Va(frame) => {
104 let i420 = frame.to_i420()?;
105 let matrix = frame
106 .colour
107 .map(|c| c.description.matrix)
108 .unwrap_or_else(|| default_matrix(i420.height));
109 *dst = i420_to_rgb(
110 &i420,
111 output.bound(),
112 output.order == RgbOrder::Bgra,
113 matrix,
114 );
115 Ok(())
116 }
117 }
118 }
119
120 /// One DMA-BUF of NV12 or P010 planes at display size, with film grain applied when the picture has it.
121 #[cfg(target_os = "linux")]
122 pub fn export_dmabuf(&self) -> Result<DmaBufPicture> {
123 match &self.source {
124 Source::Vk(picture) => picture.export(),
125 Source::Va(frame) => Ok(dmabuf_from_prime(frame.export_prime()?)?),
126 }
127 }
128}
129
130/// The GPU ring of one decode session: a token per slot, held by every picture still using the slot.
131pub(crate) struct Ring {
132 tokens: Vec<Rc<()>>,
133}
134
135impl Ring {
136 pub(crate) fn new(len: u32) -> Ring {
137 Ring {
138 tokens: (0..len).map(|_| Rc::new(())).collect(),
139 }
140 }
141
142 /// The first free slot, or a new one from `grow` when every slot is held.
143 pub(crate) fn take(&mut self, grow: impl FnOnce() -> Result<u32>) -> Result<Slot> {
144 let index = match self
145 .tokens
146 .iter()
147 .position(|token| Rc::strong_count(token) == 1)
148 {
149 Some(index) => index,
150 None => {
151 let index = grow()? as usize;
152 if index != self.tokens.len() {
153 return Err(Error::config("output ring out of step with the decoder"));
154 }
155 self.tokens.push(Rc::new(()));
156 index
157 }
158 };
159 Ok(Slot {
160 index: index as u32,
161 _held: self.tokens[index].clone(),
162 })
163 }
164}
165
166/// A ring slot in use. The slot is free again once every copy of this handle is dropped.
167#[derive(Clone)]
168pub(crate) struct Slot {
169 index: u32,
170 _held: Rc<()>,
171}
172
173impl Slot {
174 pub(crate) fn index(&self) -> u32 {
175 self.index
176 }
177}
178
179/// The decode session's output images, shared with every picture decoded in it.
180#[derive(Clone)]
181pub(crate) enum Surfaces {
182 H264(Rc<RefCell<H264DecodeSession>>),
183 H265(Rc<RefCell<H265DecodeSession>>),
184 Av1(Rc<RefCell<Av1DecodeSession>>),
185 Vp9(Rc<RefCell<Vp9DecodeSession>>),
186}
187
188impl Surfaces {
189 fn nv12(&self, slot: u32, width: u32, height: u32) -> Result<(Vec<u8>, Vec<u8>)> {
190 Ok(match self {
191 Surfaces::H264(s) => s.borrow_mut().read_output(slot, width, height)?,
192 Surfaces::H265(s) => s.borrow_mut().read_output(slot, width, height)?,
193 Surfaces::Av1(s) => s.borrow_mut().read_output(slot, width, height)?,
194 Surfaces::Vp9(s) => s.borrow_mut().read_output(slot, width, height)?,
195 })
196 }
197
198 fn rgb(
199 &self,
200 slot: u32,
201 crop: (u32, u32, u32, u32),
202 out: (u32, u32),
203 bgra: bool,
204 coeffs: [i32; 5],
205 dst: &mut Vec<u8>,
206 ) -> Result<()> {
207 match self {
208 Surfaces::H264(s) => s
209 .borrow_mut()
210 .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?,
211 Surfaces::H265(s) => s
212 .borrow_mut()
213 .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?,
214 Surfaces::Av1(s) => s
215 .borrow_mut()
216 .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?,
217 Surfaces::Vp9(s) => s
218 .borrow_mut()
219 .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?,
220 }
221 Ok(())
222 }
223
224 #[cfg(target_os = "linux")]
225 fn export(&self, slot: u32, width: u32, height: u32) -> Result<ec_vk::DmaBufExport> {
226 Ok(match self {
227 Surfaces::H264(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
228 Surfaces::H265(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
229 Surfaces::Av1(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
230 Surfaces::Vp9(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?,
231 })
232 }
233}
234
235/// A picture in a ring slot: its display size, bit depth, matrix and, for AV1, the film grain to apply when it is shown.
236#[derive(Clone)]
237pub(crate) struct VkPicture {
238 surfaces: Surfaces,
239 slot: Slot,
240 width: u32,
241 height: u32,
242 bit_depth: u8,
243 matrix: Matrix,
244 grain: Option<Grain>,
245 ring: Option<Rc<RefCell<Ring>>>,
246 grained: Rc<RefCell<Option<Slot>>>,
247}
248
249#[derive(Clone)]
250struct Grain {
251 params: FilmGrainParams,
252 seq: SequenceHeader,
253}
254
255impl VkPicture {
256 pub(crate) fn new(
257 surfaces: Surfaces,
258 slot: Slot,
259 (width, height): (u32, u32),
260 bit_depth: u8,
261 matrix: Matrix,
262 ) -> VkPicture {
263 VkPicture {
264 surfaces,
265 slot,
266 width,
267 height,
268 bit_depth,
269 matrix,
270 grain: None,
271 ring: None,
272 grained: Rc::new(RefCell::new(None)),
273 }
274 }
275
276 pub(crate) fn with_ring(mut self, ring: Rc<RefCell<Ring>>) -> VkPicture {
277 self.ring = Some(ring);
278 self
279 }
280
281 /// This picture as it is shown with `grain`: unchanged when the frame applies none.
282 pub(crate) fn with_grain(&self, params: &FilmGrainParams, seq: &SequenceHeader) -> VkPicture {
283 let mut shown = self.clone();
284 if params.apply_grain {
285 shown.grained = Rc::new(RefCell::new(None));
286 shown.grain = Some(Grain {
287 params: params.clone(),
288 seq: seq.clone(),
289 });
290 }
291 shown
292 }
293
294 fn read(&self) -> Result<(Vec<u8>, Vec<u8>)> {
295 self.surfaces.nv12(
296 self.slot.index,
297 self.width.next_multiple_of(2),
298 self.height.next_multiple_of(2),
299 )
300 }
301
302 fn i420(&self) -> Result<I420> {
303 let (y, uv) = self.read()?;
304 let frame = semi_planar_to_i420(
305 self.bit_depth,
306 &y,
307 &uv,
308 self.width.next_multiple_of(2) as usize,
309 (0, 0),
310 (self.width, self.height),
311 )?;
312 Ok(match &self.grain {
313 Some(g) => synthesize(frame, &g.params, &g.seq),
314 None => frame,
315 })
316 }
317
318 fn i420_16(&self) -> Result<I420_16> {
319 let (y, uv) = self.read()?;
320 let frame = semi_planar_to_i420_16(
321 self.bit_depth,
322 &y,
323 &uv,
324 self.width.next_multiple_of(2) as usize,
325 (0, 0),
326 (self.width, self.height),
327 )?;
328 Ok(match &self.grain {
329 Some(g) => synthesize16(frame, &g.params, &g.seq),
330 None => frame,
331 })
332 }
333
334 fn rgb(&self, output: &RgbOutput, dst: &mut RgbPicture) -> Result<()> {
335 let bgra = output.order == RgbOrder::Bgra;
336 if self.grain.is_some() {
337 if self.bit_depth != 8 {
338 return Err(Error::unsupported(
339 "Vulkan AV1 film grain",
340 "RGB of 10-bit output",
341 ));
342 }
343 *dst = i420_to_rgb(&self.i420()?, output.bound(), bgra, self.matrix);
344 return Ok(());
345 }
346 let (w, h) = rgb_size(self.width, self.height, output.bound());
347 self.surfaces.rgb(
348 self.slot.index,
349 (0, 0, self.width, self.height),
350 (w, h),
351 bgra,
352 yuv_to_rgb(self.matrix).words(),
353 &mut dst.data,
354 )?;
355 dst.width = w;
356 dst.height = h;
357 dst.stride = w * 4;
358 Ok(())
359 }
360
361 #[cfg(target_os = "linux")]
362 fn export(&self) -> Result<DmaBufPicture> {
363 match &self.grain {
364 None => Ok(self
365 .surfaces
366 .export(self.slot.index, self.width, self.height)?
367 .into()),
368 Some(grain) => self.export_grained(grain),
369 }
370 }
371
372 #[cfg(target_os = "linux")]
373 fn export_grained(&self, grain: &Grain) -> Result<DmaBufPicture> {
374 let (Surfaces::Av1(session), Some(ring)) = (&self.surfaces, &self.ring) else {
375 return Err(Error::unsupported(
376 "Vulkan DMA-BUF export",
377 "film grain outside AV1 or without an output ring",
378 ));
379 };
380 let mut grained = self.grained.borrow_mut();
381 let slot = match grained.take() {
382 Some(slot) => slot,
383 None => self.grain_slot(session, ring, grain)?,
384 };
385 let export = session.borrow_mut().read_output_dmabuf(
386 slot.index(),
387 self.width,
388 self.height,
389 );
390 *grained = Some(slot);
391 Ok(export?.into())
392 }
393
394 #[cfg(target_os = "linux")]
395 fn grain_slot(
396 &self,
397 session: &Rc<RefCell<Av1DecodeSession>>,
398 ring: &Rc<RefCell<Ring>>,
399 grain: &Grain,
400 ) -> Result<Slot> {
401 let (width, height) = (self.width, self.height);
402 let (y, uv) = self.read()?;
403 let (y, uv) = if self.bit_depth == 8 {
404 let frame = semi_planar_to_i420(8, &y, &uv, width as usize, (0, 0), (width, height))?;
405 let frame = synthesize(frame, &grain.params, &grain.seq);
406 let luma = width as usize * height as usize;
407 let (mut y, mut uv) = (vec![0; luma], vec![0; luma / 2]);
408 i420_to_nv12(&frame, &mut y, width as usize, &mut uv, width as usize);
409 (y, uv)
410 } else {
411 let frame =
412 semi_planar_to_i420_16(self.bit_depth, &y, &uv, width as usize, (0, 0), (width, height))?;
413 i420_16_to_p010(&synthesize16(frame, &grain.params, &grain.seq))
414 };
415 let slot = ring
416 .borrow_mut()
417 .take(|| Ok(session.borrow_mut().add_ring_slot()?))?;
418 session
419 .borrow_mut()
420 .upload_output(slot.index(), (width, height), &y, &uv)?;
421 Ok(slot)
422 }
423}
424
425#[cfg(target_os = "linux")]
426fn default_matrix(height: u32) -> Matrix {
427 ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix
428}
429
430#[cfg(target_os = "linux")]
431fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result<DmaBufPicture> {
432 let planes: Vec<(u32, u32, u32)> = surface
433 .layers
434 .iter()
435 .flat_map(|layer| layer.planes.iter().copied())
436 .collect();
437 let [y, uv] = planes.as_slice() else {
438 return Err(Error::config("exported surface is not a two-plane 4:2:0 picture"));
439 };
440 let plane = |&(object, offset, pitch): &(u32, u32, u32)| ec_vk::DmaBufPlane {
441 fd: object as usize,
442 offset,
443 pitch,
444 };
445 let modifier = surface.objects.first().map_or(0, |o| o.modifier);
446 Ok(DmaBufPicture {
447 fds: surface.objects.into_iter().map(|o| o.fd).collect(),
448 fourcc: surface.fourcc,
449 modifier,
450 width: surface.width,
451 height: surface.height,
452 planes: [plane(y), plane(uv)],
453 })
454}