edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·978e685·Tahinli·3 months ago·627 commits
| 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 | |
| 5 | use std::cell::RefCell; |
| 6 | use std::marker::PhantomData; |
| 7 | use std::rc::Rc; |
| 8 | use std::sync::Arc; |
| 9 | |
| 10 | use anyhow::anyhow; |
| 11 | use anyhow::Context as AnyhowContext; |
| 12 | use libva::{ |
| 13 | Buffer, Context, Display, Picture, PictureEnd, PictureNew, PictureSync, Surface, |
| 14 | SurfaceMemoryDescriptor, VaError, |
| 15 | }; |
| 16 | |
| 17 | use crate::decoder::stateless::StatelessBackendResult; |
| 18 | use crate::decoder::stateless::StatelessCodec; |
| 19 | use crate::decoder::stateless::StatelessDecoderBackend; |
| 20 | use crate::decoder::stateless::StatelessDecoderBackendPicture; |
| 21 | use crate::decoder::DecodedHandle as DecodedHandleTrait; |
| 22 | use crate::decoder::StreamInfo; |
| 23 | use crate::video_frame::VideoFrame; |
| 24 | use crate::DecodedFormat; |
| 25 | use crate::Rect; |
| 26 | use crate::Resolution; |
| 27 | |
| 28 | /// A decoded frame handle. |
| 29 | pub(crate) type DecodedHandle<V> = Rc<RefCell<VaapiDecodedHandle<V>>>; |
| 30 | |
| 31 | /// Gets the VASurfaceID for the given `picture`. |
| 32 | pub(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 | |
| 41 | impl<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. |
| 72 | pub(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. |
| 86 | enum 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 | |
| 93 | impl<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. |
| 150 | pub 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 | /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the second surface an |
| 156 | /// AV1 picture with `apply_grain` set is *displayed* from -- the driver |
| 157 | /// synthesizes the grain into it and leaves the reconstructed picture, which |
| 158 | /// is what later frames reference, untouched in `state`'s own surface. |
| 159 | /// `None` for every picture that asks for no grain, which is every picture |
| 160 | /// of every other codec. |
| 161 | display: Option<(Arc<V>, Surface<<V as VideoFrame>::MemDescriptor>)>, |
| 162 | } |
| 163 | |
| 164 | impl<V: VideoFrame> VaapiDecodedHandle<V> { |
| 165 | /// Creates a new pending handle on `surface_id`. |
| 166 | fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> { |
| 167 | let backing_frame = picture.backing_frame; |
| 168 | let display = picture.display; |
| 169 | let picture = picture.picture.begin()?.render()?.end()?; |
| 170 | Ok(Self { |
| 171 | backing_frame: backing_frame, |
| 172 | state: PictureState::Pending(picture), |
| 173 | display_resolution: display_resolution, |
| 174 | display: display, |
| 175 | }) |
| 176 | } |
| 177 | |
| 178 | fn sync(&mut self) -> Result<(), VaError> { |
| 179 | self.state.sync()?; |
| 180 | // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the grain is |
| 181 | // synthesized into a surface of its own, and it is that one the pixels |
| 182 | // are read back off, so waiting only on the reconstructed picture would |
| 183 | // hand out a half-written frame. |
| 184 | if let Some((_, surface)) = &self.display { |
| 185 | surface.sync()?; |
| 186 | } |
| 187 | Ok(()) |
| 188 | } |
| 189 | |
| 190 | /// Creates a new picture from the surface backing the current one. Useful for interlaced |
| 191 | /// decoding. TODO: Do we need this for other purposes? We don't intend to support interlaced. |
| 192 | pub(crate) fn new_picture_from_same_surface(&self, timestamp: u64) -> VaapiPicture<V> { |
| 193 | VaapiPicture { |
| 194 | picture: self.state.new_from_same_surface(timestamp), |
| 195 | backing_frame: self.backing_frame.clone(), |
| 196 | // Interlaced H.264 only, which no codec here asks film grain of. |
| 197 | display: None, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): made public so a client can |
| 202 | // read frames back with vaGetImage. Mapping the client-allocated DMA-BUF |
| 203 | // directly is a 44 MB/s uncached PCIe read on a discrete GPU; the driver's own |
| 204 | // copy path is ~100x faster. |
| 205 | pub fn surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> { |
| 206 | self.state.surface() |
| 207 | } |
| 208 | |
| 209 | /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the surface a *viewer* |
| 210 | /// wants, which is the grain-synthesized one where there is one and the |
| 211 | /// reconstructed picture everywhere else. [`Self::surface`] stays the |
| 212 | /// reconstructed one on purpose: that is what the reference lists point at. |
| 213 | pub fn display_surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> { |
| 214 | match &self.display { |
| 215 | Some((_, surface)) => surface, |
| 216 | None => self.state.surface(), |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// Returns the timestamp of this handle. |
| 221 | fn timestamp(&self) -> u64 { |
| 222 | self.state.timestamp() |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | pub struct VaapiBackend<V: VideoFrame> { |
| 227 | pub display: Rc<Display>, |
| 228 | pub context: Rc<Context>, |
| 229 | stream_info: StreamInfo, |
| 230 | // TODO: We should try to support context reuse |
| 231 | _supports_context_reuse: bool, |
| 232 | _phantom_data: PhantomData<V>, |
| 233 | } |
| 234 | |
| 235 | impl<V: VideoFrame> VaapiBackend<V> { |
| 236 | pub(crate) fn new(display: Rc<libva::Display>, supports_context_reuse: bool) -> Self { |
| 237 | // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): upstream probes with a |
| 238 | // 16x16 context, which Mesa radeonsi rejects with VA_STATUS_ERROR_UNIMPLEMENTED |
| 239 | // (measured: 16x16 and 48x48 fail, 64x64 up succeed), and the `expect` below |
| 240 | // then aborts. This placeholder is replaced by `new_sequence` anyway. |
| 241 | let init_stream_info = StreamInfo { |
| 242 | format: DecodedFormat::NV12, |
| 243 | coded_resolution: Resolution::from((64, 64)), |
| 244 | display_resolution: Resolution::from((64, 64)), |
| 245 | min_num_frames: 1, |
| 246 | }; |
| 247 | let config = display |
| 248 | .create_config( |
| 249 | vec![libva::VAConfigAttrib { |
| 250 | type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, |
| 251 | value: libva::VA_RT_FORMAT_YUV420, |
| 252 | }], |
| 253 | libva::VAProfile::VAProfileH264Main, |
| 254 | libva::VAEntrypoint::VAEntrypointVLD, |
| 255 | ) |
| 256 | .expect("Could not create initial VAConfig!"); |
| 257 | let context = display |
| 258 | .create_context::<<V as VideoFrame>::MemDescriptor>( |
| 259 | &config, |
| 260 | init_stream_info.coded_resolution.width, |
| 261 | init_stream_info.coded_resolution.height, |
| 262 | None, |
| 263 | true, |
| 264 | ) |
| 265 | .expect("Could not create initial VAContext!"); |
| 266 | Self { |
| 267 | display: display, |
| 268 | context: context, |
| 269 | _supports_context_reuse: supports_context_reuse, |
| 270 | stream_info: init_stream_info, |
| 271 | _phantom_data: Default::default(), |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | pub(crate) fn new_sequence<StreamData>( |
| 276 | &mut self, |
| 277 | stream_params: &StreamData, |
| 278 | ) -> StatelessBackendResult<()> |
| 279 | where |
| 280 | for<'a> &'a StreamData: VaStreamInfo, |
| 281 | { |
| 282 | self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect()); |
| 283 | self.stream_info.coded_resolution = stream_params.coded_size().clone(); |
| 284 | self.stream_info.min_num_frames = stream_params.min_num_surfaces(); |
| 285 | |
| 286 | // TODO: Handle context re-use |
| 287 | // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the RT format comes |
| 288 | // from the stream rather than being assumed 8-bit 4:2:0, which is what |
| 289 | // an HEVC Main 10 stream needs -- its surfaces are P010 and a |
| 290 | // YUV420-only config rejects them. This is upstream's own TODO, and |
| 291 | // `VaStreamInfo::rt_format` is upstream's own answer to it. |
| 292 | let rt_format = stream_params.rt_format().unwrap_or(libva::VA_RT_FORMAT_YUV420); |
| 293 | let config = self |
| 294 | .display |
| 295 | .create_config( |
| 296 | vec![libva::VAConfigAttrib { |
| 297 | type_: libva::VAConfigAttribType::VAConfigAttribRTFormat, |
| 298 | value: rt_format, |
| 299 | }], |
| 300 | stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?, |
| 301 | libva::VAEntrypoint::VAEntrypointVLD, |
| 302 | ) |
| 303 | .map_err(|_| anyhow!("Could not create VAConfig!"))?; |
| 304 | let context = self |
| 305 | .display |
| 306 | .create_context::<<V as VideoFrame>::MemDescriptor>( |
| 307 | &config, |
| 308 | self.stream_info.coded_resolution.width, |
| 309 | self.stream_info.coded_resolution.height, |
| 310 | None, |
| 311 | true, |
| 312 | ) |
| 313 | .map_err(|_| anyhow!("Could not create VAContext!"))?; |
| 314 | self.context = context; |
| 315 | |
| 316 | Ok(()) |
| 317 | } |
| 318 | |
| 319 | pub(crate) fn process_picture<Codec: StatelessCodec>( |
| 320 | &mut self, |
| 321 | picture: VaapiPicture<V>, |
| 322 | ) -> StatelessBackendResult<<Self as StatelessDecoderBackend>::Handle> |
| 323 | where |
| 324 | Self: StatelessDecoderBackendPicture<Codec>, |
| 325 | for<'a> &'a Codec::FormatInfo: VaStreamInfo, |
| 326 | { |
| 327 | Ok(Rc::new(RefCell::new(VaapiDecodedHandle::new( |
| 328 | picture, |
| 329 | self.stream_info.display_resolution.clone(), |
| 330 | )?))) |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | /// Shortcut for pictures used for the VAAPI backend. |
| 335 | pub struct VaapiPicture<V: VideoFrame> { |
| 336 | picture: Picture<PictureNew, Surface<V::MemDescriptor>>, |
| 337 | backing_frame: Arc<V>, |
| 338 | display: Option<(Arc<V>, Surface<V::MemDescriptor>)>, |
| 339 | } |
| 340 | |
| 341 | impl<V: VideoFrame> VaapiPicture<V> { |
| 342 | pub fn new(timestamp: u64, context: Rc<Context>, backing_frame: V) -> Self { |
| 343 | let display = context.display(); |
| 344 | let surface = backing_frame |
| 345 | .to_native_handle(display) |
| 346 | .expect("Failed to export video frame to vaapi picture!") |
| 347 | .into(); |
| 348 | Self { |
| 349 | backing_frame: Arc::new(backing_frame), |
| 350 | picture: Picture::new(timestamp, context, surface), |
| 351 | display: None, |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): gives this picture the |
| 356 | /// second surface an AV1 frame with `apply_grain` set is displayed from. The |
| 357 | /// driver writes the reconstructed picture into the render target as always |
| 358 | /// and the grain-synthesized one into this; a driver told to apply grain with |
| 359 | /// no such target refuses the picture outright (radeonsi answers |
| 360 | /// `vaEndPicture` with VA_STATUS_ERROR_INVALID_SURFACE). |
| 361 | pub fn set_display_frame(&mut self, display: &Rc<Display>, frame: V) { |
| 362 | let surface = frame |
| 363 | .to_native_handle(display) |
| 364 | .expect("Failed to export film grain target to vaapi picture!") |
| 365 | .into(); |
| 366 | self.display = Some((Arc::new(frame), surface)); |
| 367 | } |
| 368 | |
| 369 | /// The id [`Self::set_display_frame`] handed over, or `VA_INVALID_SURFACE` |
| 370 | /// when this picture wants no grain -- which is what the picture parameter |
| 371 | /// buffer's `current_display_picture` takes either way. |
| 372 | pub fn display_surface_id(&self) -> libva::VASurfaceID { |
| 373 | match &self.display { |
| 374 | Some((_, surface)) => surface.id(), |
| 375 | None => libva::VA_INVALID_SURFACE, |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | pub fn surface(&self) -> &Surface<V::MemDescriptor> { |
| 380 | self.picture.surface() |
| 381 | } |
| 382 | |
| 383 | pub fn add_buffer(&mut self, buffer: Buffer) { |
| 384 | self.picture.add_buffer(buffer) |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | impl<V: VideoFrame> StatelessDecoderBackend for VaapiBackend<V> { |
| 389 | type Handle = DecodedHandle<V>; |
| 390 | |
| 391 | fn stream_info(&self) -> Option<&StreamInfo> { |
| 392 | Some(&self.stream_info) |
| 393 | } |
| 394 | |
| 395 | fn reset_backend(&mut self) -> anyhow::Result<()> { |
| 396 | //TODO(bchoobineh): Implement VAAPI DRC |
| 397 | Ok(()) |
| 398 | } |
| 399 | } |