use std::ffi::{CString, c_char, c_int, c_uint, c_void};
use std::os::fd::AsRawFd as _;
use glow::HasContext as _;
use super::frame::{DRM_FORMAT_MOD_INVALID, DmaBufFrame};
type EglDisplay = *mut c_void;
type EglImage = *mut c_void;
type EglGetCurrentDisplay = unsafe extern "C" fn() -> EglDisplay;
type EglCreateImage =
unsafe extern "C" fn(EglDisplay, *mut c_void, c_uint, *mut c_void, *const c_int) -> EglImage;
type EglDestroyImage = unsafe extern "C" fn(EglDisplay, EglImage) -> c_uint;
type EglGetProcAddress = unsafe extern "C" fn(*const c_char) -> *const c_void;
type GlEglImageTargetTexture2d = unsafe extern "C" fn(c_uint, EglImage);
const EGL_NONE: c_int = 0x3038;
const EGL_WIDTH: c_int = 0x3057;
const EGL_HEIGHT: c_int = 0x3056;
const EGL_LINUX_DMA_BUF_EXT: c_uint = 0x3270;
const EGL_LINUX_DRM_FOURCC_EXT: c_int = 0x3271;
const EGL_DMA_BUF_PLANE0_FD_EXT: c_int = 0x3272;
const EGL_DMA_BUF_PLANE0_OFFSET_EXT: c_int = 0x3273;
const EGL_DMA_BUF_PLANE0_PITCH_EXT: c_int = 0x3274;
const EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT: c_int = 0x3443;
const EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT: c_int = 0x3444;
pub(super) struct GlesInterop {
device: wgpu::Device,
gl: glow::Context,
egl_get_current_display: EglGetCurrentDisplay,
egl_create_image: EglCreateImage,
egl_destroy_image: EglDestroyImage,
image_target_texture: GlEglImageTargetTexture2d,
_egl_library: libloading::Library,
_gles_library: libloading::Library,
}
impl core::fmt::Debug for GlesInterop {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter
.debug_struct("GlesInterop")
.finish_non_exhaustive()
}
}
impl GlesInterop {
pub(super) fn new(device: &wgpu::Device) -> Self {
let hal_device = unsafe {
device
.as_hal::<wgpu::hal::api::Gles>()
.expect("DMA-BUF import requires a GLES device")
};
let _context = hal_device.context().lock();
let egl_library = unsafe { libloading::Library::new("libEGL.so.1") }
.unwrap_or_else(|error| panic!("failed to load libEGL.so.1: {error}"));
let gles_library = unsafe { libloading::Library::new("libGLESv2.so.2") }
.unwrap_or_else(|error| panic!("failed to load libGLESv2.so.2: {error}"));
let get_proc = unsafe {
load_library_symbol::<EglGetProcAddress>(
&[&egl_library],
b"eglGetProcAddress\0",
"eglGetProcAddress",
)
};
let egl_get_current_display = unsafe {
load_egl_symbol::<EglGetCurrentDisplay>(
&egl_library,
&gles_library,
get_proc,
"eglGetCurrentDisplay",
)
};
let egl_create_image = unsafe {
load_egl_symbol::<EglCreateImage>(
&egl_library,
&gles_library,
get_proc,
"eglCreateImageKHR",
)
};
let egl_destroy_image = unsafe {
load_egl_symbol::<EglDestroyImage>(
&egl_library,
&gles_library,
get_proc,
"eglDestroyImageKHR",
)
};
let image_target_texture = unsafe {
load_egl_symbol::<GlEglImageTargetTexture2d>(
&egl_library,
&gles_library,
get_proc,
"glEGLImageTargetTexture2DOES",
)
};
let gl = unsafe {
glow::Context::from_loader_function(|name| {
load_egl_address(&egl_library, &gles_library, get_proc, name)
})
};
Self {
device: device.clone(),
gl,
egl_get_current_display,
egl_create_image,
egl_destroy_image,
image_target_texture,
_egl_library: egl_library,
_gles_library: gles_library,
}
}
fn hal_device(&self) -> impl core::ops::Deref<Target = wgpu::hal::gles::Device> {
unsafe {
self.device
.as_hal::<wgpu::hal::api::Gles>()
.expect("DMA-BUF import requires a GLES device")
}
}
pub(super) fn finish(&self) {
let hal_device = self.hal_device();
let _context = hal_device.context().lock();
unsafe {
self.gl.finish();
}
}
pub(super) fn copy_dma_buf(&self, frame: &DmaBufFrame, destination: &wgpu::Texture) {
let hal_device = self.hal_device();
let _context = hal_device.context().lock();
let display = unsafe { (self.egl_get_current_display)() };
assert!(
!display.is_null(),
"DMA-BUF EGL import requires a current EGL display"
);
let attributes = egl_attributes(frame);
let image = unsafe {
(self.egl_create_image)(
display,
std::ptr::null_mut(),
EGL_LINUX_DMA_BUF_EXT,
std::ptr::null_mut(),
attributes.as_ptr(),
)
};
assert!(!image.is_null(), "failed to import the DMA-BUF as EGLImage");
self.blit_egl_image(frame, destination, image);
let destroyed = unsafe { (self.egl_destroy_image)(display, image) };
assert_eq!(destroyed, 1, "failed to destroy the imported EGLImage");
}
fn blit_egl_image(&self, frame: &DmaBufFrame, destination: &wgpu::Texture, image: EglImage) {
let (visible_width, visible_height) = frame.visible_size();
let width = i32::try_from(visible_width).expect("DMA-BUF frame width exceeds EGLint");
let height = i32::try_from(visible_height).expect("DMA-BUF frame height exceeds EGLint");
let destination = unsafe {
destination
.as_hal::<wgpu::hal::api::Gles>()
.expect("DMA-BUF destination texture is not GLES")
};
let wgpu::hal::gles::TextureInner::Texture {
raw: destination_texture,
target: destination_target,
} = destination.inner
else {
panic!("the DMA-BUF destination must be a GLES texture");
};
assert_eq!(
destination_target,
glow::TEXTURE_2D,
"the DMA-BUF destination must be a two-dimensional GLES texture"
);
unsafe {
let source_texture = self.gl.create_texture().unwrap_or_else(|error| {
panic!("failed to create the GLES source texture: {error}")
});
self.gl.bind_texture(glow::TEXTURE_2D, Some(source_texture));
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MIN_FILTER,
i32::try_from(glow::NEAREST).expect("GL_NEAREST must fit GLint"),
);
self.gl.tex_parameter_i32(
glow::TEXTURE_2D,
glow::TEXTURE_MAG_FILTER,
i32::try_from(glow::NEAREST).expect("GL_NEAREST must fit GLint"),
);
(self.image_target_texture)(glow::TEXTURE_2D, image);
let read = self
.gl
.create_framebuffer()
.unwrap_or_else(|error| panic!("failed to create the GLES read FBO: {error}"));
let draw = self
.gl
.create_framebuffer()
.unwrap_or_else(|error| panic!("failed to create the GLES draw FBO: {error}"));
self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(read));
self.gl.framebuffer_texture_2d(
glow::READ_FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
glow::TEXTURE_2D,
Some(source_texture),
0,
);
assert_eq!(
self.gl.check_framebuffer_status(glow::READ_FRAMEBUFFER),
glow::FRAMEBUFFER_COMPLETE,
"the EGLImage read framebuffer is incomplete"
);
self.gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(draw));
self.gl.framebuffer_texture_2d(
glow::DRAW_FRAMEBUFFER,
glow::COLOR_ATTACHMENT0,
destination_target,
Some(destination_texture),
0,
);
assert_eq!(
self.gl.check_framebuffer_status(glow::DRAW_FRAMEBUFFER),
glow::FRAMEBUFFER_COMPLETE,
"the DMA-BUF destination framebuffer is incomplete"
);
self.gl.blit_framebuffer(
0,
0,
width,
height,
0,
0,
width,
height,
glow::COLOR_BUFFER_BIT,
glow::NEAREST,
);
self.gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None);
self.gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None);
self.gl.bind_texture(glow::TEXTURE_2D, None);
self.gl.delete_framebuffer(read);
self.gl.delete_framebuffer(draw);
self.gl.delete_texture(source_texture);
}
}
}
fn egl_attributes(frame: &DmaBufFrame) -> Vec<c_int> {
assert_eq!(
frame.planes.len(),
1,
"DMA-BUF EGL import requires one packed plane"
);
let plane = &frame.planes[0];
let fourcc = frame.format.fourcc();
let mut attributes = vec![
EGL_WIDTH,
i32::try_from(frame.width).expect("DMA-BUF frame width exceeds EGLint"),
EGL_HEIGHT,
i32::try_from(frame.height).expect("DMA-BUF frame height exceeds EGLint"),
EGL_LINUX_DRM_FOURCC_EXT,
i32::from_ne_bytes(fourcc.to_ne_bytes()),
EGL_DMA_BUF_PLANE0_FD_EXT,
plane.fd.as_raw_fd(),
EGL_DMA_BUF_PLANE0_OFFSET_EXT,
i32::try_from(plane.offset).expect("DMA-BUF plane offset exceeds EGLint"),
EGL_DMA_BUF_PLANE0_PITCH_EXT,
i32::try_from(plane.stride).expect("DMA-BUF plane stride exceeds EGLint"),
];
if frame.modifier != DRM_FORMAT_MOD_INVALID {
let modifier_low = u32::try_from(frame.modifier & u64::from(u32::MAX))
.expect("DMA-BUF modifier low bits must fit u32");
let modifier_high =
u32::try_from(frame.modifier >> 32).expect("DMA-BUF modifier high bits must fit u32");
attributes.extend([
EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT,
i32::from_ne_bytes(modifier_low.to_ne_bytes()),
EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT,
i32::from_ne_bytes(modifier_high.to_ne_bytes()),
]);
}
attributes.push(EGL_NONE);
attributes
}
unsafe fn load_library_symbol<T: Copy>(
libraries: &[&libloading::Library],
name: &[u8],
label: &str,
) -> T {
for library in libraries {
if let Ok(symbol) = unsafe { library.get::<T>(name) } {
return *symbol;
}
}
panic!("the required DMA-BUF import symbol `{label}` is unavailable")
}
unsafe fn load_egl_symbol<T: Copy>(
egl: &libloading::Library,
gles: &libloading::Library,
get_proc: EglGetProcAddress,
name: &str,
) -> T {
let name_with_nul =
CString::new(name).unwrap_or_else(|_| panic!("EGL symbol contains a NUL byte"));
for library in [egl, gles] {
if let Ok(symbol) = unsafe { library.get::<T>(name_with_nul.as_bytes_with_nul()) } {
return *symbol;
}
}
let address = unsafe { get_proc(name_with_nul.as_ptr()) };
assert!(
!address.is_null(),
"the required DMA-BUF import symbol `{name}` is unavailable"
);
assert_eq!(
size_of::<T>(),
size_of::<*const c_void>(),
"the resolved symbol pointer has an unexpected size"
);
unsafe { std::mem::transmute_copy(&address) }
}
fn load_egl_address(
egl: &libloading::Library,
gles: &libloading::Library,
get_proc: EglGetProcAddress,
name: &str,
) -> *const c_void {
let name_with_nul = CString::new(name).expect("GL symbol contains a NUL byte");
for library in [egl, gles] {
let Ok(symbol) =
(unsafe { library.get::<*const c_void>(name_with_nul.as_bytes_with_nul()) })
else {
continue;
};
if !symbol.is_null() {
return *symbol;
}
}
unsafe { get_proc(name_with_nul.as_ptr()) }
}