Merge pull request #93 from Smithay/anvil_fix_buffer_load

anvil: fix shm buffer loading
This commit is contained in:
Victor Berger 2018-05-19 21:45:09 +02:00 committed by GitHub
commit ad038b4a07
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 337 additions and 212 deletions

View File

@ -1,20 +1,25 @@
use glium; use glium;
use glium::{Frame, GlObject, Surface};
use glium::index::PrimitiveType; use glium::index::PrimitiveType;
use glium::texture::{MipmapsOption, Texture2d, UncompressedFloatFormat}; use glium::texture::{MipmapsOption, Texture2d, UncompressedFloatFormat};
use glium::{Frame, GlObject, Surface};
use smithay::backend::graphics::egl::EGLGraphicsBackend; use smithay::backend::graphics::egl::EGLGraphicsBackend;
use smithay::backend::graphics::egl::error::Result as EGLResult; use smithay::backend::graphics::egl::error::Result as EGLResult;
use smithay::backend::graphics::egl::wayland::{EGLDisplay, EGLImages, EGLWaylandExtensions, Format}; use smithay::backend::graphics::egl::wayland::{BufferAccessError, EGLDisplay, EGLImages,
EGLWaylandExtensions, Format};
use smithay::backend::graphics::glium::GliumGraphicsBackend; use smithay::backend::graphics::glium::GliumGraphicsBackend;
use smithay::wayland::compositor::{SubsurfaceRole, TraversalAction};
use smithay::wayland::compositor::roles::Role; use smithay::wayland::compositor::roles::Role;
use smithay::wayland_server::Display; use smithay::wayland::compositor::{SubsurfaceRole, TraversalAction};
use smithay::wayland::shm::with_buffer_contents as shm_buffer_contents;
use smithay::wayland_server::protocol::wl_buffer;
use smithay::wayland_server::{Display, Resource};
use std::cell::Ref; use std::cell::{Ref, RefCell};
use std::rc::Rc;
use slog::Logger; use slog::Logger;
use shell::{Buffer, MyCompositorToken, MyWindowMap}; use shaders;
use shell::{MyCompositorToken, MyWindowMap};
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
struct Vertex { struct Vertex {
@ -28,7 +33,9 @@ pub struct GliumDrawer<F: EGLGraphicsBackend + 'static> {
display: GliumGraphicsBackend<F>, display: GliumGraphicsBackend<F>,
vertex_buffer: glium::VertexBuffer<Vertex>, vertex_buffer: glium::VertexBuffer<Vertex>,
index_buffer: glium::IndexBuffer<u16>, index_buffer: glium::IndexBuffer<u16>,
program: glium::Program, programs: [glium::Program; shaders::FRAGMENT_COUNT],
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
log: Logger,
} }
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> { impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
@ -37,8 +44,8 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
} }
} }
impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> From<T> for GliumDrawer<T> { impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> GliumDrawer<T> {
fn from(backend: T) -> GliumDrawer<T> { pub fn init(backend: T, egl_display: Rc<RefCell<Option<EGLDisplay>>>, log: Logger) -> GliumDrawer<T> {
let display = backend.into(); let display = backend.into();
// building the vertex buffer, which contains all the vertices that we will draw // building the vertex buffer, which contains all the vertices that we will draw
@ -68,82 +75,93 @@ impl<T: Into<GliumGraphicsBackend<T>> + EGLGraphicsBackend + 'static> From<T> fo
let index_buffer = let index_buffer =
glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]).unwrap(); glium::IndexBuffer::new(&display, PrimitiveType::TriangleStrip, &[1 as u16, 2, 0, 3]).unwrap();
// compiling shaders and linking them together let programs = opengl_programs!(&display);
let program = program!(&display,
100 => {
vertex: "
#version 100
uniform lowp mat4 matrix;
attribute lowp vec2 position;
attribute lowp vec2 tex_coords;
varying lowp vec2 v_tex_coords;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
}
",
fragment: "
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = color.w;
}
",
},
).unwrap();
GliumDrawer { GliumDrawer {
display, display,
vertex_buffer, vertex_buffer,
index_buffer, index_buffer,
program, programs,
egl_display,
log,
} }
} }
} }
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> { impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
pub fn texture_from_mem(&self, contents: &[u8], surface_dimensions: (u32, u32)) -> Texture2d { pub fn texture_from_buffer(&self, buffer: Resource<wl_buffer::WlBuffer>) -> Result<TextureMetadata, ()> {
let image = glium::texture::RawImage2d { // try to retrieve the egl contents of this buffer
data: contents.into(), let images = if let Some(display) = &self.egl_display.borrow().as_ref() {
width: surface_dimensions.0, display.egl_buffer_contents(buffer)
height: surface_dimensions.1, } else {
format: glium::texture::ClientFormat::U8U8U8U8, Err(BufferAccessError::NotManaged(buffer))
}; };
Texture2d::new(&self.display, image).unwrap() match images {
} Ok(images) => {
// we have an EGL buffer
pub fn texture_from_egl(&self, images: &EGLImages) -> Option<Texture2d> { let format = match images.format {
let format = match images.format { Format::RGB => UncompressedFloatFormat::U8U8U8,
Format::RGB => UncompressedFloatFormat::U8U8U8, Format::RGBA => UncompressedFloatFormat::U8U8U8U8,
Format::RGBA => UncompressedFloatFormat::U8U8U8U8, _ => {
_ => return None, warn!(self.log, "Unsupported EGL buffer format"; "format" => format!("{:?}", images.format));
}; return Err(());
}
let opengl_texture = Texture2d::empty_with_format( };
&self.display, let opengl_texture = Texture2d::empty_with_format(
format, &self.display,
MipmapsOption::NoMipmap, format,
images.width, MipmapsOption::NoMipmap,
images.height, images.width,
).unwrap(); images.height,
unsafe { ).unwrap();
images unsafe {
.bind_to_texture(0, opengl_texture.get_id()) images
.expect("Failed to bind to texture"); .bind_to_texture(0, opengl_texture.get_id())
.expect("Failed to bind to texture");
}
Ok(TextureMetadata {
texture: opengl_texture,
fragment: ::shaders::BUFFER_RGBA,
y_inverted: images.y_inverted,
dimensions: (images.width, images.height),
images: Some(images), // I guess we need to keep this alive ?
})
}
Err(BufferAccessError::NotManaged(buffer)) => {
// this is not an EGL buffer, try SHM
match shm_buffer_contents(&buffer, |slice, data| {
::shm_load::load_shm_buffer(data, slice)
.map(|(image, kind)| (Texture2d::new(&self.display, image).unwrap(), kind, data))
}) {
Ok(Ok((texture, kind, data))) => Ok(TextureMetadata {
texture,
fragment: kind,
y_inverted: false,
dimensions: (data.width as u32, data.height as u32),
images: None,
}),
Ok(Err(format)) => {
warn!(self.log, "Unsupported SHM buffer format"; "format" => format!("{:?}", format));
Err(())
}
Err(err) => {
warn!(self.log, "Unable to load buffer contents"; "err" => format!("{:?}", err));
Err(())
}
}
}
Err(err) => {
error!(self.log, "EGL error"; "err" => format!("{:?}", err));
Err(())
}
} }
Some(opengl_texture)
} }
pub fn render_texture( pub fn render_texture(
&self, &self,
target: &mut glium::Frame, target: &mut glium::Frame,
texture: &Texture2d, texture: &Texture2d,
texture_kind: usize,
y_inverted: bool, y_inverted: bool,
surface_dimensions: (u32, u32), surface_dimensions: (u32, u32),
surface_location: (i32, i32), surface_location: (i32, i32),
@ -175,7 +193,7 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
.draw( .draw(
&self.vertex_buffer, &self.vertex_buffer,
&self.index_buffer, &self.index_buffer,
&self.program, &self.programs[texture_kind],
&uniforms, &uniforms,
&glium::DrawParameters { &glium::DrawParameters {
blend: blending, blend: blending,
@ -197,6 +215,14 @@ impl<G: EGLWaylandExtensions + EGLGraphicsBackend + 'static> EGLWaylandExtension
} }
} }
pub struct TextureMetadata {
pub texture: Texture2d,
pub fragment: usize,
pub y_inverted: bool,
pub dimensions: (u32, u32),
images: Option<EGLImages>,
}
impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> { impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
pub fn draw_windows(&self, window_map: &MyWindowMap, compositor_token: MyCompositorToken, log: &Logger) { pub fn draw_windows(&self, window_map: &MyWindowMap, compositor_token: MyCompositorToken, log: &Logger) {
let mut frame = self.draw(); let mut frame = self.draw();
@ -214,48 +240,26 @@ impl<F: EGLGraphicsBackend + 'static> GliumDrawer<F> {
|_surface, attributes, role, &(mut x, mut y)| { |_surface, attributes, role, &(mut x, mut y)| {
// there is actually something to draw ! // there is actually something to draw !
if attributes.user_data.texture.is_none() { if attributes.user_data.texture.is_none() {
let mut remove = false; if let Some(buffer) = attributes.user_data.buffer.take() {
match attributes.user_data.buffer { if let Ok(m) = self.texture_from_buffer(buffer.clone()) {
Some(Buffer::Egl { ref images }) => { attributes.user_data.texture = Some(m);
match images.format {
Format::RGB | Format::RGBA => {
attributes.user_data.texture =
self.texture_from_egl(&images);
}
_ => {
// we don't handle the more complex formats here.
attributes.user_data.texture = None;
remove = true;
}
};
} }
Some(Buffer::Shm { ref data, ref size }) => { // notify the client that we have finished reading the
attributes.user_data.texture = // buffer
Some(self.texture_from_mem(data, *size)); buffer.send(wl_buffer::Event::Release);
}
_ => {}
}
if remove {
attributes.user_data.buffer = None;
} }
} }
if let Some(ref metadata) = attributes.user_data.texture {
if let Some(ref texture) = attributes.user_data.texture {
if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) { if let Ok(subdata) = Role::<SubsurfaceRole>::data(role) {
x += subdata.location.0; x += subdata.location.0;
y += subdata.location.1; y += subdata.location.1;
} }
self.render_texture( self.render_texture(
&mut frame, &mut frame,
texture, &metadata.texture,
match *attributes.user_data.buffer.as_ref().unwrap() { metadata.fragment,
Buffer::Egl { ref images } => images.y_inverted, metadata.y_inverted,
Buffer::Shm { .. } => false, metadata.dimensions,
},
match *attributes.user_data.buffer.as_ref().unwrap() {
Buffer::Egl { ref images } => (images.width, images.height),
Buffer::Shm { ref size, .. } => *size,
},
(x, y), (x, y),
screen_dimensions, screen_dimensions,
::glium::Blend { ::glium::Blend {

View File

@ -12,16 +12,19 @@ extern crate xkbcommon;
use slog::Drain; use slog::Drain;
use smithay::wayland_server::Display; use smithay::wayland_server::Display;
#[macro_use]
mod shaders;
mod glium_drawer; mod glium_drawer;
mod input_handler;
#[cfg(feature = "tty_launch")]
mod raw_drm;
mod shell; mod shell;
mod shm_load;
#[cfg(feature = "udev")] #[cfg(feature = "udev")]
mod udev; mod udev;
mod window_map; mod window_map;
#[cfg(feature = "winit")] #[cfg(feature = "winit")]
mod winit; mod winit;
mod input_handler;
#[cfg(feature = "tty_launch")]
mod raw_drm;
static POSSIBLE_BACKENDS: &'static [&'static str] = &[ static POSSIBLE_BACKENDS: &'static [&'static str] = &[
#[cfg(feature = "winit")] #[cfg(feature = "winit")]

View File

@ -75,11 +75,18 @@ pub fn run_raw_drm(mut display: Display, mut event_loop: EventLoop, log: Logger)
let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.) let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.)
// Initialize the hardware backend // Initialize the hardware backend
let renderer = GliumDrawer::from( let backend = device
device .create_backend(crtc, mode, vec![connector_info.handle()])
.create_backend(crtc, mode, vec![connector_info.handle()]) .unwrap();
.unwrap(), let egl_display = Rc::new(RefCell::new(
); if let Ok(egl_display) = backend.bind_wl_display(&display) {
info!(log, "EGL hardware-acceleration enabled");
Some(egl_display)
} else {
None
},
));
let renderer = GliumDrawer::init(backend, egl_display, log.clone());
{ {
/* /*
* Initialize glium * Initialize glium
@ -89,23 +96,13 @@ pub fn run_raw_drm(mut display: Display, mut event_loop: EventLoop, log: Logger)
frame.finish().unwrap(); frame.finish().unwrap();
} }
let egl_display = Rc::new(RefCell::new(
if let Ok(egl_display) = renderer.bind_wl_display(&display) {
info!(log, "EGL hardware-acceleration enabled");
Some(egl_display)
} else {
None
},
));
/* /*
* Initialize the globals * Initialize the globals
*/ */
init_shm_global(&mut display, event_loop.token(), vec![], log.clone()); init_shm_global(&mut display, event_loop.token(), vec![], log.clone());
let (compositor_token, _, _, window_map) = let (compositor_token, _, _, window_map) = init_shell(&mut display, event_loop.token(), log.clone());
init_shell(&mut display, event_loop.token(), log.clone(), egl_display);
/* /*
* Add a listening socket: * Add a listening socket:

120
anvil/src/shaders.rs Normal file
View File

@ -0,0 +1,120 @@
/*
* This file is the single point of definition of the opengl shaders
* and their indexes.
*
* The opengl_programs!() macro must call make_program!() in the correct
* order matching the indices stored in the BUFFER_* constants, if it
* does not, things will be drawn on screen with wrong colors.
*/
// create a set of shaders for various loading types
macro_rules! make_program(
($display: expr, $fragment_shader:expr) => {
program!($display,
100 => {
vertex: ::shaders::VERTEX_SHADER,
fragment: $fragment_shader,
},
).unwrap()
}
);
#[macro_escape]
macro_rules! opengl_programs(
($display: expr) => {
[
make_program!($display, ::shaders::FRAGMENT_SHADER_RGBA),
make_program!($display, ::shaders::FRAGMENT_SHADER_ABGR),
make_program!($display, ::shaders::FRAGMENT_SHADER_XBGR),
make_program!($display, ::shaders::FRAGMENT_SHADER_BGRA),
make_program!($display, ::shaders::FRAGMENT_SHADER_BGRX),
]
}
);
/*
* OpenGL Shaders
*/
pub const VERTEX_SHADER: &'static str = r#"
#version 100
uniform lowp mat4 matrix;
attribute lowp vec2 position;
attribute lowp vec2 tex_coords;
varying lowp vec2 v_tex_coords;
void main() {
gl_Position = matrix * vec4(position, 0.0, 1.0);
v_tex_coords = tex_coords;
}"#;
pub const FRAGMENT_COUNT: usize = 5;
pub const BUFFER_RGBA: usize = 0;
pub const FRAGMENT_SHADER_RGBA: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.x;
gl_FragColor.g = color.y;
gl_FragColor.b = color.z;
gl_FragColor.a = color.w;
}
"#;
pub const BUFFER_ABGR: usize = 1;
pub const FRAGMENT_SHADER_ABGR: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.w;
gl_FragColor.g = color.z;
gl_FragColor.b = color.y;
gl_FragColor.a = color.x;
}
"#;
pub const BUFFER_XBGR: usize = 2;
pub const FRAGMENT_SHADER_XBGR: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.w;
gl_FragColor.g = color.z;
gl_FragColor.b = color.y;
gl_FragColor.a = 1.0;
}
"#;
pub const BUFFER_BGRA: usize = 3;
pub const FRAGMENT_SHADER_BGRA: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = color.w;
}
"#;
pub const BUFFER_BGRX: usize = 4;
pub const FRAGMENT_SHADER_BGRX: &'static str = r#"
#version 100
uniform lowp sampler2D tex;
varying lowp vec2 v_tex_coords;
void main() {
lowp vec4 color = texture2D(tex, v_tex_coords);
gl_FragColor.r = color.z;
gl_FragColor.g = color.y;
gl_FragColor.b = color.x;
gl_FragColor.a = 1.0;
}
"#;

View File

@ -2,20 +2,15 @@ use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use glium::texture::Texture2d;
use rand; use rand;
use smithay::backend::graphics::egl::wayland::{BufferAccessError, Format};
use smithay::backend::graphics::egl::wayland::{EGLDisplay, EGLImages};
use smithay::wayland::compositor::{compositor_init, CompositorToken, SurfaceAttributes, SurfaceEvent}; use smithay::wayland::compositor::{compositor_init, CompositorToken, SurfaceAttributes, SurfaceEvent};
use smithay::wayland::shell::xdg::{xdg_shell_init, PopupConfigure, ShellState as XdgShellState,
ToplevelConfigure, XdgRequest, XdgSurfaceRole};
use smithay::wayland::shell::legacy::{wl_shell_init, ShellRequest, ShellState as WlShellState, use smithay::wayland::shell::legacy::{wl_shell_init, ShellRequest, ShellState as WlShellState,
ShellSurfaceKind, ShellSurfaceRole}; ShellSurfaceKind, ShellSurfaceRole};
use smithay::wayland::shm::with_buffer_contents as shm_buffer_contents; use smithay::wayland::shell::xdg::{xdg_shell_init, PopupConfigure, ShellState as XdgShellState,
use smithay::wayland_server::{Display, LoopToken, Resource}; ToplevelConfigure, XdgRequest, XdgSurfaceRole};
use smithay::wayland_server::protocol::{wl_buffer, wl_callback, wl_shell_surface, wl_surface}; use smithay::wayland_server::protocol::{wl_buffer, wl_callback, wl_shell_surface, wl_surface};
use smithay::wayland_server::{Display, LoopToken, Resource};
use window_map::{Kind as SurfaceKind, WindowMap}; use window_map::{Kind as SurfaceKind, WindowMap};
@ -30,7 +25,6 @@ pub fn init_shell(
display: &mut Display, display: &mut Display,
looptoken: LoopToken, looptoken: LoopToken,
log: ::slog::Logger, log: ::slog::Logger,
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
) -> ( ) -> (
CompositorToken<SurfaceData, Roles>, CompositorToken<SurfaceData, Roles>,
Arc<Mutex<XdgShellState<SurfaceData, Roles, ()>>>, Arc<Mutex<XdgShellState<SurfaceData, Roles, ()>>>,
@ -38,12 +32,11 @@ pub fn init_shell(
Rc<RefCell<MyWindowMap>>, Rc<RefCell<MyWindowMap>>,
) { ) {
// Create the compositor // Create the compositor
let c_egl_display = egl_display.clone();
let (compositor_token, _, _) = compositor_init( let (compositor_token, _, _) = compositor_init(
display, display,
looptoken.clone(), looptoken.clone(),
move |request, (surface, ctoken)| match request { move |request, (surface, ctoken)| match request {
SurfaceEvent::Commit => surface_commit(&surface, ctoken, &*c_egl_display), SurfaceEvent::Commit => surface_commit(&surface, ctoken),
SurfaceEvent::Frame { callback } => callback SurfaceEvent::Frame { callback } => callback
.implement(|e, _| match e {}, None::<fn(_, _)>) .implement(|e, _| match e {}, None::<fn(_, _)>)
.send(wl_callback::Event::Done { callback_data: 0 }), .send(wl_callback::Event::Done { callback_data: 0 }),
@ -117,72 +110,24 @@ pub fn init_shell(
log.clone(), log.clone(),
); );
( (compositor_token, xdg_shell_state, wl_shell_state, window_map)
compositor_token,
xdg_shell_state,
wl_shell_state,
window_map,
)
} }
#[derive(Default)] #[derive(Default)]
pub struct SurfaceData { pub struct SurfaceData {
pub buffer: Option<Buffer>, pub buffer: Option<Resource<wl_buffer::WlBuffer>>,
pub texture: Option<Texture2d>, pub texture: Option<::glium_drawer::TextureMetadata>,
} }
pub enum Buffer { fn surface_commit(surface: &Resource<wl_surface::WlSurface>, token: CompositorToken<SurfaceData, Roles>) {
Egl { images: EGLImages },
Shm { data: Vec<u8>, size: (u32, u32) },
}
fn surface_commit(
surface: &Resource<wl_surface::WlSurface>,
token: CompositorToken<SurfaceData, Roles>,
display: &RefCell<Option<EGLDisplay>>,
) {
// we retrieve the contents of the associated buffer and copy it // we retrieve the contents of the associated buffer and copy it
token.with_surface_data(surface, |attributes| { token.with_surface_data(surface, |attributes| {
match attributes.buffer.take() { match attributes.buffer.take() {
Some(Some((buffer, (_x, _y)))) => { Some(Some((buffer, (_x, _y)))) => {
// we ignore hotspot coordinates in this simple example // new contents
match if let Some(display) = display.borrow().as_ref() { // TODO: handle hotspot coordinates
display.egl_buffer_contents(buffer) attributes.user_data.buffer = Some(buffer);
} else { attributes.user_data.texture = None;
Err(BufferAccessError::NotManaged(buffer))
} {
Ok(images) => {
match images.format {
Format::RGB => {}
Format::RGBA => {}
_ => {
// we don't handle the more complex formats here.
attributes.user_data.buffer = None;
attributes.user_data.texture = None;
return;
}
};
attributes.user_data.texture = None;
attributes.user_data.buffer = Some(Buffer::Egl { images });
}
Err(BufferAccessError::NotManaged(buffer)) => {
shm_buffer_contents(&buffer, |slice, data| {
let offset = data.offset as usize;
let stride = data.stride as usize;
let width = data.width as usize;
let height = data.height as usize;
let mut new_vec = Vec::with_capacity(width * height * 4);
for i in 0..height {
new_vec
.extend(&slice[(offset + i * stride)..(offset + i * stride + width * 4)]);
}
attributes.user_data.texture = None;
attributes.user_data.buffer = Some(Buffer::Shm { data: new_vec, size: (data.width as u32, data.height as u32) });
}).expect("Got EGL buffer with no set EGLDisplay. You need to unbind your EGLContexts before dropping them!");
buffer.send(wl_buffer::Event::Release);
}
Err(err) => panic!("EGL error: {}", err),
}
} }
Some(None) => { Some(None) => {
// erase the contents // erase the contents
@ -197,11 +142,8 @@ fn surface_commit(
fn get_size(attrs: &SurfaceAttributes<SurfaceData>) -> Option<(i32, i32)> { fn get_size(attrs: &SurfaceAttributes<SurfaceData>) -> Option<(i32, i32)> {
attrs attrs
.user_data .user_data
.buffer .texture
.as_ref() .as_ref()
.map(|ref buffer| match **buffer { .map(|ref meta| meta.dimensions)
Buffer::Shm { ref size, .. } => *size,
Buffer::Egl { ref images } => (images.width, images.height),
})
.map(|(x, y)| (x as i32, y as i32)) .map(|(x, y)| (x as i32, y as i32))
} }

52
anvil/src/shm_load.rs Normal file
View File

@ -0,0 +1,52 @@
use std::borrow::Cow;
use smithay::wayland::shm::BufferData;
use smithay::wayland_server::protocol::wl_shm::Format;
use glium::texture::{ClientFormat, RawImage2d};
pub fn load_shm_buffer<'a>(data: BufferData, pool: &'a [u8]) -> Result<(RawImage2d<'a, u8>, usize), Format> {
let offset = data.offset as usize;
let width = data.width as usize;
let height = data.height as usize;
let stride = data.stride as usize;
// number of bytes per pixel
// TODO: compute from data.format
let pixelsize = 4;
// ensure consistency, the SHM handler of smithay should ensure this
assert!(offset + (height - 1) * stride + width * pixelsize <= pool.len());
let slice: Cow<[u8]> = if stride == width * pixelsize {
// the buffer is cleanly continuous, use as-is
Cow::Borrowed(&pool[offset..(offset + height * width * pixelsize)])
} else {
// the buffer is discontinuous or lines overlap
// we need to make a copy as unfortunately glium does not
// expose the OpenGL APIs we would need to load this buffer :/
let mut data = Vec::with_capacity(height * width * pixelsize);
for i in 0..height {
data.extend(&pool[(offset + i * stride)..(offset + i * stride + width * pixelsize)]);
}
Cow::Owned(data)
};
// sharders format need to be reversed to account for endianness
let (client_format, fragment) = match data.format {
Format::Argb8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_BGRA),
Format::Xrgb8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_BGRX),
Format::Rgba8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_ABGR),
Format::Rgbx8888 => (ClientFormat::U8U8U8U8, ::shaders::BUFFER_XBGR),
_ => return Err(data.format),
};
Ok((
RawImage2d {
data: slice,
width: width as u32,
height: height as u32,
format: client_format,
},
fragment,
))
}

View File

@ -62,7 +62,6 @@ pub fn run_udev(mut display: Display, mut event_loop: EventLoop, log: Logger) ->
&mut display.borrow_mut(), &mut display.borrow_mut(),
event_loop.token(), event_loop.token(),
log.clone(), log.clone(),
active_egl_context.clone(),
); );
/* /*
@ -215,6 +214,7 @@ impl UdevHandlerImpl {
pub fn scan_connectors( pub fn scan_connectors(
&self, &self,
device: &mut DrmDevice<SessionFdDrmDevice>, device: &mut DrmDevice<SessionFdDrmDevice>,
egl_display: Rc<RefCell<Option<EGLDisplay>>>,
) -> HashMap<crtc::Handle, GliumDrawer<DrmBackend<SessionFdDrmDevice>>> { ) -> HashMap<crtc::Handle, GliumDrawer<DrmBackend<SessionFdDrmDevice>>> {
// Get a set of all modesetting resource handles (excluding planes): // Get a set of all modesetting resource handles (excluding planes):
let res_handles = device.resource_handles().unwrap(); let res_handles = device.resource_handles().unwrap();
@ -242,10 +242,12 @@ impl UdevHandlerImpl {
if !backends.contains_key(&crtc) { if !backends.contains_key(&crtc) {
let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.) let mode = connector_info.modes()[0]; // Use first mode (usually highest resoltion, but in reality you should filter and sort and check and match with other connectors, if you use more then one.)
// create a backend // create a backend
let renderer = GliumDrawer::from( let renderer = GliumDrawer::init(
device device
.create_backend(crtc, mode, vec![connector_info.handle()]) .create_backend(crtc, mode, vec![connector_info.handle()])
.unwrap(), .unwrap(),
egl_display.clone(),
self.logger.clone(),
); );
// create cursor // create cursor
@ -279,7 +281,10 @@ impl UdevHandler<DrmHandlerImpl> for UdevHandlerImpl {
*self.active_egl_context.borrow_mut() = device.bind_wl_display(&*self.display.borrow()).ok(); *self.active_egl_context.borrow_mut() = device.bind_wl_display(&*self.display.borrow()).ok();
} }
let backends = Rc::new(RefCell::new(self.scan_connectors(device))); let backends = Rc::new(RefCell::new(self.scan_connectors(
device,
self.active_egl_context.clone(),
)));
self.backends.insert(device.device_id(), backends.clone()); self.backends.insert(device.device_id(), backends.clone());
Some(DrmHandlerImpl { Some(DrmHandlerImpl {
@ -294,7 +299,7 @@ impl UdevHandler<DrmHandlerImpl> for UdevHandlerImpl {
fn device_changed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) { fn device_changed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) {
//quick and dirt, just re-init all backends //quick and dirt, just re-init all backends
let backends = self.backends.get(&device.device_id()).unwrap(); let backends = self.backends.get(&device.device_id()).unwrap();
*backends.borrow_mut() = self.scan_connectors(device); *backends.borrow_mut() = self.scan_connectors(device, self.active_egl_context.clone());
} }
fn device_removed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) { fn device_removed(&mut self, device: &mut DrmDevice<SessionFdDrmDevice>) {

View File

@ -32,7 +32,7 @@ pub fn run_winit(display: &mut Display, event_loop: &mut EventLoop, log: Logger)
)); ));
let (w, h) = renderer.get_framebuffer_dimensions(); let (w, h) = renderer.get_framebuffer_dimensions();
let drawer = GliumDrawer::from(renderer); let drawer = GliumDrawer::init(renderer, egl_display, log.clone());
let name = display.add_socket_auto().unwrap().into_string().unwrap(); let name = display.add_socket_auto().unwrap().into_string().unwrap();
info!(log, "Listening on wayland socket"; "name" => name.clone()); info!(log, "Listening on wayland socket"; "name" => name.clone());
@ -46,8 +46,7 @@ pub fn run_winit(display: &mut Display, event_loop: &mut EventLoop, log: Logger)
init_shm_global(display, event_loop.token(), vec![], log.clone()); init_shm_global(display, event_loop.token(), vec![], log.clone());
let (compositor_token, _, _, window_map) = let (compositor_token, _, _, window_map) = init_shell(display, event_loop.token(), log.clone());
init_shell(display, event_loop.token(), log.clone(), egl_display);
let (mut seat, _) = Seat::new(display, event_loop.token(), "winit".into(), log.clone()); let (mut seat, _) = Seat::new(display, event_loop.token(), "winit".into(), log.clone());

View File

@ -137,6 +137,7 @@ impl ::std::error::Error for TextureCreationError {
/// Texture format types /// Texture format types
#[repr(i32)] #[repr(i32)]
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
#[derive(Debug)]
pub enum Format { pub enum Format {
/// RGB format /// RGB format
RGB = ffi::egl::TEXTURE_RGB as i32, RGB = ffi::egl::TEXTURE_RGB as i32,

View File

@ -145,24 +145,26 @@ pub enum BufferAccessError {
/// ///
/// If the buffer is not managed by the provided `ShmGlobal`, the closure is not called /// If the buffer is not managed by the provided `ShmGlobal`, the closure is not called
/// and this method will return `Err(())` (this will be the case for an EGL buffer for example). /// and this method will return `Err(())` (this will be the case for an EGL buffer for example).
pub fn with_buffer_contents<F>(buffer: &Resource<wl_buffer::WlBuffer>, f: F) -> Result<(), BufferAccessError> pub fn with_buffer_contents<F, T>(
buffer: &Resource<wl_buffer::WlBuffer>,
f: F,
) -> Result<T, BufferAccessError>
where where
F: FnOnce(&[u8], BufferData), F: FnOnce(&[u8], BufferData) -> T,
{ {
if !buffer.is_implemented_with::<ShmGlobalData>() { if !buffer.is_implemented_with::<ShmGlobalData>() {
return Err(BufferAccessError::NotManaged); return Err(BufferAccessError::NotManaged);
} }
let data = unsafe { &*(buffer.get_user_data() as *mut InternalBufferData) }; let data = unsafe { &*(buffer.get_user_data() as *mut InternalBufferData) };
if data.pool match data.pool.with_data_slice(|slice| f(slice, data.data)) {
.with_data_slice(|slice| f(slice, data.data)) Ok(t) => Ok(t),
.is_err() Err(()) => {
{ // SIGBUS error occured
// SIGBUS error occured buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into());
buffer.post_error(wl_shm::Error::InvalidFd as u32, "Bad pool size.".into()); Err(BufferAccessError::BadMap)
return Err(BufferAccessError::BadMap); }
} }
Ok(())
} }
impl Implementation<Resource<wl_shm::WlShm>, wl_shm::Request> for ShmGlobalData { impl Implementation<Resource<wl_shm::WlShm>, wl_shm::Request> for ShmGlobalData {

View File

@ -46,7 +46,7 @@ impl Pool {
}) })
} }
pub fn with_data_slice<F: FnOnce(&[u8])>(&self, f: F) -> Result<(), ()> { pub fn with_data_slice<T, F: FnOnce(&[u8]) -> T>(&self, f: F) -> Result<T, ()> {
// Place the sigbus handler // Place the sigbus handler
SIGBUS_INIT.call_once(|| unsafe { SIGBUS_INIT.call_once(|| unsafe {
place_sigbus_handler(); place_sigbus_handler();
@ -67,7 +67,7 @@ impl Pool {
}); });
let slice = pool_guard.get_slice(); let slice = pool_guard.get_slice();
f(slice); let t = f(slice);
// Cleanup Post-access // Cleanup Post-access
SIGBUS_GUARD.with(|guard| { SIGBUS_GUARD.with(|guard| {
@ -77,7 +77,7 @@ impl Pool {
debug!(self.log, "SIGBUS caught on access on shm pool"; "fd" => self.fd); debug!(self.log, "SIGBUS caught on access on shm pool"; "fd" => self.fd);
Err(()) Err(())
} else { } else {
Ok(()) Ok(t)
} }
}) })
} }