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
/* SPDX-License-Identifier: LGPL-2.1-or-later

Copyright (c) 2022 Purism, SPC
Copyright (c) 2024 DorotaC
*/
/*! EGL procedures +GBM offscreen rendering context.
*/


use crate::egl_ext as ext;
use crate::glerr;
use ext::{ExtPlatformBaseInstance, KhrImageBaseInstance, OesImageInstance};
use gbm;
use gbm::{AsRaw, FdError};
use gl::types::GLuint;
pub use khronos_egl;
use khronos_egl::Image;
use khronos_egl as egl;
use std::error::Error;
use std::ffi::c_void;
use std::fs;
use std::fs::File;
use std::ops::Deref;
use std::os::fd::{AsRawFd, AsFd, BorrowedFd, OwnedFd};
use std::ptr;
use std::sync::Arc;
use std::sync::atomic;
use std::sync::atomic::AtomicUsize;


// TODO: should this be Clone? Is concurrent mutable access to raw display and context bad?
// Currently, Backend needs a copy, while a copy remains in Facade.
/// GBM EGL GPU context
#[derive(Clone, Debug)]
pub struct Egl {
    display: egl::Display,
    context: egl::Context,
    config: egl::Config,
    device: Arc<gbm::Device<File>>,
}

impl Egl {
    unsafe fn make_current(&self) {
        egl::Instance::new(egl::Static)
            .make_current(
                self.display,
                None,
                None,
                Some(self.context),
            )
            .unwrap()
    }
    unsafe fn release_current(&self) {
        egl::Instance::new(egl::Static)
            .make_current(
                self.display,
                None,
                None,
                None,
            )
            .unwrap()
    }
}

// The texture number is not arbitrary, so creating/replacing one should not be possible outside of code which knows how to handle this..
/// OpenGL texture identifier, used for binding textures to context.
#[derive(Copy, Clone, Debug)]
pub struct TextureId(GLuint);

impl TextureId {
    /// Returns the OpenGL texture identifier
    pub fn as_gl_id(&self) -> GLuint {
        self.0
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Dimensions {
    pub width: u32,
    pub height: u32,
}

/// A texture attached to an image
#[derive(Debug)]
pub struct Texture {
    id: TextureId,
    dimensions: Dimensions,
    format: gbm::Format,
}

impl Texture {
    pub fn id(&self) ->TextureId {
        self.id
    }
    pub fn dimensions(&self) -> Dimensions {
        self.dimensions
    }
    pub fn format(&self) -> gbm::Format {
        self.format
    }
}

/// The image is created from a fd, but it does not get invalidated when the fd is released
#[derive(Debug)]
pub struct DmabufImage {
    texture: TextureId,
    image: egl::Image,
    dimensions: Dimensions,
    format: gbm::Format,
}

/// The image is created from a fd, but it does not get invalidated when the fd is released
#[derive(Debug)]
pub struct DmabufTexture {
    texture: glium::Texture2d,
    image: egl::Image,
    dimensions: Dimensions,
    format: gbm::Format,
}


// FIXME: is it actually safe? egl::Image is not Send, but glutin requires Send in Context::exec_in_context for some reason. Can't avoid using that to create a DmabufImage.
unsafe impl Send for DmabufImage{}

impl DmabufImage {
    // TODO: don't just assume this is bound. Dmabufimage should contain a bound texture
    pub fn get_texture(&self) ->Texture {
        Texture {
            id: self.texture,
            dimensions: self.dimensions,
            format: self.format,
        }
    }
}

pub type DmabufImageRef = DmabufImage;

/// Clears the fd once finished. TODO: clear texture?
#[derive(Debug)]
pub struct OwnedDmabufImage {
    dmafd: OwnedFd,
    image: DmabufImageRef,
}

impl OwnedDmabufImage {
    pub fn get_texture(&self) -> &DmabufImageRef {
        &self.image
    }
    
    pub fn fd(&self) -> BorrowedFd {
        self.dmafd.as_fd()
    }
}

#[derive(Debug)]
pub struct Tex {
    // TODO: is this ever needed after creating the FD?
    bo: gbm::BufferObject<()>,
    image: OwnedDmabufImage,
}

impl Tex {
    pub fn new(bo: gbm::BufferObject<()>, image: DmabufImage) -> Result<Self, FdError> {
        Ok(Tex {
            image: OwnedDmabufImage {
                dmafd: bo.fd()?,
                image,
            },
            bo,
        })
    }

    pub fn get_image(&self) -> &OwnedDmabufImage {
        &self.image
    }
    
    pub fn get_texture(&self) -> &DmabufImageRef {
        &self.image.get_texture()
    }
}

/// A shared reference to a GBM EGL GPU context.
#[derive(Clone)]
pub struct ContextRef {
    pub egl: Egl,
    /// Number of times make_current was called.
    // This counts values across threads, even though 2 make_current calls betwen threads are trouble.
    // It's because ContextRef itself will move between threads on the C side, and the data structures must survive that.
    // It's easier to be synced across threads than to reflect the restriction.
    current: Arc<AtomicUsize>,
}

impl ContextRef {
    pub fn new() -> Self {
        let egl_calls = egl::Instance::new(egl::Static);

        let gbm = gbm::Device::new(
            // WARNING: Rust is said to always use CLOEXEC, so it's not specified here. It's still needed!
            // https://github.com/rust-lang/rust/pull/27971
            fs::OpenOptions::new().read(true).write(true).open("/dev/dri/renderD128").unwrap()
        ).unwrap();

        egl_calls.bind_api(egl::OPENGL_API).unwrap();

        // Older API versions don't have get_platform_display (TODO: check, this is from memory of Librem 5), so use "_ext" despite the reimplementation.
        let display: egl::Display = unsafe { egl_calls.get_platform_display_ext(
            ext::PLATFORM_GBM_MESA as u32,
            gbm.as_raw() as _,
            &[egl::ATTRIB_NONE],
        )}.unwrap();

        egl_calls.initialize(display).unwrap();

        // Set context
        
        // TODO: try EGL_KHR_no_config_context
        
        // get an appropriate EGL frame buffer configuration
        let configs = {
            let mut configs = Vec::with_capacity(32);
            egl_calls.choose_config(
                display, 
                &[
                    egl::BUFFER_SIZE, 32,
                    egl::DEPTH_SIZE, egl::DONT_CARE,
                    egl::STENCIL_SIZE, egl::DONT_CARE,
                    egl::RENDERABLE_TYPE, egl::OPENGL_ES2_BIT,
                    egl::SURFACE_TYPE, egl::WINDOW_BIT,
                    egl::NONE,
                ],
                &mut configs,
            ).unwrap();
            configs
        };
        
        // Find a config whose native visual ID is the desired GBM format.
        let config = configs.into_iter().find(|config|
            egl_calls.get_config_attrib(
                display,
                *config,
                egl::NATIVE_VISUAL_ID
            ).unwrap() == gbm::Format::Argb8888 as i32
        ).unwrap();
        
        let context = egl_calls
            .create_context(
                display,
                config,
                None,
                &[
                    egl::CONTEXT_MAJOR_VERSION, 1,
                    ext::CONTEXT_FLAGS_KHR, ext::CONTEXT_OPENGL_DEBUG_BIT_KHR,
                    egl::NONE,
                 ],
             ).unwrap();
        
        Self {
            egl: Egl { context, config, device: Arc::new(gbm), display },
            current: Arc::new(AtomicUsize::new(0)),
        }
    }
    
    /// Only needed for raw::backend.
    /// Glium doesn't know that CurrentContext needs to be held in scope.
    /// Unsafe because it requires a manual release.
    pub unsafe fn force_make_current(&self) {
        if self.current.load(atomic::Ordering::SeqCst) == 0 {
            self.egl.make_current();
        }
    }

    fn release_current(&self) {
        if self.current.fetch_sub(1, atomic::Ordering::SeqCst) == 0 {
            unsafe { self.egl.release_current() };
        }
    }

    pub fn get_proc_address(procname: &str) -> *const c_void {
        egl::Instance::new(egl::Static)
            .get_proc_address(procname)
            .map(|a| a as *const c_void)
            .unwrap_or(ptr::null())
    }
    
    pub fn get_device(&self) -> Arc<gbm::Device<File>>{
        self.egl.device.clone()
    }
}

impl EglContext for ContextRef {
    fn get_display(&self) -> egl::Display {
        self.egl.display
    }

    /// Acquires the context.
    /// Relase by letting CurrentContext go out of scope.
    /// CAUTION: this will crash if multiple contexts are interleaved in a single thread. (TODO? thread-local storage could help.)
    fn make_current<'a>(&'a self) -> CurrentContext<'a> {
        if self.current.fetch_add(1, atomic::Ordering::SeqCst) == 1 {
            unsafe { self.egl.make_current() };
        }
        CurrentContext(&self)
    }
}

/// Automatically releases the context by going out of scope.
pub struct CurrentContext<'a>(&'a ContextRef);

impl<'a> Deref for CurrentContext<'a> {
    type Target = ContextRef;
    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl<'a> Drop for CurrentContext<'a> {
    fn drop(&mut self) {
        self.0.release_current();
    }
}

fn format_bpp(fourcc: gbm::Format) -> Option<usize> {
    match fourcc {
        gbm::Format::Argb8888 => Some(4),
        gbm::Format::R8 => Some(1),
        gbm::Format::R16 => Some(2),
        gbm::Format::Rg88 => Some(2),
        gbm::Format::Gr88 => Some(2),
        _ => None,
    }
}


/// WIP: this is to find out what import_dmabuf actually needs
pub trait EglContext {
    fn make_current<'a>(&'a self) -> CurrentContext<'a>;
    fn get_display(&self) -> egl::Display;
}

use thiserror::Error;

#[derive(Debug, Error)]
pub enum DmabufImportError {
    #[error("This format is TODO")]
    UnsupportedPixelFormat,
    #[error("EGL call failed")]
    EglError(egl::Error),
    #[error("OpenGL call failed")]
    GlError(crate::glerr::Error),
}

/// If you intend to import a surface as a rendering target, better use ARGB8888.
/// Otherwise the config won't match.
pub fn import_dmabuf(
    egl: &impl EglContext,
    fd: BorrowedFd,
    dimensions: (u32, u32),
    fourcc: gbm::Format,
) -> Result<DmabufImage, Box<dyn Error>> {
    let _current = egl.make_current();
    Ok(unsafe { import_dmabuf_display(egl.get_display(), fd, dimensions, fourcc) }?)
}

/// Requires the context to already be current
pub unsafe fn import_dmabuf_display(
    display: egl::Display,
    fd: BorrowedFd,
    (width, height): (u32, u32),
    fourcc: gbm::Format,
) -> Result<DmabufImage, DmabufImportError> {
    let egl_calls = egl::Instance::new(egl::Static);
    
    let bytes_per_pixel = format_bpp(fourcc).ok_or(DmabufImportError::UnsupportedPixelFormat)?;
    let image = unsafe {
        egl_calls.create_image_khr(
            display,
            egl::Context::from_ptr(egl::NO_CONTEXT),
            ext::LINUX_DMA_BUF_EXT,
            egl::ClientBuffer::from_ptr(ptr::null_mut()), 
            &[
                egl::WIDTH as _, width as _,
                egl::HEIGHT as _, height as _,
                ext::LINUX_DRM_FOURCC_EXT, fourcc as _,
                ext::DMA_BUF_PLANE0_FD_EXT, fd.as_raw_fd() as _,
                ext::DMA_BUF_PLANE0_OFFSET_EXT, 0,
                ext::DMA_BUF_PLANE0_PITCH_EXT, (width as egl::Int) * (bytes_per_pixel as egl::Int),
                egl::NONE,
            ],
        )
    }.map_err(DmabufImportError::EglError)?;
    
    gl::load_with(|s| egl_calls.get_proc_address(s).unwrap() as _);
    
    let texture = {
        let mut texture = 0;
        glerr::check(unsafe {
            gl::GenTextures(1, &mut texture);
            texture
        })
    }.map_err(DmabufImportError::GlError)?;
    
    Ok(DmabufImage {
        texture: TextureId(texture),
        image,
        dimensions: Dimensions { width, height },
        format: fourcc,
    })
}

/// Attaches texture to image
pub fn attach_image(_egl: CurrentContext, buf: DmabufImage) -> Result<DmabufImage, DmabufImportError> {
    unsafe { attach_image_current(buf) }
}

/// Creates a texture with the image attached
pub unsafe fn attach_image_current(buf: DmabufImage) -> Result<DmabufImage, DmabufImportError> {

    let egl_calls = egl::Instance::new(egl::Static);
    gl::load_with(|s| egl_calls.get_proc_address(s).unwrap() as _);
    
    glerr::check(unsafe {
        gl::BindTexture(gl::TEXTURE_2D, buf.texture.0)
    }).map_err(DmabufImportError::GlError)?;

    // TODO: a renderbuffer used here would/could be faster.
	// EGLImageTargetRenderbufferStorageOES
    unsafe {
        egl_calls.image_target_texture_2d_oes(gl::TEXTURE_2D, buf.image)
    }.map_err(DmabufImportError::EglError)?;
    
    Ok(buf)
}