fev 0.2.3

High-level VA-API bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Display API access and attributes.

use core::fmt;
use std::{
    ffi::{c_char, c_int, c_void, CStr},
    mem,
    panic::catch_unwind,
    ptr::{self, NonNull},
    sync::Arc,
    vec,
};

use raw_window_handle::{HasDisplayHandle, RawDisplayHandle};

use crate::{
    check, check_log,
    dlopen::{libva, libva_drm, libva_wayland, libva_win32, libva_x11},
    image::{ImageFormat, ImageFormats},
    raw::{VADisplay, VA_PADDING_LOW},
    subpicture::{SubpictureFlags, SubpictureFormats},
    Entrypoint, Entrypoints, Error, Profile, Profiles, Result,
};

ffi_enum! {
    pub enum DisplayAttribType: c_int {
        Brightness          = 0,
        Contrast            = 1,
        Hue                 = 2,
        Saturation          = 3,
        BackgroundColor     = 4,
        DirectSurface       = 5,
        Rotation            = 6,
        OutofLoopDeblock    = 7,
        BLEBlackMode        = 8,
        BLEWhiteMode        = 9,
        BlueStretch         = 10,
        SkinColorCorrection = 11,
        CSCMatrix           = 12,
        BlendColor          = 13,
        OverlayAutoPaintColorKey = 14,
        OverlayColorKey     = 15,
        RenderMode          = 16,
        RenderDevice        = 17,
        RenderRect          = 18,
        SubDevice           = 19,
        Copy                = 20,
        PCIID               = 21,
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct DisplayAttribFlags: u32 {
        const GETTABLE = 0x0001;
        const SETTABLE = 0x0002;
    }
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct DisplayAttribute {
    pub(crate) type_: DisplayAttribType,
    pub(crate) min_value: i32,
    pub(crate) max_value: i32,
    pub(crate) value: i32,
    pub(crate) flags: DisplayAttribFlags,
    va_reserved: [u32; VA_PADDING_LOW],
}

impl DisplayAttribute {
    pub(crate) fn zeroed() -> Self {
        unsafe { mem::zeroed() }
    }

    pub fn new(ty: DisplayAttribType, value: i32) -> Self {
        let mut this: Self = unsafe { std::mem::zeroed() };
        this.type_ = ty;
        this.value = value;
        this
    }

    pub fn ty(&self) -> DisplayAttribType {
        self.type_
    }

    pub fn min_value(&self) -> i32 {
        self.min_value
    }

    pub fn max_value(&self) -> i32 {
        self.max_value
    }

    pub fn value(&self) -> i32 {
        self.value
    }

    pub fn flags(&self) -> DisplayAttribFlags {
        self.flags
    }
}

#[derive(Clone)]
pub struct DisplayAttributes {
    pub(crate) vec: Vec<DisplayAttribute>,
}

impl DisplayAttributes {
    pub fn len(&self) -> usize {
        self.vec.len()
    }

    pub fn is_empty(&self) -> bool {
        self.vec.is_empty()
    }
}

impl IntoIterator for DisplayAttributes {
    type Item = DisplayAttribute;
    type IntoIter = vec::IntoIter<DisplayAttribute>;

    fn into_iter(self) -> Self::IntoIter {
        self.vec.into_iter()
    }
}

/// List of OS APIs that may be used to obtain a libva [`Display`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DisplayApi {
    Xlib,
    Wayland,
    Drm,
    Win32,
}

/// Owns a VADisplay and destroys it on drop.
pub(crate) struct DisplayOwner {
    pub(crate) raw: VADisplay,
    pub(crate) libva: &'static libva,
    #[allow(dead_code)]
    display_handle_owner: Option<Box<dyn HasDisplayHandle>>,
}

// Safety: VA-API clearly and unambiguously documents that it is thread-safe.
unsafe impl Send for DisplayOwner {}
unsafe impl Sync for DisplayOwner {}

impl fmt::Debug for DisplayOwner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DisplayOwner")
            .field("raw", &self.raw)
            .finish()
    }
}

impl Drop for DisplayOwner {
    fn drop(&mut self) {
        unsafe {
            check_log("vaTerminate", self.libva.vaTerminate(self.raw));
        }
    }
}

/// The main entry point into the library.
///
/// [`Display`] wraps a native display handle and the corresponding libva implementation. It
/// provides methods for querying implementation capabilities and for creating libva objects. All
/// objects created from a [`Display`] will keep the underlying display handle and libva instance
/// alive even when the [`Display`] itself is dropped.
///
/// Creating a [`Display`] will initialize libva and set up its logging callbacks to forward
/// messages to the Rust `log` crate.
pub struct Display {
    pub(crate) d: Arc<DisplayOwner>,
    api: DisplayApi,
    major: u32,
    minor: u32,
}

impl Display {
    /// Opens a VA-API display from an owned display handle.
    ///
    /// This function takes ownership of `handle` to ensure that the native display handle isn't
    /// closed before the VA-API [`Display`] is dropped.
    pub fn new<H: HasDisplayHandle + 'static>(handle: H) -> Result<Self> {
        Self::new_impl(
            handle.display_handle().map_err(Error::from)?.as_raw(),
            Some(Box::new(handle)),
        )
    }

    /// Opens a VA-API display from a raw, native display handle with unmanaged lifetime.
    ///
    /// # Safety
    ///
    /// It is the user's responsibility to ensure that the native display handle `handle` remains
    /// valid until the last VA-API object created from this [`Display`] (including the [`Display`]
    /// itself) has been destroyed.
    pub unsafe fn new_unmanaged<H: HasDisplayHandle>(handle: &H) -> Result<Self> {
        Self::new_impl(handle.display_handle().map_err(Error::from)?.as_raw(), None)
    }

    fn new_impl(
        handle: RawDisplayHandle,
        display_handle_owner: Option<Box<dyn HasDisplayHandle>>,
    ) -> Result<Self> {
        unsafe {
            let raw: VADisplay;
            let api = match handle {
                RawDisplayHandle::Xlib(d) => {
                    let display = d.display.map_or(ptr::null_mut(), NonNull::as_ptr);
                    raw = libva_x11::get()?.vaGetDisplay(display.cast());
                    DisplayApi::Xlib
                }
                RawDisplayHandle::Wayland(d) => {
                    raw = libva_wayland::get()?.vaGetDisplayWl(d.display.as_ptr().cast());
                    DisplayApi::Wayland
                }
                RawDisplayHandle::Drm(d) => {
                    raw = libva_drm::get()?.vaGetDisplayDRM(d.fd);
                    DisplayApi::Drm
                }
                RawDisplayHandle::Windows(_) => {
                    raw = libva_win32::get()?.vaGetDisplayWin32(ptr::null());
                    DisplayApi::Win32
                }
                _ => {
                    return Err(Error::from(format!(
                        "unsupported display handle type: {:?}",
                        handle
                    )));
                }
            };

            let libva = libva::get()?;
            let valid = libva.vaDisplayIsValid(raw);
            if valid == 0 {
                return Err(Error::from(format!(
                    "failed to create VADisplay from window handle {:?}",
                    handle
                )));
            }

            libva.vaSetErrorCallback(raw, error_callback, ptr::null_mut());
            libva.vaSetInfoCallback(raw, info_callback, ptr::null_mut());

            let mut major = 0;
            let mut minor = 0;
            check(
                "vaInitialize",
                libva.vaInitialize(raw, &mut major, &mut minor),
            )?;

            log::info!("initialized libva {major}.{minor}");

            let this = Self {
                d: Arc::new(DisplayOwner {
                    raw,
                    libva,
                    display_handle_owner,
                }),
                api,
                major: major as _,
                minor: minor as _,
            };
            let vendor = this.query_vendor_string()?;
            log::info!("VA-API vendor: {vendor}");
            Ok(this)
        }
    }

    /// Returns the major part of the libva version.
    #[inline]
    pub fn version_major(&self) -> u32 {
        self.major
    }

    /// Returns the minor part of the libva version.
    #[inline]
    pub fn version_minor(&self) -> u32 {
        self.minor
    }

    /// Returns the [`DisplayApi`] that this [`Display`] is using.
    #[inline]
    pub fn display_api(&self) -> DisplayApi {
        self.api
    }

    /// Queries a string representing the vendor of the libva implementation.
    pub fn query_vendor_string(&self) -> Result<&str> {
        unsafe {
            let cstr = CStr::from_ptr(self.d.libva.vaQueryVendorString(self.d.raw));
            cstr.to_str().map_err(Error::from)
        }
    }

    /// Queries the supported [`Profiles`].
    pub fn query_profiles(&self) -> Result<Profiles> {
        let max = unsafe { self.d.libva.vaMaxNumProfiles(self.d.raw) as usize };
        let mut profiles = vec![Profile(0); max];
        let mut num = 0;
        unsafe {
            check(
                "vaQueryConfigProfiles",
                self.d
                    .libva
                    .vaQueryConfigProfiles(self.d.raw, profiles.as_mut_ptr(), &mut num),
            )?;
        }
        profiles.truncate(num as usize);
        Ok(Profiles { vec: profiles })
    }

    /// Queries supported [`Entrypoints`] for the given [`Profile`].
    pub fn query_entrypoints(&self, profile: Profile) -> Result<Entrypoints> {
        let max = unsafe { self.d.libva.vaMaxNumEntrypoints(self.d.raw) as usize };
        let mut entrypoints = vec![Entrypoint(0); max];
        let mut num = 0;
        unsafe {
            check(
                "vaQueryConfigEntrypoints",
                self.d.libva.vaQueryConfigEntrypoints(
                    self.d.raw,
                    profile,
                    entrypoints.as_mut_ptr(),
                    &mut num,
                ),
            )?;
        }
        entrypoints.truncate(num as usize);
        Ok(Entrypoints { vec: entrypoints })
    }

    /// Queries the supported [`ImageFormat`]s.
    pub fn query_image_formats(&self) -> Result<ImageFormats> {
        unsafe {
            let max = self.d.libva.vaMaxNumImageFormats(self.d.raw) as usize;
            let mut formats = vec![ImageFormat::zeroed(); max];
            let mut num = 0;
            check(
                "vaQueryImageFormats",
                self.d
                    .libva
                    .vaQueryImageFormats(self.d.raw, formats.as_mut_ptr(), &mut num),
            )?;
            formats.truncate(num as usize);
            Ok(ImageFormats { vec: formats })
        }
    }

    pub fn query_subpicture_format(&self) -> Result<SubpictureFormats> {
        unsafe {
            let max = self.d.libva.vaMaxNumSubpictureFormats(self.d.raw) as usize;
            let mut formats = vec![ImageFormat::zeroed(); max];
            let mut flags: Vec<SubpictureFlags> = vec![SubpictureFlags::empty(); max];
            let mut num = 0;
            check(
                "vaQuerySubpictureFormats",
                self.d.libva.vaQuerySubpictureFormats(
                    self.d.raw,
                    formats.as_mut_ptr(),
                    flags.as_mut_ptr().cast(),
                    &mut num,
                ),
            )?;
            formats.truncate(num as usize);
            flags.truncate(num as usize);

            Ok(SubpictureFormats { formats, flags })
        }
    }

    pub fn query_display_attributes(&self) -> Result<DisplayAttributes> {
        let max = unsafe { self.d.libva.vaMaxNumDisplayAttributes(self.d.raw) as usize };
        let mut attribs = vec![DisplayAttribute::zeroed(); max];
        let mut num = 0;
        unsafe {
            check(
                "vaQueryDisplayAttributes",
                self.d
                    .libva
                    .vaQueryDisplayAttributes(self.d.raw, attribs.as_mut_ptr(), &mut num),
            )?;
        }
        attribs.truncate(num as usize);
        Ok(DisplayAttributes { vec: attribs })
    }

    pub fn set_driver_name(&mut self, name: &str) -> Result<()> {
        let mut buf;
        let mut name = name.as_bytes();
        if name.last() != Some(&0) {
            buf = Vec::with_capacity(name.len() + 1);
            buf.extend_from_slice(name);
            buf.push(0);
            name = &buf;
        }
        unsafe {
            // NB: casting to a mutable pointer - libva doesn't modify the string, and other code
            // would probably break if it did
            check(
                "vaSetDriverName",
                self.d
                    .libva
                    .vaSetDriverName(self.d.raw, name.as_ptr() as *mut c_char),
            )
        }
    }

    pub fn set_attributes(&mut self, attr_list: &mut [DisplayAttribute]) -> Result<()> {
        unsafe {
            check(
                "vaSetDisplayAttributes",
                self.d.libva.vaSetDisplayAttributes(
                    self.d.raw,
                    attr_list.as_mut_ptr(),
                    attr_list.len().try_into().unwrap(),
                ),
            )?;
            Ok(())
        }
    }
}

extern "C" fn error_callback(_ctx: *mut c_void, message: *const c_char) {
    catch_unwind(|| unsafe {
        let cstr = CStr::from_ptr(message);
        match cstr.to_str() {
            Ok(s) => {
                log::error!("libva: {}", s.trim());
            }
            Err(e) => {
                log::error!("failed to decode libva error: {e}");
            }
        }
    })
    .ok();
}

extern "C" fn info_callback(_ctx: *mut c_void, message: *const c_char) {
    catch_unwind(|| unsafe {
        let cstr = CStr::from_ptr(message);
        match cstr.to_str() {
            Ok(s) => {
                log::info!("libva: {}", s.trim());
            }
            Err(e) => {
                log::error!("failed to decode libva info message: {e}");
            }
        }
    })
    .ok();
}