forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

decoder.rs343 lines, 11.9 KiBHistoryRawDownload
1// Copyright 2023 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cell::RefCell;
6use std::marker::PhantomData;
7use std::rc::Rc;
8use std::sync::Arc;
9
10use anyhow::anyhow;
11use anyhow::Context as AnyhowContext;
12use libva::{
13 Buffer, Context, Display, Picture, PictureEnd, PictureNew, PictureSync, Surface,
14 SurfaceMemoryDescriptor, VaError,
15};
16
17use crate::decoder::stateless::StatelessBackendResult;
18use crate::decoder::stateless::StatelessCodec;
19use crate::decoder::stateless::StatelessDecoderBackend;
20use crate::decoder::stateless::StatelessDecoderBackendPicture;
21use crate::decoder::DecodedHandle as DecodedHandleTrait;
22use crate::decoder::StreamInfo;
23use crate::video_frame::VideoFrame;
24use crate::DecodedFormat;
25use crate::Rect;
26use crate::Resolution;
27
28/// A decoded frame handle.
29pub(crate) type DecodedHandle<V> = Rc<RefCell<VaapiDecodedHandle<V>>>;
30
31/// Gets the VASurfaceID for the given `picture`.
32pub(crate) fn va_surface_id<V: VideoFrame>(
33 handle: &Option<DecodedHandle<V>>,
34) -> libva::VASurfaceID {
35 match handle {
36 None => libva::VA_INVALID_SURFACE,
37 Some(handle) => handle.borrow().surface().id(),
38 }
39}
40
41impl<V: VideoFrame> DecodedHandleTrait for DecodedHandle<V> {
42 type Frame = V;
43
44 fn video_frame(&self) -> Arc<Self::Frame> {
45 self.borrow().backing_frame.clone()
46 }
47
48 fn coded_resolution(&self) -> Resolution {
49 self.borrow().surface().size().into()
50 }
51
52 fn display_resolution(&self) -> Resolution {
53 self.borrow().display_resolution
54 }
55
56 fn timestamp(&self) -> u64 {
57 self.borrow().timestamp()
58 }
59
60 fn is_ready(&self) -> bool {
61 self.borrow().state.is_ready().unwrap_or(true)
62 }
63
64 fn sync(&self) -> anyhow::Result<()> {
65 self.borrow_mut().sync().context("while syncing picture")?;
66
67 Ok(())
68 }
69}
70
71/// A trait for providing the basic information needed to setup libva for decoding.
72pub(crate) trait VaStreamInfo {
73 /// Returns the VA profile of the stream.
74 fn va_profile(&self) -> anyhow::Result<i32>;
75 /// Returns the RT format of the stream.
76 fn rt_format(&self) -> anyhow::Result<u32>;
77 /// Returns the minimum number of surfaces required to decode the stream.
78 fn min_num_surfaces(&self) -> usize;
79 /// Returns the coded size of the surfaces required to decode the stream.
80 fn coded_size(&self) -> Resolution;
81 /// Returns the visible rectangle within the coded size for the stream.
82 fn visible_rect(&self) -> Rect;
83}
84
85/// Rendering state of a VA picture.
86enum PictureState<M: SurfaceMemoryDescriptor> {
87 Ready(Picture<PictureSync, Surface<M>>),
88 Pending(Picture<PictureEnd, Surface<M>>),
89 // Only set in sync when we take ownership of the VA picture.
90 Invalid,
91}
92
93impl<M: SurfaceMemoryDescriptor> PictureState<M> {
94 /// Make sure that all pending operations on the picture have completed.
95 fn sync(&mut self) -> Result<(), VaError> {
96 let res;
97
98 (*self, res) = match std::mem::replace(self, PictureState::Invalid) {
99 state @ PictureState::Ready(_) => (state, Ok(())),
100 PictureState::Pending(picture) => match picture.sync() {
101 Ok(picture) => (PictureState::Ready(picture), Ok(())),
102 Err((e, picture)) => (PictureState::Pending(picture), Err(e)),
103 },
104 PictureState::Invalid => unreachable!(),
105 };
106
107 res
108 }
109
110 fn surface(&self) -> &Surface<M> {
111 match self {
112 PictureState::Ready(picture) => picture.surface(),
113 PictureState::Pending(picture) => picture.surface(),
114 PictureState::Invalid => unreachable!(),
115 }
116 }
117
118 fn timestamp(&self) -> u64 {
119 match self {
120 PictureState::Ready(picture) => picture.timestamp(),
121 PictureState::Pending(picture) => picture.timestamp(),
122 PictureState::Invalid => unreachable!(),
123 }
124 }
125
126 fn is_ready(&self) -> Result<bool, VaError> {
127 match self {
128 PictureState::Ready(_) => Ok(true),
129 PictureState::Pending(picture) => picture
130 .surface()
131 .query_status()
132 .map(|s| s == libva::VASurfaceStatus::VASurfaceReady),
133 PictureState::Invalid => unreachable!(),
134 }
135 }
136
137 fn new_from_same_surface(&self, timestamp: u64) -> Picture<PictureNew, Surface<M>> {
138 match &self {
139 PictureState::Ready(picture) => Picture::new_from_same_surface(timestamp, picture),
140 PictureState::Pending(picture) => Picture::new_from_same_surface(timestamp, picture),
141 PictureState::Invalid => unreachable!(),
142 }
143 }
144}
145
146/// VA-API backend handle.
147///
148/// This includes the VA picture which can be pending rendering or complete, as well as useful
149/// meta-information.
150pub struct VaapiDecodedHandle<V: VideoFrame> {
151 backing_frame: Arc<V>,
152 state: PictureState<<V as VideoFrame>::MemDescriptor>,
153 /// Actual resolution of the visible rectangle in the decoded buffer.
154 display_resolution: Resolution,
155}
156
157impl<V: VideoFrame> VaapiDecodedHandle<V> {
158 /// Creates a new pending handle on `surface_id`.
159 fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> {
160 let backing_frame = picture.backing_frame;
161 let picture = picture.picture.begin()?.render()?.end()?;
162 Ok(Self {
163 backing_frame: backing_frame,
164 state: PictureState::Pending(picture),
165 display_resolution: display_resolution,
166 })
167 }
168
169 fn sync(&mut self) -> Result<(), VaError> {
170 self.state.sync()
171 }
172
173 /// Creates a new picture from the surface backing the current one. Useful for interlaced
174 /// decoding. TODO: Do we need this for other purposes? We don't intend to support interlaced.
175 pub(crate) fn new_picture_from_same_surface(&self, timestamp: u64) -> VaapiPicture<V> {
176 VaapiPicture {
177 picture: self.state.new_from_same_surface(timestamp),
178 backing_frame: self.backing_frame.clone(),
179 }
180 }
181
182 // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): made public so a client can
183 // read frames back with vaGetImage. Mapping the client-allocated DMA-BUF
184 // directly is a 44 MB/s uncached PCIe read on a discrete GPU; the driver's own
185 // copy path is ~100x faster.
186 pub fn surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> {
187 self.state.surface()
188 }
189
190 /// Returns the timestamp of this handle.
191 fn timestamp(&self) -> u64 {
192 self.state.timestamp()
193 }
194}
195
196pub struct VaapiBackend<V: VideoFrame> {
197 pub display: Rc<Display>,
198 pub context: Rc<Context>,
199 stream_info: StreamInfo,
200 // TODO: We should try to support context reuse
201 _supports_context_reuse: bool,
202 _phantom_data: PhantomData<V>,
203}
204
205impl<V: VideoFrame> VaapiBackend<V> {
206 pub(crate) fn new(display: Rc<libva::Display>, supports_context_reuse: bool) -> Self {
207 // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): upstream probes with a
208 // 16x16 context, which Mesa radeonsi rejects with VA_STATUS_ERROR_UNIMPLEMENTED
209 // (measured: 16x16 and 48x48 fail, 64x64 up succeed), and the `expect` below
210 // then aborts. This placeholder is replaced by `new_sequence` anyway.
211 let init_stream_info = StreamInfo {
212 format: DecodedFormat::NV12,
213 coded_resolution: Resolution::from((64, 64)),
214 display_resolution: Resolution::from((64, 64)),
215 min_num_frames: 1,
216 };
217 let config = display
218 .create_config(
219 vec![libva::VAConfigAttrib {
220 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
221 value: libva::VA_RT_FORMAT_YUV420,
222 }],
223 libva::VAProfile::VAProfileH264Main,
224 libva::VAEntrypoint::VAEntrypointVLD,
225 )
226 .expect("Could not create initial VAConfig!");
227 let context = display
228 .create_context::<<V as VideoFrame>::MemDescriptor>(
229 &config,
230 init_stream_info.coded_resolution.width,
231 init_stream_info.coded_resolution.height,
232 None,
233 true,
234 )
235 .expect("Could not create initial VAContext!");
236 Self {
237 display: display,
238 context: context,
239 _supports_context_reuse: supports_context_reuse,
240 stream_info: init_stream_info,
241 _phantom_data: Default::default(),
242 }
243 }
244
245 pub(crate) fn new_sequence<StreamData>(
246 &mut self,
247 stream_params: &StreamData,
248 ) -> StatelessBackendResult<()>
249 where
250 for<'a> &'a StreamData: VaStreamInfo,
251 {
252 self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect());
253 self.stream_info.coded_resolution = stream_params.coded_size().clone();
254 self.stream_info.min_num_frames = stream_params.min_num_surfaces();
255
256 // TODO: Handle context re-use
257 // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the RT format comes
258 // from the stream rather than being assumed 8-bit 4:2:0, which is what
259 // an HEVC Main 10 stream needs -- its surfaces are P010 and a
260 // YUV420-only config rejects them. This is upstream's own TODO, and
261 // `VaStreamInfo::rt_format` is upstream's own answer to it.
262 let rt_format = stream_params.rt_format().unwrap_or(libva::VA_RT_FORMAT_YUV420);
263 let config = self
264 .display
265 .create_config(
266 vec![libva::VAConfigAttrib {
267 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
268 value: rt_format,
269 }],
270 stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?,
271 libva::VAEntrypoint::VAEntrypointVLD,
272 )
273 .map_err(|_| anyhow!("Could not create VAConfig!"))?;
274 let context = self
275 .display
276 .create_context::<<V as VideoFrame>::MemDescriptor>(
277 &config,
278 self.stream_info.coded_resolution.width,
279 self.stream_info.coded_resolution.height,
280 None,
281 true,
282 )
283 .map_err(|_| anyhow!("Could not create VAContext!"))?;
284 self.context = context;
285
286 Ok(())
287 }
288
289 pub(crate) fn process_picture<Codec: StatelessCodec>(
290 &mut self,
291 picture: VaapiPicture<V>,
292 ) -> StatelessBackendResult<<Self as StatelessDecoderBackend>::Handle>
293 where
294 Self: StatelessDecoderBackendPicture<Codec>,
295 for<'a> &'a Codec::FormatInfo: VaStreamInfo,
296 {
297 Ok(Rc::new(RefCell::new(VaapiDecodedHandle::new(
298 picture,
299 self.stream_info.display_resolution.clone(),
300 )?)))
301 }
302}
303
304/// Shortcut for pictures used for the VAAPI backend.
305pub struct VaapiPicture<V: VideoFrame> {
306 picture: Picture<PictureNew, Surface<V::MemDescriptor>>,
307 backing_frame: Arc<V>,
308}
309
310impl<V: VideoFrame> VaapiPicture<V> {
311 pub fn new(timestamp: u64, context: Rc<Context>, backing_frame: V) -> Self {
312 let display = context.display();
313 let surface = backing_frame
314 .to_native_handle(display)
315 .expect("Failed to export video frame to vaapi picture!")
316 .into();
317 Self {
318 backing_frame: Arc::new(backing_frame),
319 picture: Picture::new(timestamp, context, surface),
320 }
321 }
322
323 pub fn surface(&self) -> &Surface<V::MemDescriptor> {
324 self.picture.surface()
325 }
326
327 pub fn add_buffer(&mut self, buffer: Buffer) {
328 self.picture.add_buffer(buffer)
329 }
330}
331
332impl<V: VideoFrame> StatelessDecoderBackend for VaapiBackend<V> {
333 type Handle = DecodedHandle<V>;
334
335 fn stream_info(&self) -> Option<&StreamInfo> {
336 Some(&self.stream_info)
337 }
338
339 fn reset_backend(&mut self) -> anyhow::Result<()> {
340 //TODO(bchoobineh): Implement VAAPI DRC
341 Ok(())
342 }
343}