edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·8a26b91·Tahinli·3 months ago·348 commits
| 1 | //! [`Surface`] — GPU-side picture storage, plus the two ways of getting at its |
| 2 | //! contents: DRM PRIME export (zero-copy handoff) and image mapping (readback). |
| 3 | |
| 4 | use std::os::fd::{FromRawFd, OwnedFd}; |
| 5 | use std::sync::Arc; |
| 6 | |
| 7 | use crate::display::Display; |
| 8 | use crate::error::{Error, Result, check}; |
| 9 | use crate::sys; |
| 10 | |
| 11 | /// What kind of surface to allocate. |
| 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 13 | pub struct SurfaceSpec { |
| 14 | /// `VA_RT_FORMAT_*` for the config this surface will be used with. |
| 15 | pub rt_format: u32, |
| 16 | /// Exact pixel layout (FourCC). `None` lets the driver choose. |
| 17 | pub fourcc: Option<u32>, |
| 18 | /// Width in pixels. Must satisfy [`crate::SurfaceCaps::allows`]. |
| 19 | pub width: u32, |
| 20 | /// Height in pixels. |
| 21 | pub height: u32, |
| 22 | /// `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask; drivers use it to pick tiling. |
| 23 | pub usage_hint: u32, |
| 24 | } |
| 25 | |
| 26 | impl SurfaceSpec { |
| 27 | /// 8-bit 4:2:0 NV12, the decode output format of every codec in the family. |
| 28 | pub fn nv12(width: u32, height: u32) -> Self { |
| 29 | SurfaceSpec { |
| 30 | rt_format: sys::VA_RT_FORMAT_YUV420, |
| 31 | fourcc: Some(sys::VA_FOURCC_NV12), |
| 32 | width, |
| 33 | height, |
| 34 | usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// 10-bit 4:2:0 P010, for HEVC Main10 / VP9 Profile 2 / AV1 10-bit. |
| 39 | /// |
| 40 | /// The RT format is derived from the stream's bit depth, never hardcoded to |
| 41 | /// 8-bit: an 8-bit context on a 10-bit stream is the incumbent defect this |
| 42 | /// constructor exists to make impossible to write by accident. |
| 43 | pub fn p010(width: u32, height: u32) -> Self { |
| 44 | SurfaceSpec { |
| 45 | rt_format: sys::VA_RT_FORMAT_YUV420_10, |
| 46 | fourcc: Some(sys::VA_FOURCC_P010), |
| 47 | width, |
| 48 | height, |
| 49 | usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// Set the usage hint (`VA_SURFACE_ATTRIB_USAGE_HINT_*`). |
| 54 | pub fn with_usage_hint(mut self, hint: u32) -> Self { |
| 55 | self.usage_hint = hint; |
| 56 | self |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// A live `VASurfaceID`. |
| 61 | /// |
| 62 | /// Surfaces may only be destroyed after every context using them is gone; |
| 63 | /// [`crate::Context`] therefore holds `Arc<Surface>` for its render targets and |
| 64 | /// this `Drop` cannot run too early. |
| 65 | pub struct Surface { |
| 66 | display: Arc<Display>, |
| 67 | id: sys::VASurfaceID, |
| 68 | spec: SurfaceSpec, |
| 69 | } |
| 70 | |
| 71 | impl Surface { |
| 72 | /// Allocate a single surface. |
| 73 | pub fn create(display: &Arc<Display>, spec: &SurfaceSpec) -> Result<Arc<Surface>> { |
| 74 | let mut pool = Surface::create_pool(display, spec, 1)?; |
| 75 | Ok(pool.pop().expect("create_pool(1) returns one surface")) |
| 76 | } |
| 77 | |
| 78 | /// Allocate `count` surfaces in one driver call. |
| 79 | /// |
| 80 | /// Each returned surface owns its own id and destroys exactly that id, so a |
| 81 | /// pool can be torn down incrementally as frames are released. |
| 82 | pub fn create_pool( |
| 83 | display: &Arc<Display>, |
| 84 | spec: &SurfaceSpec, |
| 85 | count: usize, |
| 86 | ) -> Result<Vec<Arc<Surface>>> { |
| 87 | if count == 0 { |
| 88 | return Ok(Vec::new()); |
| 89 | } |
| 90 | let mut attribs: Vec<sys::VASurfaceAttrib> = Vec::with_capacity(2); |
| 91 | if let Some(fourcc) = spec.fourcc { |
| 92 | attribs.push(int_attrib(sys::VASurfaceAttribPixelFormat, fourcc as i32)); |
| 93 | } |
| 94 | if spec.usage_hint != sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC { |
| 95 | attribs.push(int_attrib( |
| 96 | sys::VASurfaceAttribUsageHint, |
| 97 | spec.usage_hint as i32, |
| 98 | )); |
| 99 | } |
| 100 | |
| 101 | let mut ids = vec![sys::VA_INVALID_SURFACE; count]; |
| 102 | // SAFETY: `ids` has room for exactly `count` surface ids and `attribs` |
| 103 | // for exactly `attribs.len()` attributes; both counts are passed |
| 104 | // alongside. libva writes only within those bounds and does not retain |
| 105 | // either pointer past the call. |
| 106 | let status = unsafe { |
| 107 | sys::vaCreateSurfaces( |
| 108 | display.handle(), |
| 109 | spec.rt_format, |
| 110 | spec.width, |
| 111 | spec.height, |
| 112 | ids.as_mut_ptr(), |
| 113 | count as u32, |
| 114 | attribs.as_mut_ptr(), |
| 115 | attribs.len() as u32, |
| 116 | ) |
| 117 | }; |
| 118 | check("vaCreateSurfaces", status)?; |
| 119 | |
| 120 | if ids.contains(&sys::VA_INVALID_SURFACE) { |
| 121 | // Destroy whatever did get created rather than leaking it. |
| 122 | let mut good: Vec<sys::VASurfaceID> = ids |
| 123 | .iter() |
| 124 | .copied() |
| 125 | .filter(|&id| id != sys::VA_INVALID_SURFACE) |
| 126 | .collect(); |
| 127 | if !good.is_empty() { |
| 128 | // SAFETY: every id in `good` was returned by the successful |
| 129 | // vaCreateSurfaces above and has not been destroyed yet. |
| 130 | unsafe { |
| 131 | sys::vaDestroySurfaces(display.handle(), good.as_mut_ptr(), good.len() as i32) |
| 132 | }; |
| 133 | } |
| 134 | return Err(Error::Protocol( |
| 135 | "vaCreateSurfaces succeeded but left VA_INVALID_SURFACE in the array".to_string(), |
| 136 | )); |
| 137 | } |
| 138 | |
| 139 | Ok(ids |
| 140 | .into_iter() |
| 141 | .map(|id| { |
| 142 | Arc::new(Surface { |
| 143 | display: Arc::clone(display), |
| 144 | id, |
| 145 | spec: *spec, |
| 146 | }) |
| 147 | }) |
| 148 | .collect()) |
| 149 | } |
| 150 | |
| 151 | /// Block until every operation targeting this surface has completed. |
| 152 | pub fn sync(&self) -> Result<()> { |
| 153 | // SAFETY: `self.id` is live for the lifetime of `self` on |
| 154 | // `self.display`. vaSyncSurface only blocks; it mutates no Rust state. |
| 155 | let status = unsafe { sys::vaSyncSurface(self.display.handle(), self.id) }; |
| 156 | check("vaSyncSurface", status) |
| 157 | } |
| 158 | |
| 159 | /// Export as DRM PRIME (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`). |
| 160 | /// |
| 161 | /// `flags` is a combination of `VA_EXPORT_SURFACE_*`. This performs no |
| 162 | /// synchronisation: call [`Surface::sync`] first if the contents will be |
| 163 | /// read. |
| 164 | pub fn export_prime(&self, flags: u32) -> Result<PrimeSurface> { |
| 165 | let mut desc = sys::VADRMPRIMESurfaceDescriptor::default(); |
| 166 | // SAFETY: `desc` is a valid, fully initialized (zeroed) descriptor of |
| 167 | // exactly the type `VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2` selects |
| 168 | // (va_drmcommon.h:96-99); passing any other mem_type with this pointer |
| 169 | // would be the unsound case, which is why mem_type is not a parameter. |
| 170 | let status = unsafe { |
| 171 | sys::vaExportSurfaceHandle( |
| 172 | self.display.handle(), |
| 173 | self.id, |
| 174 | sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, |
| 175 | flags, |
| 176 | (&raw mut desc).cast(), |
| 177 | ) |
| 178 | }; |
| 179 | check("vaExportSurfaceHandle", status)?; |
| 180 | PrimeSurface::from_raw(desc) |
| 181 | } |
| 182 | |
| 183 | /// A directly mapped view of the surface's own memory (`vaDeriveImage`). |
| 184 | /// |
| 185 | /// Falls back is the caller's business: drivers may refuse to derive (tiled |
| 186 | /// or compressed layouts), reporting `VA_STATUS_ERROR_OPERATION_FAILED`. |
| 187 | pub fn derive_image(self: &Arc<Self>) -> Result<Image> { |
| 188 | let mut image = sys::VAImage::default(); |
| 189 | // SAFETY: valid display and surface id; `image` is a valid |
| 190 | // out-parameter that libva fully overwrites on success. |
| 191 | let status = unsafe { sys::vaDeriveImage(self.display.handle(), self.id, &raw mut image) }; |
| 192 | check("vaDeriveImage", status)?; |
| 193 | Ok(Image { |
| 194 | display: Arc::clone(&self.display), |
| 195 | _surface: Some(Arc::clone(self)), |
| 196 | raw: image, |
| 197 | }) |
| 198 | } |
| 199 | |
| 200 | /// Copy the surface into an [`Image`] created with [`Image::create`]. |
| 201 | /// |
| 202 | /// The readback path for drivers that refuse [`Surface::derive_image`]. |
| 203 | /// The image must be at least as large as the requested region. |
| 204 | pub fn read_into( |
| 205 | &self, |
| 206 | image: &mut Image, |
| 207 | x: i32, |
| 208 | y: i32, |
| 209 | width: u32, |
| 210 | height: u32, |
| 211 | ) -> Result<()> { |
| 212 | let (img_w, img_h) = image.size(); |
| 213 | if width > img_w || height > img_h { |
| 214 | return Err(Error::Protocol(format!( |
| 215 | "vaGetImage region {width}x{height} exceeds image {img_w}x{img_h}" |
| 216 | ))); |
| 217 | } |
| 218 | // SAFETY: valid display and surface id; `image.raw.image_id` is a live |
| 219 | // image on the same display. The region is bounded above by the image |
| 220 | // size, which is what vaGetImage requires (va.h:4827). |
| 221 | let status = unsafe { |
| 222 | sys::vaGetImage( |
| 223 | self.display.handle(), |
| 224 | self.id, |
| 225 | x, |
| 226 | y, |
| 227 | width, |
| 228 | height, |
| 229 | image.raw.image_id, |
| 230 | ) |
| 231 | }; |
| 232 | check("vaGetImage", status) |
| 233 | } |
| 234 | |
| 235 | /// Copy an [`Image`] into the surface (`vaPutImage`). |
| 236 | /// |
| 237 | /// The upload path an encoder needs: fill a standalone image with source |
| 238 | /// pixels, then hand it to the driver, which detiles and converts on the |
| 239 | /// way in. The region is `(0, 0, width, height)` on both sides — scaling |
| 240 | /// during upload is a video-processing job, not an encoder's. |
| 241 | pub fn write_from(&self, image: &Image, width: u32, height: u32) -> Result<()> { |
| 242 | let (img_w, img_h) = image.size(); |
| 243 | if width > img_w || height > img_h { |
| 244 | return Err(Error::Protocol(format!( |
| 245 | "vaPutImage region {width}x{height} exceeds image {img_w}x{img_h}" |
| 246 | ))); |
| 247 | } |
| 248 | // SAFETY: valid display and surface id; `image.raw.image_id` is a live |
| 249 | // image on the same display, and the region is bounded above by both |
| 250 | // the image and the surface size (va.h:4860). |
| 251 | let status = unsafe { |
| 252 | sys::vaPutImage( |
| 253 | self.display.handle(), |
| 254 | self.id, |
| 255 | image.raw.image_id, |
| 256 | 0, |
| 257 | 0, |
| 258 | width, |
| 259 | height, |
| 260 | 0, |
| 261 | 0, |
| 262 | width, |
| 263 | height, |
| 264 | ) |
| 265 | }; |
| 266 | check("vaPutImage", status) |
| 267 | } |
| 268 | |
| 269 | /// The surface id, for FFI-level callers (`ec-hw` picture parameters). |
| 270 | pub fn id(&self) -> sys::VASurfaceID { |
| 271 | self.id |
| 272 | } |
| 273 | |
| 274 | /// The spec this surface was allocated with. |
| 275 | pub fn spec(&self) -> &SurfaceSpec { |
| 276 | &self.spec |
| 277 | } |
| 278 | |
| 279 | /// Allocated size in pixels. |
| 280 | pub fn size(&self) -> (u32, u32) { |
| 281 | (self.spec.width, self.spec.height) |
| 282 | } |
| 283 | |
| 284 | /// The display this surface belongs to. |
| 285 | pub fn display(&self) -> &Arc<Display> { |
| 286 | &self.display |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | fn int_attrib(type_: sys::VASurfaceAttribType, value: i32) -> sys::VASurfaceAttrib { |
| 291 | sys::VASurfaceAttrib { |
| 292 | type_, |
| 293 | flags: sys::VA_SURFACE_ATTRIB_SETTABLE, |
| 294 | value: sys::VAGenericValue { |
| 295 | type_: sys::VAGenericValueTypeInteger, |
| 296 | value: sys::VAGenericValueUnion { i: value }, |
| 297 | }, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | impl std::fmt::Debug for Surface { |
| 302 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 303 | f.debug_struct("Surface") |
| 304 | .field("id", &self.id) |
| 305 | .field("size", &(self.spec.width, self.spec.height)) |
| 306 | .finish() |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | impl Drop for Surface { |
| 311 | fn drop(&mut self) { |
| 312 | let mut id = self.id; |
| 313 | // SAFETY: `id` is live and belongs to `self.display`. Any context that |
| 314 | // used it held an `Arc<Surface>`, so it was destroyed first; any |
| 315 | // derived Image also held one. |
| 316 | unsafe { sys::vaDestroySurfaces(self.display.handle(), &raw mut id, 1) }; |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /// One DRM object (buffer object) of an exported surface. |
| 321 | #[derive(Debug)] |
| 322 | pub struct PrimeObject { |
| 323 | /// The PRIME file descriptor, owned and closed on drop. |
| 324 | pub fd: OwnedFd, |
| 325 | /// Total size of the object in bytes. |
| 326 | pub size: u32, |
| 327 | /// DRM format modifier (tiling/compression layout). |
| 328 | pub modifier: u64, |
| 329 | } |
| 330 | |
| 331 | /// One layer (plane group) of an exported surface. |
| 332 | #[derive(Debug, Clone)] |
| 333 | pub struct PrimeLayer { |
| 334 | /// `DRM_FORMAT_*` FourCC of this layer. |
| 335 | pub drm_format: u32, |
| 336 | /// Per-plane `(object_index, offset, pitch)`. |
| 337 | pub planes: Vec<(u32, u32, u32)>, |
| 338 | } |
| 339 | |
| 340 | /// A surface exported as DRM PRIME file descriptors. |
| 341 | /// |
| 342 | /// Owns the descriptors: dropping this closes them. libva hands over ownership |
| 343 | /// on export (`va.h:4155`), so anything less would leak one fd per frame. |
| 344 | #[derive(Debug)] |
| 345 | pub struct PrimeSurface { |
| 346 | /// Surface FourCC (`VA_FOURCC_*`). |
| 347 | pub fourcc: u32, |
| 348 | /// Width in pixels. |
| 349 | pub width: u32, |
| 350 | /// Height in pixels. |
| 351 | pub height: u32, |
| 352 | /// Backing DRM objects. |
| 353 | pub objects: Vec<PrimeObject>, |
| 354 | /// Layers referencing those objects. |
| 355 | pub layers: Vec<PrimeLayer>, |
| 356 | } |
| 357 | |
| 358 | impl PrimeSurface { |
| 359 | /// Take ownership of the fds in a filled descriptor. |
| 360 | fn from_raw(desc: sys::VADRMPRIMESurfaceDescriptor) -> Result<PrimeSurface> { |
| 361 | // The array is 4 elements wide; a driver reporting more would mean our |
| 362 | // transcription and the runtime disagree about the struct, so refuse |
| 363 | // rather than read past the end. |
| 364 | if desc.num_objects as usize > desc.objects.len() |
| 365 | || desc.num_layers as usize > desc.layers.len() |
| 366 | { |
| 367 | return Err(Error::Protocol(format!( |
| 368 | "vaExportSurfaceHandle reported {} objects / {} layers, max 4 each", |
| 369 | desc.num_objects, desc.num_layers |
| 370 | ))); |
| 371 | } |
| 372 | |
| 373 | let mut objects = Vec::with_capacity(desc.num_objects as usize); |
| 374 | for obj in &desc.objects[..desc.num_objects as usize] { |
| 375 | if obj.fd < 0 { |
| 376 | return Err(Error::Protocol(format!( |
| 377 | "vaExportSurfaceHandle returned fd {} for an exported object", |
| 378 | obj.fd |
| 379 | ))); |
| 380 | } |
| 381 | objects.push(PrimeObject { |
| 382 | // SAFETY: libva transfers ownership of every exported fd to the |
| 383 | // caller (va.h:4155). Each fd appears exactly once in the |
| 384 | // descriptor, so it is wrapped exactly once here and closed |
| 385 | // exactly once when this `PrimeSurface` drops. |
| 386 | fd: unsafe { OwnedFd::from_raw_fd(obj.fd) }, |
| 387 | size: obj.size, |
| 388 | modifier: obj.drm_format_modifier, |
| 389 | }); |
| 390 | } |
| 391 | |
| 392 | let mut layers = Vec::with_capacity(desc.num_layers as usize); |
| 393 | for layer in &desc.layers[..desc.num_layers as usize] { |
| 394 | if layer.num_planes as usize > layer.object_index.len() { |
| 395 | return Err(Error::Protocol(format!( |
| 396 | "vaExportSurfaceHandle reported {} planes in a layer, max 4", |
| 397 | layer.num_planes |
| 398 | ))); |
| 399 | } |
| 400 | layers.push(PrimeLayer { |
| 401 | drm_format: layer.drm_format, |
| 402 | planes: (0..layer.num_planes as usize) |
| 403 | .map(|i| (layer.object_index[i], layer.offset[i], layer.pitch[i])) |
| 404 | .collect(), |
| 405 | }); |
| 406 | } |
| 407 | |
| 408 | Ok(PrimeSurface { |
| 409 | fourcc: desc.fourcc, |
| 410 | width: desc.width, |
| 411 | height: desc.height, |
| 412 | objects, |
| 413 | layers, |
| 414 | }) |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | /// A `VAImage` bound to a surface (derived) or standalone (created). |
| 419 | pub struct Image { |
| 420 | display: Arc<Display>, |
| 421 | /// Kept alive because a derived image aliases the surface's memory. |
| 422 | _surface: Option<Arc<Surface>>, |
| 423 | raw: sys::VAImage, |
| 424 | } |
| 425 | |
| 426 | impl Image { |
| 427 | /// Allocate a standalone image to read a surface back into |
| 428 | /// ([`Surface::read_into`]). |
| 429 | /// |
| 430 | /// `fourcc` must be one of [`crate::CapReport::image_formats`]; the other |
| 431 | /// [`sys::VAImageFormat`] fields are only meaningful for RGB layouts and |
| 432 | /// are left zero, as libva's own examples do for planar YUV. |
| 433 | pub fn create(display: &Arc<Display>, fourcc: u32, width: u32, height: u32) -> Result<Image> { |
| 434 | let mut format = sys::VAImageFormat { |
| 435 | fourcc, |
| 436 | byte_order: 1, // VA_LSB_FIRST |
| 437 | bits_per_pixel: match fourcc { |
| 438 | sys::VA_FOURCC_NV12 | sys::VA_FOURCC_I420 | sys::VA_FOURCC_YV12 => 12, |
| 439 | sys::VA_FOURCC_P010 => 24, |
| 440 | _ => 0, |
| 441 | }, |
| 442 | ..sys::VAImageFormat::default() |
| 443 | }; |
| 444 | let mut image = sys::VAImage::default(); |
| 445 | // SAFETY: `format` and `image` are valid, initialized in/out parameters |
| 446 | // that outlive the call; libva copies the format and fully overwrites |
| 447 | // `image` on success. |
| 448 | let status = unsafe { |
| 449 | sys::vaCreateImage( |
| 450 | display.handle(), |
| 451 | &raw mut format, |
| 452 | width as i32, |
| 453 | height as i32, |
| 454 | &raw mut image, |
| 455 | ) |
| 456 | }; |
| 457 | check("vaCreateImage", status)?; |
| 458 | Ok(Image { |
| 459 | display: Arc::clone(display), |
| 460 | _surface: None, |
| 461 | raw: image, |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | /// Pixel format FourCC. |
| 466 | pub fn fourcc(&self) -> u32 { |
| 467 | self.raw.format.fourcc |
| 468 | } |
| 469 | |
| 470 | /// `(width, height)` of the image, which may exceed the requested size. |
| 471 | pub fn size(&self) -> (u32, u32) { |
| 472 | (self.raw.width as u32, self.raw.height as u32) |
| 473 | } |
| 474 | |
| 475 | /// Number of planes (at most 3). |
| 476 | pub fn num_planes(&self) -> u32 { |
| 477 | self.raw.num_planes.min(3) |
| 478 | } |
| 479 | |
| 480 | /// Row pitch of plane `i` in bytes. |
| 481 | pub fn pitch(&self, plane: usize) -> Option<u32> { |
| 482 | self.raw.pitches.get(plane).copied() |
| 483 | } |
| 484 | |
| 485 | /// Map the image's buffer into this process. |
| 486 | /// |
| 487 | /// The returned guard unmaps on drop. That is not politeness: an unmatched |
| 488 | /// `vaMapBuffer` leaks the mapping for the lifetime of the display, which |
| 489 | /// is how the incumbent stack lost ~3MB per frame. |
| 490 | pub fn map(&mut self) -> Result<MappedImage<'_>> { |
| 491 | let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); |
| 492 | // SAFETY: `self.raw.buf` is the image buffer libva created and still |
| 493 | // owns; `ptr` is a valid out-parameter. On success libva guarantees the |
| 494 | // mapping stays valid until vaUnmapBuffer, which `MappedImage::drop` |
| 495 | // calls exactly once. |
| 496 | let status = unsafe { sys::vaMapBuffer(self.display.handle(), self.raw.buf, &raw mut ptr) }; |
| 497 | check("vaMapBuffer", status)?; |
| 498 | if ptr.is_null() { |
| 499 | // SAFETY: the map call reported success, so the buffer is mapped |
| 500 | // and must be unmapped even though the pointer is unusable. |
| 501 | unsafe { sys::vaUnmapBuffer(self.display.handle(), self.raw.buf) }; |
| 502 | return Err(Error::Protocol( |
| 503 | "vaMapBuffer succeeded but returned NULL".to_string(), |
| 504 | )); |
| 505 | } |
| 506 | Ok(MappedImage { |
| 507 | image: self, |
| 508 | base: ptr.cast::<u8>(), |
| 509 | }) |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | impl std::fmt::Debug for Image { |
| 514 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 515 | f.debug_struct("Image") |
| 516 | .field("fourcc", &crate::caps::fourcc_str(self.raw.format.fourcc)) |
| 517 | .field("size", &(self.raw.width, self.raw.height)) |
| 518 | .field("num_planes", &self.raw.num_planes) |
| 519 | .field("data_size", &self.raw.data_size) |
| 520 | .finish() |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | impl Drop for Image { |
| 525 | fn drop(&mut self) { |
| 526 | // SAFETY: `image_id` came from vaDeriveImage/vaCreateImage on |
| 527 | // `self.display` and is destroyed once. Any mapping was released |
| 528 | // first: `map` borrows `self` mutably, so no `MappedImage` can outlive |
| 529 | // this. The surface (if any) is released after, as libva requires. |
| 530 | unsafe { sys::vaDestroyImage(self.display.handle(), self.raw.image_id) }; |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | /// A mapped [`Image`]. Unmaps on drop. |
| 535 | pub struct MappedImage<'a> { |
| 536 | image: &'a mut Image, |
| 537 | base: *mut u8, |
| 538 | } |
| 539 | |
| 540 | impl MappedImage<'_> { |
| 541 | /// Byte range of plane `i` within the mapped buffer, as `(offset, len)`. |
| 542 | /// |
| 543 | /// The length runs to the next plane's offset, or to `data_size` for the |
| 544 | /// last plane — libva does not report per-plane sizes. |
| 545 | fn plane_range(&self, plane: usize) -> Option<(usize, usize)> { |
| 546 | let n = self.image.num_planes() as usize; |
| 547 | if plane >= n { |
| 548 | return None; |
| 549 | } |
| 550 | let raw = &self.image.raw; |
| 551 | let offset = raw.offsets[plane] as usize; |
| 552 | let end = raw |
| 553 | .offsets |
| 554 | .get(plane + 1) |
| 555 | .copied() |
| 556 | .filter(|_| plane + 1 < n) |
| 557 | .unwrap_or(raw.data_size) as usize; |
| 558 | // A driver reporting decreasing or out-of-range offsets would otherwise |
| 559 | // produce a slice past the mapping. |
| 560 | if end < offset || end > raw.data_size as usize { |
| 561 | return None; |
| 562 | } |
| 563 | Some((offset, end - offset)) |
| 564 | } |
| 565 | |
| 566 | /// Read-only view of plane `plane`. |
| 567 | pub fn plane(&self, plane: usize) -> Option<&[u8]> { |
| 568 | let (offset, len) = self.plane_range(plane)?; |
| 569 | // SAFETY: `base` points at a mapping of `data_size` bytes that libva |
| 570 | // keeps valid until vaUnmapBuffer (called only in `drop`). `plane_range` |
| 571 | // guarantees `offset + len <= data_size`, so the slice stays inside the |
| 572 | // mapping. The borrow is tied to `&self`, so it cannot outlive it. |
| 573 | Some(unsafe { std::slice::from_raw_parts(self.base.add(offset), len) }) |
| 574 | } |
| 575 | |
| 576 | /// Mutable view of plane `plane`, for upload paths. |
| 577 | pub fn plane_mut(&mut self, plane: usize) -> Option<&mut [u8]> { |
| 578 | let (offset, len) = self.plane_range(plane)?; |
| 579 | // SAFETY: as `plane`, plus: `&mut self` guarantees no other slice into |
| 580 | // the mapping is alive, so this is the only reference to those bytes. |
| 581 | Some(unsafe { std::slice::from_raw_parts_mut(self.base.add(offset), len) }) |
| 582 | } |
| 583 | |
| 584 | /// Row pitch of plane `plane` in bytes. |
| 585 | pub fn pitch(&self, plane: usize) -> Option<u32> { |
| 586 | self.image.pitch(plane) |
| 587 | } |
| 588 | |
| 589 | /// The image being mapped. |
| 590 | pub fn image(&self) -> &Image { |
| 591 | self.image |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | impl Drop for MappedImage<'_> { |
| 596 | fn drop(&mut self) { |
| 597 | // SAFETY: the buffer was mapped in `Image::map` and is unmapped exactly |
| 598 | // once, here; `self.image` is still alive because this guard borrows it. |
| 599 | unsafe { sys::vaUnmapBuffer(self.image.display.handle(), self.image.raw.buf) }; |
| 600 | } |
| 601 | } |