forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

decoder.rs339 lines, 11.5 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 #[allow(dead_code)]
77 fn rt_format(&self) -> anyhow::Result<u32>;
78 /// Returns the minimum number of surfaces required to decode the stream.
79 fn min_num_surfaces(&self) -> usize;
80 /// Returns the coded size of the surfaces required to decode the stream.
81 fn coded_size(&self) -> Resolution;
82 /// Returns the visible rectangle within the coded size for the stream.
83 fn visible_rect(&self) -> Rect;
84}
85
86/// Rendering state of a VA picture.
87enum PictureState<M: SurfaceMemoryDescriptor> {
88 Ready(Picture<PictureSync, Surface<M>>),
89 Pending(Picture<PictureEnd, Surface<M>>),
90 // Only set in sync when we take ownership of the VA picture.
91 Invalid,
92}
93
94impl<M: SurfaceMemoryDescriptor> PictureState<M> {
95 /// Make sure that all pending operations on the picture have completed.
96 fn sync(&mut self) -> Result<(), VaError> {
97 let res;
98
99 (*self, res) = match std::mem::replace(self, PictureState::Invalid) {
100 state @ PictureState::Ready(_) => (state, Ok(())),
101 PictureState::Pending(picture) => match picture.sync() {
102 Ok(picture) => (PictureState::Ready(picture), Ok(())),
103 Err((e, picture)) => (PictureState::Pending(picture), Err(e)),
104 },
105 PictureState::Invalid => unreachable!(),
106 };
107
108 res
109 }
110
111 fn surface(&self) -> &Surface<M> {
112 match self {
113 PictureState::Ready(picture) => picture.surface(),
114 PictureState::Pending(picture) => picture.surface(),
115 PictureState::Invalid => unreachable!(),
116 }
117 }
118
119 fn timestamp(&self) -> u64 {
120 match self {
121 PictureState::Ready(picture) => picture.timestamp(),
122 PictureState::Pending(picture) => picture.timestamp(),
123 PictureState::Invalid => unreachable!(),
124 }
125 }
126
127 fn is_ready(&self) -> Result<bool, VaError> {
128 match self {
129 PictureState::Ready(_) => Ok(true),
130 PictureState::Pending(picture) => picture
131 .surface()
132 .query_status()
133 .map(|s| s == libva::VASurfaceStatus::VASurfaceReady),
134 PictureState::Invalid => unreachable!(),
135 }
136 }
137
138 fn new_from_same_surface(&self, timestamp: u64) -> Picture<PictureNew, Surface<M>> {
139 match &self {
140 PictureState::Ready(picture) => Picture::new_from_same_surface(timestamp, picture),
141 PictureState::Pending(picture) => Picture::new_from_same_surface(timestamp, picture),
142 PictureState::Invalid => unreachable!(),
143 }
144 }
145}
146
147/// VA-API backend handle.
148///
149/// This includes the VA picture which can be pending rendering or complete, as well as useful
150/// meta-information.
151pub struct VaapiDecodedHandle<V: VideoFrame> {
152 backing_frame: Arc<V>,
153 state: PictureState<<V as VideoFrame>::MemDescriptor>,
154 /// Actual resolution of the visible rectangle in the decoded buffer.
155 display_resolution: Resolution,
156}
157
158impl<V: VideoFrame> VaapiDecodedHandle<V> {
159 /// Creates a new pending handle on `surface_id`.
160 fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> {
161 let backing_frame = picture.backing_frame;
162 let picture = picture.picture.begin()?.render()?.end()?;
163 Ok(Self {
164 backing_frame: backing_frame,
165 state: PictureState::Pending(picture),
166 display_resolution: display_resolution,
167 })
168 }
169
170 fn sync(&mut self) -> Result<(), VaError> {
171 self.state.sync()
172 }
173
174 /// Creates a new picture from the surface backing the current one. Useful for interlaced
175 /// decoding. TODO: Do we need this for other purposes? We don't intend to support interlaced.
176 pub(crate) fn new_picture_from_same_surface(&self, timestamp: u64) -> VaapiPicture<V> {
177 VaapiPicture {
178 picture: self.state.new_from_same_surface(timestamp),
179 backing_frame: self.backing_frame.clone(),
180 }
181 }
182
183 // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): made public so a client can
184 // read frames back with vaGetImage. Mapping the client-allocated DMA-BUF
185 // directly is a 44 MB/s uncached PCIe read on a discrete GPU; the driver's own
186 // copy path is ~100x faster.
187 pub fn surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> {
188 self.state.surface()
189 }
190
191 /// Returns the timestamp of this handle.
192 fn timestamp(&self) -> u64 {
193 self.state.timestamp()
194 }
195}
196
197pub struct VaapiBackend<V: VideoFrame> {
198 pub display: Rc<Display>,
199 pub context: Rc<Context>,
200 stream_info: StreamInfo,
201 // TODO: We should try to support context reuse
202 _supports_context_reuse: bool,
203 _phantom_data: PhantomData<V>,
204}
205
206impl<V: VideoFrame> VaapiBackend<V> {
207 pub(crate) fn new(display: Rc<libva::Display>, supports_context_reuse: bool) -> Self {
208 // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): upstream probes with a
209 // 16x16 context, which Mesa radeonsi rejects with VA_STATUS_ERROR_UNIMPLEMENTED
210 // (measured: 16x16 and 48x48 fail, 64x64 up succeed), and the `expect` below
211 // then aborts. This placeholder is replaced by `new_sequence` anyway.
212 let init_stream_info = StreamInfo {
213 format: DecodedFormat::NV12,
214 coded_resolution: Resolution::from((64, 64)),
215 display_resolution: Resolution::from((64, 64)),
216 min_num_frames: 1,
217 };
218 let config = display
219 .create_config(
220 vec![libva::VAConfigAttrib {
221 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
222 value: libva::VA_RT_FORMAT_YUV420,
223 }],
224 libva::VAProfile::VAProfileH264Main,
225 libva::VAEntrypoint::VAEntrypointVLD,
226 )
227 .expect("Could not create initial VAConfig!");
228 let context = display
229 .create_context::<<V as VideoFrame>::MemDescriptor>(
230 &config,
231 init_stream_info.coded_resolution.width,
232 init_stream_info.coded_resolution.height,
233 None,
234 true,
235 )
236 .expect("Could not create initial VAContext!");
237 Self {
238 display: display,
239 context: context,
240 _supports_context_reuse: supports_context_reuse,
241 stream_info: init_stream_info,
242 _phantom_data: Default::default(),
243 }
244 }
245
246 pub(crate) fn new_sequence<StreamData>(
247 &mut self,
248 stream_params: &StreamData,
249 ) -> StatelessBackendResult<()>
250 where
251 for<'a> &'a StreamData: VaStreamInfo,
252 {
253 self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect());
254 self.stream_info.coded_resolution = stream_params.coded_size().clone();
255 self.stream_info.min_num_frames = stream_params.min_num_surfaces();
256
257 // TODO: Handle context re-use
258 // TODO: We should obtain RT_FORMAT from stream_info
259 let config = self
260 .display
261 .create_config(
262 vec![libva::VAConfigAttrib {
263 type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
264 value: libva::VA_RT_FORMAT_YUV420,
265 }],
266 stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?,
267 libva::VAEntrypoint::VAEntrypointVLD,
268 )
269 .map_err(|_| anyhow!("Could not create VAConfig!"))?;
270 let context = self
271 .display
272 .create_context::<<V as VideoFrame>::MemDescriptor>(
273 &config,
274 self.stream_info.coded_resolution.width,
275 self.stream_info.coded_resolution.height,
276 None,
277 true,
278 )
279 .map_err(|_| anyhow!("Could not create VAContext!"))?;
280 self.context = context;
281
282 Ok(())
283 }
284
285 pub(crate) fn process_picture<Codec: StatelessCodec>(
286 &mut self,
287 picture: VaapiPicture<V>,
288 ) -> StatelessBackendResult<<Self as StatelessDecoderBackend>::Handle>
289 where
290 Self: StatelessDecoderBackendPicture<Codec>,
291 for<'a> &'a Codec::FormatInfo: VaStreamInfo,
292 {
293 Ok(Rc::new(RefCell::new(VaapiDecodedHandle::new(
294 picture,
295 self.stream_info.display_resolution.clone(),
296 )?)))
297 }
298}
299
300/// Shortcut for pictures used for the VAAPI backend.
301pub struct VaapiPicture<V: VideoFrame> {
302 picture: Picture<PictureNew, Surface<V::MemDescriptor>>,
303 backing_frame: Arc<V>,
304}
305
306impl<V: VideoFrame> VaapiPicture<V> {
307 pub fn new(timestamp: u64, context: Rc<Context>, backing_frame: V) -> Self {
308 let display = context.display();
309 let surface = backing_frame
310 .to_native_handle(display)
311 .expect("Failed to export video frame to vaapi picture!")
312 .into();
313 Self {
314 backing_frame: Arc::new(backing_frame),
315 picture: Picture::new(timestamp, context, surface),
316 }
317 }
318
319 pub fn surface(&self) -> &Surface<V::MemDescriptor> {
320 self.picture.surface()
321 }
322
323 pub fn add_buffer(&mut self, buffer: Buffer) {
324 self.picture.add_buffer(buffer)
325 }
326}
327
328impl<V: VideoFrame> StatelessDecoderBackend for VaapiBackend<V> {
329 type Handle = DecodedHandle<V>;
330
331 fn stream_info(&self) -> Option<&StreamInfo> {
332 Some(&self.stream_info)
333 }
334
335 fn reset_backend(&mut self) -> anyhow::Result<()> {
336 //TODO(bchoobineh): Implement VAAPI DRC
337 Ok(())
338 }
339}