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
use {AsRaw, BufferObject, BufferObjectFlags, Format, Modifier, Ptr, Surface};

use libc::c_void;

use std::error;
use std::ffi::CStr;
use std::fmt;
use std::io::{Error as IoError, Result as IoResult};
use std::ops::{Deref, DerefMut};
use std::os::unix::io::{AsRawFd, RawFd};

#[cfg(feature = "import-wayland")]
use wayland_server::protocol::wl_buffer::WlBuffer;

#[cfg(feature = "import-egl")]
/// An EGLImage handle
pub type EGLImage = *mut c_void;

#[cfg(feature = "drm-support")]
use drm::control::Device as DrmControlDevice;
#[cfg(feature = "drm-support")]
use drm::Device as DrmDevice;

/// Type wrapping a foreign file destructor
#[derive(Debug)]
pub struct FdWrapper(RawFd);

impl AsRawFd for FdWrapper {
    fn as_raw_fd(&self) -> RawFd {
        self.0
    }
}

/// An open GBM device
pub struct Device<T: AsRawFd + 'static> {
    fd: T,
    ffi: Ptr<::ffi::gbm_device>,
}

impl<T: AsRawFd + 'static> fmt::Debug for Device<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Device")
            .field("ptr", &format_args!("{:p}", &self.ffi))
            .finish()
    }
}

impl<T: AsRawFd + Clone + 'static> Clone for Device<T> {
    fn clone(&self) -> Device<T> {
        Device {
            fd: self.fd.clone(),
            ffi: self.ffi.clone(),
        }
    }
}

unsafe impl Send for Ptr<::ffi::gbm_device> {}

impl<T: AsRawFd + 'static> AsRawFd for Device<T> {
    fn as_raw_fd(&self) -> RawFd {
        unsafe { ::ffi::gbm_device_get_fd(*self.ffi) }
    }
}

impl<T: AsRawFd + 'static> AsRaw<::ffi::gbm_device> for Device<T> {
    fn as_raw(&self) -> *const ::ffi::gbm_device {
        *self.ffi
    }
}

impl<T: AsRawFd + 'static> Deref for Device<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.fd
    }
}

impl<T: AsRawFd + 'static> DerefMut for Device<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.fd
    }
}

impl Device<FdWrapper> {
    /// Open a GBM device from a given unix file descriptor.
    ///
    /// The file descriptor passed in is used by the backend to communicate with
    /// platform for allocating the memory.  For allocations using DRI this would be
    /// the file descriptor returned when opening a device such as `/dev/dri/card0`.
    ///
    /// # Safety
    ///
    /// The lifetime of the resulting device depends on the ownership of the file descriptor.
    /// Closing the file descriptor before dropping the Device will lead to undefined behavior.
    ///
    pub unsafe fn new_from_fd(fd: RawFd) -> IoResult<Device<FdWrapper>> {
        let ptr = ::ffi::gbm_create_device(fd);
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(Device {
                fd: FdWrapper(fd),
                ffi: Ptr::new(ptr, |ptr| ::ffi::gbm_device_destroy(ptr)),
            })
        }
    }
}

impl<T: AsRawFd + 'static> Device<T> {
    /// Open a GBM device from a given open DRM device.
    ///
    /// The underlying file descriptor passed in is used by the backend to communicate with
    /// platform for allocating the memory.  For allocations using DRI this would be
    /// the file descriptor returned when opening a device such as `/dev/dri/card0`.
    pub fn new(fd: T) -> IoResult<Device<T>> {
        let ptr = unsafe { ::ffi::gbm_create_device(fd.as_raw_fd()) };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(Device {
                fd,
                ffi: Ptr::<::ffi::gbm_device>::new(ptr, |ptr| unsafe {
                    ::ffi::gbm_device_destroy(ptr)
                }),
            })
        }
    }

    /// Get the backend name
    pub fn backend_name(&self) -> &str {
        unsafe {
            CStr::from_ptr(::ffi::gbm_device_get_backend_name(*self.ffi))
                .to_str()
                .expect("GBM passed invalid utf8 string")
        }
    }

    /// Test if a format is supported for a given set of usage flags
    pub fn is_format_supported(&self, format: Format, usage: BufferObjectFlags) -> bool {
        unsafe {
            ::ffi::gbm_device_is_format_supported(*self.ffi, format as u32, usage.bits()) != 0
        }
    }

    /// Allocate a new surface object
    pub fn create_surface<U: 'static>(
        &self,
        width: u32,
        height: u32,
        format: Format,
        usage: BufferObjectFlags,
    ) -> IoResult<Surface<U>> {
        let ptr = unsafe {
            ::ffi::gbm_surface_create(*self.ffi, width, height, format as u32, usage.bits())
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { Surface::new(ptr, self.ffi.downgrade()) })
        }
    }

    /// Allocate a new surface object with explicit modifiers
    pub fn create_surface_with_modifiers<U: 'static>(
        &self,
        width: u32,
        height: u32,
        format: Format,
        modifiers: impl Iterator<Item = Modifier>,
    ) -> IoResult<Surface<U>> {
        let mods = modifiers
            .take(::ffi::GBM_MAX_PLANES as usize)
            .map(|m| m.into())
            .collect::<Vec<u64>>();
        let ptr = unsafe {
            ::ffi::gbm_surface_create_with_modifiers(
                *self.ffi,
                width,
                height,
                format as u32,
                mods.as_ptr(),
                mods.len() as u32,
            )
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { Surface::new(ptr, self.ffi.downgrade()) })
        }
    }

    ///  Allocate a buffer object for the given dimensions
    pub fn create_buffer_object<U: 'static>(
        &self,
        width: u32,
        height: u32,
        format: Format,
        usage: BufferObjectFlags,
    ) -> IoResult<BufferObject<U>> {
        let ptr =
            unsafe { ::ffi::gbm_bo_create(*self.ffi, width, height, format as u32, usage.bits()) };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { BufferObject::new(ptr, self.ffi.downgrade()) })
        }
    }

    ///  Allocate a buffer object for the given dimensions with explicit modifiers
    pub fn create_buffer_object_with_modifiers<U: 'static>(
        &self,
        width: u32,
        height: u32,
        format: Format,
        modifiers: impl Iterator<Item = Modifier>,
    ) -> IoResult<BufferObject<U>> {
        let mods = modifiers
            .take(::ffi::GBM_MAX_PLANES as usize)
            .map(|m| m.into())
            .collect::<Vec<u64>>();
        let ptr = unsafe {
            ::ffi::gbm_bo_create_with_modifiers(
                *self.ffi,
                width,
                height,
                format as u32,
                mods.as_ptr(),
                mods.len() as u32,
            )
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { BufferObject::new(ptr, self.ffi.downgrade()) })
        }
    }

    /// Create a GBM buffer object from a wayland buffer
    ///
    /// This function imports a foreign [`WlBuffer`] object and creates a new GBM
    /// buffer object for it.
    /// This enables using the foreign object with a display API such as KMS.
    ///
    /// The GBM bo shares the underlying pixels but its life-time is
    /// independent of the foreign object.
    #[cfg(feature = "import-wayland")]
    pub fn import_buffer_object_from_wayland<U: 'static>(
        &self,
        buffer: &WlBuffer,
        usage: BufferObjectFlags,
    ) -> IoResult<BufferObject<U>> {
        let ptr = unsafe {
            ::ffi::gbm_bo_import(
                *self.ffi,
                ::ffi::GBM_BO_IMPORT_WL_BUFFER as u32,
                buffer.as_ref().c_ptr() as *mut _,
                usage.bits(),
            )
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { BufferObject::new(ptr, self.ffi.downgrade()) })
        }
    }

    /// Create a GBM buffer object from an egl buffer
    ///
    /// This function imports a foreign [`EGLImage`] object and creates a new GBM
    /// buffer object for it.
    /// This enables using the foreign object with a display API such as KMS.
    ///
    /// The GBM bo shares the underlying pixels but its life-time is
    /// independent of the foreign object.
    ///
    /// # Safety
    ///
    /// The given [`EGLImage`] is a raw pointer.  Passing null or an invalid [`EGLImage`] will
    /// cause undefined behavior.
    #[cfg(feature = "import-egl")]
    pub unsafe fn import_buffer_object_from_egl<U: 'static>(
        &self,
        buffer: EGLImage,
        usage: BufferObjectFlags,
    ) -> IoResult<BufferObject<U>> {
        let ptr = ::ffi::gbm_bo_import(
            *self.ffi,
            ::ffi::GBM_BO_IMPORT_EGL_IMAGE as u32,
            buffer,
            usage.bits(),
        );
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(BufferObject::new(ptr, self.ffi.downgrade()))
        }
    }

    /// Create a GBM buffer object from a dma buffer
    ///
    /// This function imports a foreign dma buffer from an open file descriptor
    /// and creates a new GBM buffer object for it.
    /// This enables using the foreign object with a display API such as KMS.
    ///
    /// The GBM bo shares the underlying pixels but its life-time is
    /// independent of the foreign object.
    pub fn import_buffer_object_from_dma_buf<U: 'static>(
        &self,
        buffer: RawFd,
        width: u32,
        height: u32,
        stride: u32,
        format: Format,
        usage: BufferObjectFlags,
    ) -> IoResult<BufferObject<U>> {
        let mut fd_data = ::ffi::gbm_import_fd_data {
            fd: buffer,
            width,
            height,
            stride,
            format: format as u32,
        };

        let ptr = unsafe {
            ::ffi::gbm_bo_import(
                *self.ffi,
                ::ffi::GBM_BO_IMPORT_FD as u32,
                &mut fd_data as *mut ::ffi::gbm_import_fd_data as *mut _,
                usage.bits(),
            )
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { BufferObject::new(ptr, self.ffi.downgrade()) })
        }
    }

    /// Create a GBM buffer object from a dma buffer with explicit modifiers
    ///
    /// This function imports a foreign dma buffer from an open file descriptor
    /// and creates a new GBM buffer object for it.
    /// This enables using the foreign object with a display API such as KMS.
    ///
    /// The GBM bo shares the underlying pixels but its life-time is
    /// independent of the foreign object.
    #[allow(clippy::too_many_arguments)]
    pub fn import_buffer_object_from_dma_buf_with_modifiers<U: 'static>(
        &self,
        len: u32,
        buffers: [RawFd; 4],
        width: u32,
        height: u32,
        format: Format,
        usage: BufferObjectFlags,
        strides: [i32; 4],
        offsets: [i32; 4],
        modifier: Modifier,
    ) -> IoResult<BufferObject<U>> {
        let mut fd_data = ::ffi::gbm_import_fd_modifier_data {
            fds: buffers,
            width,
            height,
            format: format as u32,
            strides,
            offsets,
            modifier: modifier.into(),
            num_fds: len,
        };

        let ptr = unsafe {
            ::ffi::gbm_bo_import(
                *self.ffi,
                ::ffi::GBM_BO_IMPORT_FD_MODIFIER as u32,
                &mut fd_data as *mut ::ffi::gbm_import_fd_modifier_data as *mut _,
                usage.bits(),
            )
        };
        if ptr.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(unsafe { BufferObject::new(ptr, self.ffi.downgrade()) })
        }
    }
}

#[cfg(feature = "drm-support")]
impl<T: DrmDevice + AsRawFd + 'static> DrmDevice for Device<T> {}

#[cfg(feature = "drm-support")]
impl<T: DrmControlDevice + AsRawFd + 'static> DrmControlDevice for Device<T> {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Thrown when the underlying GBM device was already destroyed
pub struct DeviceDestroyedError;

impl fmt::Display for DeviceDestroyedError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "The underlying GBM device was already destroyed")
    }
}

impl error::Error for DeviceDestroyedError {
    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}