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// CUDA test policy: turns a vacuous CUDA skip into a required-coverage
76// failure under HAL_TEST_REQUIRE_CUDA=1. Test-only -- every item in it is
77// consumed by `tests.rs` under #[cfg(test)] and by its own unit tests, so an
78// ungated module would be empty (and dead-code-flagged) in a release build.
79#[cfg(test)]
80mod cuda_policy;
81// `EGL_ANGLE_image_d3d11_texture` attribute assembly (pure); consumed by the
82// Windows leaf (`platform/windows.rs`) to build the EGLImage import target.
83#[cfg(target_os = "windows")]
84pub(super) mod d3d11_import;
85#[cfg(target_os = "linux")]
86mod fourcc;
87#[cfg(any(target_os = "macos", target_os = "ios"))]
88mod iosurface_import;
89#[cfg(target_os = "android")]
90mod native_fence;
91mod platform;
92mod processor;
93mod resources;
94mod shaders;
95mod shaders_common;
96// Engine GL tests, in three tiers (see crates/image/TESTING.md):
97//   portable                       — run on Linux AND macOS/ANGLE
98//   cfg(target_os = "linux")       — display probing, PBO/CUDA paths
99//   cfg(all(linux, dma_test_formats)) — DMA-BUF import/pool specifics
100// Per-item cfg gates inside the module select the tier; the mount
101// itself is unconditional so the macOS lane runs the portable tier.
102mod tests;
103mod threaded;
104
105#[cfg(target_os = "linux")]
106pub use context::probe_egl_displays;
107// These are accessed by sibling sub-modules via `super::context::` directly.
108// No re-export needed at the mod.rs level.
109pub use cache::{CacheStats, ConvertStats, GlCacheStats};
110pub use threaded::GLProcessorThreaded;
111
112/// Dynamically-loaded EGL 1.4 instance. The lifetime parameter is
113/// `'static` because the underlying `libloading::Library` is intentionally
114/// leaked at first load (see `EGL_LIB` in `context.rs` and the equivalent
115/// on macOS — drivers may retain internal state past explicit cleanup, so
116/// dlclose can SIGBUS on process exit).
117///
118/// Defined here at the `gl` module root so the `platform/` trait and both
119/// platform implementations can name it without dragging in a cross-cfg
120/// re-export. The Linux `context.rs` and the macOS `platform/macos.rs`
121/// both use this same alias.
122pub(super) type Egl = edgefirst_egl::Instance<
123    edgefirst_egl::Dynamic<&'static libloading::Library, edgefirst_egl::EGL1_4>,
124>;
125
126/// Handle returned by `GlPlatform::export_completion_fence` (and surfaced
127/// by `convert_with_fence`): a sync_file fd on Unix
128/// (`EGL_ANDROID_native_fence_sync`), an event NT handle on Windows, set
129/// when the D3D11 device fence reaches the value the convert queued.
130/// Keeps the engine free of `cfg` branches (precedent: `BlobFd` in
131/// `crates/tensor/src/blob.rs`).
132#[cfg(unix)]
133pub type CompletionFence = std::os::fd::OwnedFd;
134#[cfg(windows)]
135pub type CompletionFence = std::os::windows::io::OwnedHandle;
136
137/// Identifies the type of EGL display used for headless OpenGL ES rendering.
138///
139/// The HAL creates a surfaceless GLES 3.0 context
140/// (`EGL_KHR_surfaceless_context` + `EGL_KHR_no_config_context`) and
141/// renders exclusively through FBOs backed by EGLImages imported from
142/// DMA-buf file descriptors. No window or PBuffer surface is created.
143///
144/// Displays are probed in priority order: PlatformDevice first (zero
145/// external dependencies), then GBM, then Default. Use
146/// [`probe_egl_displays`] to discover which are available and
147/// [`ImageProcessorConfig::egl_display`](crate::ImageProcessorConfig::egl_display)
148/// to override the auto-detection.
149///
150/// # Display Types
151///
152/// - **`PlatformDevice`** — Uses `EGL_EXT_device_enumeration` to query
153///   available EGL devices via `eglQueryDevicesEXT`, then selects the first
154///   device with `eglGetPlatformDisplay(EGL_EXT_platform_device, ...)`.
155///   Headless and compositor-free with zero external library dependencies.
156///   Works on NVIDIA GPUs and newer Vivante drivers.
157///
158/// - **`Gbm`** — Opens a DRM render node (e.g. `/dev/dri/renderD128`) and
159///   creates a GBM (Generic Buffer Manager) device, then calls
160///   `eglGetPlatformDisplay(EGL_PLATFORM_GBM_KHR, gbm_device)`. Requires
161///   `libgbm` and a DRM render node. Needed on ARM Mali (i.MX95) and older
162///   Vivante drivers that do not expose `EGL_EXT_platform_device`.
163///
164/// - **`Default`** — Calls `eglGetDisplay(EGL_DEFAULT_DISPLAY)`, letting the
165///   EGL implementation choose the display. On Wayland systems this connects
166///   to the compositor; on X11 it connects to the X server. May block on
167///   headless systems where a compositor is expected but not running.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
169pub enum EglDisplayKind {
170    Gbm,
171    PlatformDevice,
172    Default,
173}
174
175impl std::fmt::Display for EglDisplayKind {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        match self {
178            EglDisplayKind::Gbm => write!(f, "GBM"),
179            EglDisplayKind::PlatformDevice => write!(f, "PlatformDevice"),
180            EglDisplayKind::Default => write!(f, "Default"),
181        }
182    }
183}
184
185/// A validated, available EGL display discovered by [`probe_egl_displays`].
186#[derive(Debug, Clone)]
187pub struct EglDisplayInfo {
188    /// The type of EGL display.
189    pub kind: EglDisplayKind,
190    /// Human-readable description for logging/diagnostics
191    /// (e.g. "GBM via /dev/dri/renderD128").
192    pub description: String,
193}
194
195/// Tracks which data-transfer method is active for moving pixels
196/// between CPU memory and GPU textures/framebuffers.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub(crate) enum TransferBackend {
199    /// Zero-copy via EGLImage imported from DMA-buf file descriptors.
200    /// Available on i.MX8 (Vivante), i.MX95 (Mali), Jetson, and any
201    /// platform where `EGL_EXT_image_dma_buf_import` is present AND
202    /// the GPU can actually render through DMA-buf-backed textures.
203    DmaBuf,
204
205    /// Zero-copy via `EGL_ANGLE_iosurface_client_buffer` (macOS/iOS).
206    /// Available when ANGLE's Metal backend is loaded and the EGL
207    /// extension is advertised. The IOSurface is wrapped as an EGL
208    /// pbuffer and bound to a 2D texture via `eglBindTexImage`.
209    #[cfg(any(target_os = "macos", target_os = "ios"))]
210    IOSurface,
211
212    /// Zero-copy via `EGL_ANDROID_image_native_buffer` (Android). The
213    /// AHardwareBuffer is wrapped as an EGLImage via
214    /// `eglGetNativeClientBufferANDROID` → `eglCreateImageKHR` and bound
215    /// to a 2D texture via `glEGLImageTargetTexture2DOES` — persistent
216    /// bindings, like Linux DMA-BUF (unlike the per-pass IOSurface
217    /// pbuffer binds).
218    #[cfg(target_os = "android")]
219    AHardwareBuffer,
220
221    /// Zero-copy via `EGL_ANGLE_image_d3d11_texture` (Windows): the tensor's
222    /// `ID3D11Texture2D` wrapped as an EGLImage and bound with
223    /// `glEGLImageTargetTexture2DOES`. Unlike Linux and Android the binding
224    /// is re-issued per use, because ANGLE does not observe writes made to
225    /// the texture outside GL (see `AngleD3d11::PERSISTENT_TEX_BINDINGS`).
226    #[cfg(target_os = "windows")]
227    D3d11Texture,
228
229    /// GPU buffer via Pixel Buffer Object. Used when DMA-buf is unavailable
230    /// but OpenGL is present. Data stays in GPU-accessible memory. Windows
231    /// took this path until the D3D11 texture import landed and now reports
232    /// [`TransferBackend::D3d11Texture`]; PBO destinations still exist there
233    /// as `TensorMemory::Pbo` tensors.
234    Pbo,
235
236    /// Synchronous `glTexSubImage2D` upload + `glReadPixels` readback.
237    /// Used when DMA-buf is unavailable or when the DMA-buf verification
238    /// probe fails (e.g. NVIDIA discrete GPUs where EGLImage creation
239    /// succeeds but rendered data is all zeros).
240    Sync,
241}
242
243impl TransferBackend {
244    /// Returns `true` if DMA-buf zero-copy is available.
245    pub(crate) fn is_dma(self) -> bool {
246        self == TransferBackend::DmaBuf
247    }
248
249    /// Returns `true` if the platform can import `TensorMemory::DmaBuf`
250    /// tensors zero-copy: DMA-BUF EGLImages on Linux, IOSurface pbuffers
251    /// on macOS. Path-selection sites use this; probes that are
252    /// specifically about DMA-BUF semantics (e.g. the render-roundtrip
253    /// verification) keep `is_dma`.
254    pub(crate) fn is_zero_copy(self) -> bool {
255        #[cfg(any(target_os = "macos", target_os = "ios"))]
256        if self == TransferBackend::IOSurface {
257            return true;
258        }
259        #[cfg(target_os = "android")]
260        if self == TransferBackend::AHardwareBuffer {
261            return true;
262        }
263        #[cfg(target_os = "windows")]
264        if self == TransferBackend::D3d11Texture {
265            return true;
266        }
267        self == TransferBackend::DmaBuf
268    }
269}
270
271/// Interpolation mode for int8 proto textures (GL_R8I cannot use GL_LINEAR).
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum Int8InterpolationMode {
274    /// texelFetch at nearest texel — simplest, fastest GPU execution.
275    Nearest,
276    /// texelFetch × 4 neighbors with shader-computed bilinear weights (default).
277    Bilinear,
278    /// Two-pass: dequant int8→f16 FBO, then existing f16 shader with GL_LINEAR.
279    TwoPass,
280}
281
282/// A rectangular region of interest expressed as normalised [0, 1] coordinates.
283#[derive(Debug, Clone, Copy)]
284pub(super) struct RegionOfInterest {
285    pub(super) left: f32,
286    pub(super) top: f32,
287    pub(super) right: f32,
288    pub(super) bottom: f32,
289}
290
291impl RegionOfInterest {
292    /// Build a source ROI from a pixel-space crop rectangle with a half-texel
293    /// inset. The inset ensures that `GL_LINEAR` filtering never samples
294    /// outside the crop boundary — at the extreme texture coordinates the
295    /// bilinear kernel is centred on the boundary texel and cannot reach
296    /// adjacent padding pixels.
297    ///
298    /// The result is clamped to [0, 1] so an out-of-bounds crop rectangle
299    /// cannot produce invalid texture coordinates.
300    ///
301    /// `crop`: pixel-space rectangle (left, top, width, height).
302    /// `tex_w`, `tex_h`: full texture dimensions in pixels.
303    pub(super) fn from_crop_clamped(crop: &crate::Rect, tex_w: usize, tex_h: usize) -> Self {
304        let half_x = 0.5 / tex_w as f32;
305        let half_y = 0.5 / tex_h as f32;
306        RegionOfInterest {
307            left: (crop.left as f32 / tex_w as f32 + half_x).clamp(0.0, 1.0),
308            top: ((crop.top + crop.height) as f32 / tex_h as f32 - half_y).clamp(0.0, 1.0),
309            right: ((crop.left + crop.width) as f32 / tex_w as f32 - half_x).clamp(0.0, 1.0),
310            bottom: (crop.top as f32 / tex_h as f32 + half_y).clamp(0.0, 1.0),
311        }
312    }
313}
314
315#[cfg(all(test, target_os = "windows"))]
316mod d3d11_backend_tests {
317    use super::TransferBackend;
318
319    #[test]
320    fn d3d11_texture_is_zero_copy_and_not_dma() {
321        assert!(TransferBackend::D3d11Texture.is_zero_copy());
322        assert!(!TransferBackend::D3d11Texture.is_dma());
323    }
324}