Skip to main content

edgefirst_image/gl/
mod.rs

1// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
2// SPDX-License-Identifier: Apache-2.0
3
4#![cfg(any(
5    target_os = "linux",
6    target_os = "macos",
7    target_os = "ios",
8    target_os = "android",
9    target_os = "windows"
10))]
11#![cfg(feature = "opengl")]
12// Several types defined at the `gl` module root (EglDisplayKind,
13// TransferBackend, RegionOfInterest, etc.) are consumed only by the
14// Linux-only inner modules (`context`, `dma_import`, `fourcc`). The
15// macOS/iOS and Android paths import platform buffers through their own
16// modules (`iosurface_import`, `ahardwarebuffer_import`) and do not
17// touch every shared type, so some appear unused off Linux.
18// Rather than fragmenting the type definitions per platform, suppress
19// the dead-code/unused-import lints on non-Linux targets.
20#![cfg_attr(not(target_os = "linux"), allow(dead_code, unused_imports))]
21
22// Module layout:
23//   - `platform/` — cross-platform display/EGL-loader seam (all OSes)
24//   - Linux-only:   `context`, `dma_import`, `fourcc`
25//   - macOS/iOS:    `iosurface_import`
26//   - Android-only: `ahardwarebuffer_import`
27//   - Windows:      `platform/windows.rs` (ANGLE/D3D11, PBO transfers only)
28// The engine (`processor`, `threaded`, `cache`, `resources`, `shaders`)
29// is portable and reaches platform buffers only through the `GlPlatform`
30// trait — see `crates/image/ARCHITECTURE.md`.
31
32macro_rules! function {
33    () => {{
34        fn f() {}
35        fn type_name_of<T>(_: T) -> &'static str {
36            std::any::type_name::<T>()
37        }
38        let name = type_name_of(f);
39
40        // Find and cut the rest of the path
41        match &name[..name.len() - 3].rfind(':') {
42            Some(pos) => &name[pos + 1..name.len() - 3],
43            None => &name[..name.len() - 3],
44        }
45    }};
46}
47
48mod cache;
49#[cfg(target_os = "linux")]
50mod context;
51#[cfg(target_os = "linux")]
52mod dma_import;
53// Cfg-agnostic: the float render-path classifier is the single source of
54// truth for the "(PixelFormat, DType, TensorMemory) → float path" decision and
55// is compiled on every platform so both the Linux and macOS backends share one
56// definition (see `crates/image/ARCHITECTURE.md`, review item #4).
57// Portable renderer helpers (crop uniforms, …) shared by both platform
58// backends. No gbm/IOSurface types; compiled on both.
59mod core;
60mod float_dispatch;
61// Pure decision table for the proto-segmentation render path (upload
62// strategy × program × count uniform). No GL types; host-tested
63// exhaustively. See `proto_dispatch.rs`.
64mod proto_dispatch;
65// Portable GL render lowering (y-flip viewport, source UV, batch chunk planner).
66// No platform types; compiled on both platforms, consumed by the converged
67// tile/batch renderer. See `render.rs`.
68mod render;
69// PixelFormat -> DRM FourCC mapping via the portable `drm_fourcc` crate (NOT
70// `gbm`). DRM FourCC is a Linux/DMA-BUF concept, so this lives with the other
71// Linux graphics modules; the point is that it carries no `gbm` coupling, so
72// `shaders.rs` and the format code no longer pull in `gbm`.
73#[cfg(target_os = "android")]
74mod ahardwarebuffer_import;
75// `EGL_ANGLE_image_d3d11_texture` attribute assembly (pure); consumed by the
76// Windows leaf (`platform/windows.rs`) to build the EGLImage import target.
77#[cfg(target_os = "windows")]
78pub(super) mod d3d11_import;
79#[cfg(target_os = "linux")]
80mod fourcc;
81#[cfg(any(target_os = "macos", target_os = "ios"))]
82mod iosurface_import;
83#[cfg(target_os = "android")]
84mod native_fence;
85mod platform;
86mod processor;
87mod resources;
88mod shaders;
89mod shaders_common;
90// Engine GL tests, in three tiers (see crates/image/TESTING.md):
91//   portable                       — run on Linux AND macOS/ANGLE
92//   cfg(target_os = "linux")       — display probing, PBO/CUDA paths
93//   cfg(all(linux, dma_test_formats)) — DMA-BUF import/pool specifics
94// Per-item cfg gates inside the module select the tier; the mount
95// itself is unconditional so the macOS lane runs the portable tier.
96mod tests;
97mod threaded;
98
99#[cfg(target_os = "linux")]
100pub use context::probe_egl_displays;
101// These are accessed by sibling sub-modules via `super::context::` directly.
102// No re-export needed at the mod.rs level.
103pub use cache::{CacheStats, ConvertStats, GlCacheStats};
104pub use threaded::GLProcessorThreaded;
105
106/// Dynamically-loaded EGL 1.4 instance. The lifetime parameter is
107/// `'static` because the underlying `libloading::Library` is intentionally
108/// leaked at first load (see `EGL_LIB` in `context.rs` and the equivalent
109/// on macOS — drivers may retain internal state past explicit cleanup, so
110/// dlclose can SIGBUS on process exit).
111///
112/// Defined here at the `gl` module root so the `platform/` trait and both
113/// platform implementations can name it without dragging in a cross-cfg
114/// re-export. The Linux `context.rs` and the macOS `platform/macos.rs`
115/// both use this same alias.
116pub(super) type Egl = edgefirst_egl::Instance<
117    edgefirst_egl::Dynamic<&'static libloading::Library, edgefirst_egl::EGL1_4>,
118>;
119
120/// Handle returned by `GlPlatform::export_completion_fence` (and surfaced
121/// by `convert_with_fence`): a sync_file fd on Unix
122/// (`EGL_ANDROID_native_fence_sync`), an event NT handle on Windows, set
123/// when the D3D11 device fence reaches the value the convert queued.
124/// Keeps the engine free of `cfg` branches (precedent: `BlobFd` in
125/// `crates/tensor/src/blob.rs`).
126#[cfg(unix)]
127pub type CompletionFence = std::os::fd::OwnedFd;
128#[cfg(windows)]
129pub type CompletionFence = std::os::windows::io::OwnedHandle;
130
131/// Identifies the type of EGL display used for headless OpenGL ES rendering.
132///
133/// The HAL creates a surfaceless GLES 3.0 context
134/// (`EGL_KHR_surfaceless_context` + `EGL_KHR_no_config_context`) and
135/// renders exclusively through FBOs backed by EGLImages imported from
136/// DMA-buf file descriptors. No window or PBuffer surface is created.
137///
138/// Displays are probed in priority order: PlatformDevice first (zero
139/// external dependencies), then GBM, then Default. Use
140/// [`probe_egl_displays`] to discover which are available and
141/// [`ImageProcessorConfig::egl_display`](crate::ImageProcessorConfig::egl_display)
142/// to override the auto-detection.
143///
144/// # Display Types
145///
146/// - **`PlatformDevice`** — Uses `EGL_EXT_device_enumeration` to query
147///   available EGL devices via `eglQueryDevicesEXT`, then selects the first
148///   device with `eglGetPlatformDisplay(EGL_EXT_platform_device, ...)`.
149///   Headless and compositor-free with zero external library dependencies.
150///   Works on NVIDIA GPUs and newer Vivante drivers.
151///
152/// - **`Gbm`** — Opens a DRM render node (e.g. `/dev/dri/renderD128`) and
153///   creates a GBM (Generic Buffer Manager) device, then calls
154///   `eglGetPlatformDisplay(EGL_PLATFORM_GBM_KHR, gbm_device)`. Requires
155///   `libgbm` and a DRM render node. Needed on ARM Mali (i.MX95) and older
156///   Vivante drivers that do not expose `EGL_EXT_platform_device`.
157///
158/// - **`Default`** — Calls `eglGetDisplay(EGL_DEFAULT_DISPLAY)`, letting the
159///   EGL implementation choose the display. On Wayland systems this connects
160///   to the compositor; on X11 it connects to the X server. May block on
161///   headless systems where a compositor is expected but not running.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163pub enum EglDisplayKind {
164    Gbm,
165    PlatformDevice,
166    Default,
167}
168
169impl std::fmt::Display for EglDisplayKind {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match self {
172            EglDisplayKind::Gbm => write!(f, "GBM"),
173            EglDisplayKind::PlatformDevice => write!(f, "PlatformDevice"),
174            EglDisplayKind::Default => write!(f, "Default"),
175        }
176    }
177}
178
179/// A validated, available EGL display discovered by [`probe_egl_displays`].
180#[derive(Debug, Clone)]
181pub struct EglDisplayInfo {
182    /// The type of EGL display.
183    pub kind: EglDisplayKind,
184    /// Human-readable description for logging/diagnostics
185    /// (e.g. "GBM via /dev/dri/renderD128").
186    pub description: String,
187}
188
189/// Tracks which data-transfer method is active for moving pixels
190/// between CPU memory and GPU textures/framebuffers.
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
192pub(crate) enum TransferBackend {
193    /// Zero-copy via EGLImage imported from DMA-buf file descriptors.
194    /// Available on i.MX8 (Vivante), i.MX95 (Mali), Jetson, and any
195    /// platform where `EGL_EXT_image_dma_buf_import` is present AND
196    /// the GPU can actually render through DMA-buf-backed textures.
197    DmaBuf,
198
199    /// Zero-copy via `EGL_ANGLE_iosurface_client_buffer` (macOS/iOS).
200    /// Available when ANGLE's Metal backend is loaded and the EGL
201    /// extension is advertised. The IOSurface is wrapped as an EGL
202    /// pbuffer and bound to a 2D texture via `eglBindTexImage`.
203    #[cfg(any(target_os = "macos", target_os = "ios"))]
204    IOSurface,
205
206    /// Zero-copy via `EGL_ANDROID_image_native_buffer` (Android). The
207    /// AHardwareBuffer is wrapped as an EGLImage via
208    /// `eglGetNativeClientBufferANDROID` → `eglCreateImageKHR` and bound
209    /// to a 2D texture via `glEGLImageTargetTexture2DOES` — persistent
210    /// bindings, like Linux DMA-BUF (unlike the per-pass IOSurface
211    /// pbuffer binds).
212    #[cfg(target_os = "android")]
213    AHardwareBuffer,
214
215    /// Zero-copy via `EGL_ANGLE_image_d3d11_texture` (Windows): the tensor's
216    /// `ID3D11Texture2D` wrapped as an EGLImage and bound with
217    /// `glEGLImageTargetTexture2DOES`. Unlike Linux and Android the binding
218    /// is re-issued per use, because ANGLE does not observe writes made to
219    /// the texture outside GL (see `AngleD3d11::PERSISTENT_TEX_BINDINGS`).
220    #[cfg(target_os = "windows")]
221    D3d11Texture,
222
223    /// GPU buffer via Pixel Buffer Object. Used when DMA-buf is unavailable
224    /// but OpenGL is present. Data stays in GPU-accessible memory. Windows
225    /// took this path until the D3D11 texture import landed and now reports
226    /// [`TransferBackend::D3d11Texture`]; PBO destinations still exist there
227    /// as `TensorMemory::Pbo` tensors.
228    Pbo,
229
230    /// Synchronous `glTexSubImage2D` upload + `glReadPixels` readback.
231    /// Used when DMA-buf is unavailable or when the DMA-buf verification
232    /// probe fails (e.g. NVIDIA discrete GPUs where EGLImage creation
233    /// succeeds but rendered data is all zeros).
234    Sync,
235}
236
237impl TransferBackend {
238    /// Returns `true` if DMA-buf zero-copy is available.
239    pub(crate) fn is_dma(self) -> bool {
240        self == TransferBackend::DmaBuf
241    }
242
243    /// Returns `true` if the platform can import `TensorMemory::DmaBuf`
244    /// tensors zero-copy: DMA-BUF EGLImages on Linux, IOSurface pbuffers
245    /// on macOS. Path-selection sites use this; probes that are
246    /// specifically about DMA-BUF semantics (e.g. the render-roundtrip
247    /// verification) keep `is_dma`.
248    pub(crate) fn is_zero_copy(self) -> bool {
249        #[cfg(any(target_os = "macos", target_os = "ios"))]
250        if self == TransferBackend::IOSurface {
251            return true;
252        }
253        #[cfg(target_os = "android")]
254        if self == TransferBackend::AHardwareBuffer {
255            return true;
256        }
257        #[cfg(target_os = "windows")]
258        if self == TransferBackend::D3d11Texture {
259            return true;
260        }
261        self == TransferBackend::DmaBuf
262    }
263}
264
265/// Interpolation mode for int8 proto textures (GL_R8I cannot use GL_LINEAR).
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
267pub enum Int8InterpolationMode {
268    /// texelFetch at nearest texel — simplest, fastest GPU execution.
269    Nearest,
270    /// texelFetch × 4 neighbors with shader-computed bilinear weights (default).
271    Bilinear,
272    /// Two-pass: dequant int8→f16 FBO, then existing f16 shader with GL_LINEAR.
273    TwoPass,
274}
275
276/// A rectangular region of interest expressed as normalised [0, 1] coordinates.
277#[derive(Debug, Clone, Copy)]
278pub(super) struct RegionOfInterest {
279    pub(super) left: f32,
280    pub(super) top: f32,
281    pub(super) right: f32,
282    pub(super) bottom: f32,
283}
284
285impl RegionOfInterest {
286    /// Build a source ROI from a pixel-space crop rectangle with a half-texel
287    /// inset. The inset ensures that `GL_LINEAR` filtering never samples
288    /// outside the crop boundary — at the extreme texture coordinates the
289    /// bilinear kernel is centred on the boundary texel and cannot reach
290    /// adjacent padding pixels.
291    ///
292    /// The result is clamped to [0, 1] so an out-of-bounds crop rectangle
293    /// cannot produce invalid texture coordinates.
294    ///
295    /// `crop`: pixel-space rectangle (left, top, width, height).
296    /// `tex_w`, `tex_h`: full texture dimensions in pixels.
297    pub(super) fn from_crop_clamped(crop: &crate::Rect, tex_w: usize, tex_h: usize) -> Self {
298        let half_x = 0.5 / tex_w as f32;
299        let half_y = 0.5 / tex_h as f32;
300        RegionOfInterest {
301            left: (crop.left as f32 / tex_w as f32 + half_x).clamp(0.0, 1.0),
302            top: ((crop.top + crop.height) as f32 / tex_h as f32 - half_y).clamp(0.0, 1.0),
303            right: ((crop.left + crop.width) as f32 / tex_w as f32 - half_x).clamp(0.0, 1.0),
304            bottom: (crop.top as f32 / tex_h as f32 + half_y).clamp(0.0, 1.0),
305        }
306    }
307}
308
309#[cfg(all(test, target_os = "windows"))]
310mod d3d11_backend_tests {
311    use super::TransferBackend;
312
313    #[test]
314    fn d3d11_texture_is_zero_copy_and_not_dma() {
315        assert!(TransferBackend::D3d11Texture.is_zero_copy());
316        assert!(!TransferBackend::D3d11Texture.is_dma());
317    }
318}