Skip to main content

velox_engine/platform/
embed_ffi.rs

1//! 全平台零拷贝宿主嵌入统一 C ABI(`velox_engine::platform::embed_ffi`)。
2//!
3//! 为外部 UI 框架(Qt6 `QQuickRhiItem`、GTK4 `GdkDmabufTextureBuilder`、WinUI 3 `SurfaceImageSource`、
4//! WPF `D3DImage`、Android `ASurfaceTransaction`、iOS `IOSurface` 与原生合成器)提供一套统一句柄共享协议:
5//! - **GPU 零拷贝优先**:启用 `gpu`(及 `gpu-interop`)且物理 GPU 可用时,通过 [`WgpuSharedExportRenderer`] 导出
6//!   Win32 DX12 NT `HANDLE` / Linux `dma_buf` fd / Apple `IOSurfaceRef` / Android `AHardwareBuffer*` 与 GPU 同步栅栏;
7//! - **软件缓冲自动回退**:在无 GPU 环境或显式关闭 GPU 时无缝回退至 `Rgba8888` CPU 帧缓冲 + [`CDirtyRect`] 局部脏区;
8//! - **预乘透明 HUD 支持**:`transparent_bg = 1` 时背景全透明,可直接零拷贝叠加在外部应用画面之上。
9
10use std::boxed::Box;
11use std::vec;
12use std::vec::Vec;
13
14use crate::display::Rgba8888;
15use crate::element::View;
16use crate::engine::VeloxEngine;
17use crate::platform::mobile::CDirtyRect;
18use crate::pod::{InputEvent, KeyCode};
19use crate::renderers::software::rasterize_region_scaled_parallel;
20
21#[cfg(feature = "gpu")]
22use crate::renderers::wgpu::{ExportedHandle, ExternalSyncHandle, WgpuSharedExportRenderer};
23
24/// C ABI 导出的共享帧句柄类别。
25#[repr(u8)]
26#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
27pub enum VeloxHandleKind {
28    #[default]
29    None = 0,
30    Win32Dx12NtHandle = 1,
31    LinuxDmaBufFd = 2,
32    AppleIoSurface = 3,
33    AndroidHardwareBuffer = 4,
34    SoftwareRgbaPtr = 5,
35}
36
37/// C ABI 导出的 GPU 同步原语类别。
38#[repr(u8)]
39#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
40pub enum VeloxSyncKind {
41    #[default]
42    None = 0,
43    Win32Dx12FenceNtHandle = 1,
44    LinuxSemaphoreFd = 2,
45    AppleMetalSharedEvent = 3,
46    AndroidSyncFd = 4,
47}
48
49/// 宿主传入的物理显卡对齐与后端初始化配置(`#[repr(C)]`)。
50#[repr(C)]
51#[derive(Copy, Clone, Debug)]
52pub struct VeloxHostAdapterConfig {
53    /// `1` 表示 `adapter_luid` 有效(Windows DX12 同卡对齐)。
54    pub has_luid: u8,
55    /// Windows DXGI 8 字节 `AdapterLuid`。
56    pub adapter_luid: [u8; 8],
57    /// `1` 表示 `device_uuid` 有效(Linux/Android Vulkan 同卡对齐)。
58    pub has_uuid: u8,
59    /// Vulkan 16 字节 `deviceUUID`。
60    pub device_uuid: [u8; 16],
61    /// `1` 优先启用硬件 GPU 零拷贝导出,`0` 强制使用内置软件光栅器。
62    pub prefer_gpu: u8,
63    /// `1` 启用预乘 Alpha 全透明背景(用于悬浮镂空 HUD 合成),`0` 为不透明背景。
64    pub transparent_bg: u8,
65}
66
67impl Default for VeloxHostAdapterConfig {
68    fn default() -> Self {
69        Self {
70            has_luid: 0,
71            adapter_luid: [0u8; 8],
72            has_uuid: 0,
73            device_uuid: [0u8; 16],
74            prefer_gpu: 1,
75            transparent_bg: 1,
76        }
77    }
78}
79
80/// 跨语言零拷贝共享帧描述符(由宿主通过 `velox_embed_acquire_shared_frame` 获取)。
81#[repr(C)]
82#[derive(Copy, Clone, Debug)]
83pub struct VeloxSharedFrameDesc {
84    /// 表面重建代数(窗口 Resize 后递增,宿主检测到变化须重新打开共享句柄)。
85    pub generation_id: u32,
86    /// 三缓冲槽位索引(`0..3`)。
87    pub slot_index: u8,
88    /// `1` 表示本帧为新渲染完成的画面,`0` 表示复用上次最新帧。
89    pub is_fresh: u8,
90    /// 显存句柄类型(见 [`VeloxHandleKind`])。
91    pub handle_kind: u8,
92    /// 同步原语类型(见 [`VeloxSyncKind`])。
93    pub sync_kind: u8,
94    /// 物理像素宽度。
95    pub width: u32,
96    /// 物理像素高度。
97    pub height: u32,
98    /// 像素格式编码(`0 = Rgba8Unorm`,`1 = Bgra8Unorm`,均为预乘 Alpha)。
99    pub pixel_format: u32,
100    /// 跨 API 原始显存句柄(Win32 NT `HANDLE` / Linux `dma_buf` fd / `IOSurfaceRef` / `AHB*`)。
101    pub raw_handle: u64,
102    /// 跨 API GPU 同步句柄(`ID3D12Fence` NT `HANDLE` / Timeline Semaphore fd / `MTLSharedEvent`)。
103    pub sync_handle: u64,
104    /// 宿主采样前需等待的 GPU 栅栏单调计数值。
105    pub fence_value: u64,
106    /// 行步长(字节,主要用于 `LinuxDmaBufFd` 与 `SoftwareRgbaPtr`)。
107    pub stride: u32,
108    /// 平面字节偏移量。
109    pub offset: u32,
110    /// DRM FourCC(仅 Linux DMA-BUF 有效)。
111    pub drm_format: u32,
112    /// DRM Format Modifier(仅 Linux DMA-BUF 有效)。
113    pub drm_modifier: u64,
114    /// 软件光栅回退模式的 `RGBA8888` 像素缓冲指针(GPU 模式下为空指针)。
115    pub software_rgba_ptr: *const u8,
116    /// 脏矩形数组指针(三缓冲 GPU 模式下已自动做 3 帧并集合并)。
117    pub dirty_rects_ptr: *const CDirtyRect,
118    /// 脏矩形数量。
119    pub dirty_rect_count: u32,
120}
121
122impl Default for VeloxSharedFrameDesc {
123    fn default() -> Self {
124        Self {
125            generation_id: 0,
126            slot_index: 0,
127            is_fresh: 0,
128            handle_kind: VeloxHandleKind::None as u8,
129            sync_kind: VeloxSyncKind::None as u8,
130            width: 0,
131            height: 0,
132            pixel_format: 0,
133            raw_handle: 0,
134            sync_handle: 0,
135            fence_value: 0,
136            stride: 0,
137            offset: 0,
138            drm_format: 0,
139            drm_modifier: 0,
140            software_rgba_ptr: core::ptr::null(),
141            dirty_rects_ptr: core::ptr::null(),
142            dirty_rect_count: 0,
143        }
144    }
145}
146
147/// 单个可多实例并行的宿主嵌入会话(统一承载 `VeloxEngine` + GPU 共享导出器或软件缓冲回退)。
148pub struct VeloxEmbedSession {
149    pub engine: VeloxEngine,
150    scale_factor: f32,
151    phys_width: u32,
152    phys_height: u32,
153    transparent_bg: bool,
154    #[cfg(feature = "gpu")]
155    gpu_exporter: Option<WgpuSharedExportRenderer>,
156    sw_pixmap: Vec<Rgba8888>,
157    sw_rgba_bytes: Vec<u8>,
158    sw_generation: u32,
159    sw_fresh: bool,
160    dirty_rects: Vec<CDirtyRect>,
161}
162
163impl VeloxEmbedSession {
164    /// 创建一个挂载指定根视图的跨框架嵌入会话。
165    pub fn new<V: View>(
166        root_view: V,
167        logical_width: i16,
168        logical_height: i16,
169        scale_factor: f32,
170        config: VeloxHostAdapterConfig,
171    ) -> Self {
172        let lw = logical_width.max(1);
173        let lh = logical_height.max(1);
174        let sf = scale_factor.clamp(0.5, 4.0);
175        let pw = ((lw as f32) * sf).round().max(1.0) as u32;
176        let ph = ((lh as f32) * sf).round().max(1.0) as u32;
177
178        let mut engine = VeloxEngine::new(lw, lh);
179        engine.set_scale_factor(sf);
180        let _ = engine.mount_root(root_view);
181
182        #[cfg(feature = "gpu")]
183        let gpu_exporter = if config.prefer_gpu != 0 {
184            let luid = (config.has_luid != 0).then_some(config.adapter_luid);
185            let uuid = (config.has_uuid != 0).then_some(config.device_uuid);
186            WgpuSharedExportRenderer::new(pw, ph, luid, uuid).map(|mut exp| {
187                if config.transparent_bg != 0 {
188                    exp.set_clear_color(crate::renderers::wgpu::wgpu::Color::TRANSPARENT);
189                } else {
190                    exp.set_clear_color(crate::renderers::wgpu::wgpu::Color::BLACK);
191                }
192                exp
193            })
194        } else {
195            None
196        };
197
198        let sw_needed = {
199            #[cfg(feature = "gpu")]
200            {
201                gpu_exporter.is_none()
202            }
203            #[cfg(not(feature = "gpu"))]
204            {
205                true
206            }
207        };
208        let (sw_pixmap, sw_rgba_bytes) = if sw_needed {
209            let n = (pw as usize) * (ph as usize);
210            (vec![Rgba8888(0); n], vec![0u8; n * 4])
211        } else {
212            (Vec::new(), Vec::new())
213        };
214
215        Self {
216            engine,
217            scale_factor: sf,
218            phys_width: pw,
219            phys_height: ph,
220            transparent_bg: config.transparent_bg != 0,
221            #[cfg(feature = "gpu")]
222            gpu_exporter,
223            sw_pixmap,
224            sw_rgba_bytes,
225            sw_generation: 1,
226            sw_fresh: false,
227            dirty_rects: Vec::with_capacity(8),
228        }
229    }
230
231    /// 返回当前会话是否激活了 GPU 硬件共享导出后端。
232    #[inline]
233    pub fn backend_is_gpu(&self) -> bool {
234        #[cfg(feature = "gpu")]
235        {
236            self.gpu_exporter.is_some()
237        }
238        #[cfg(not(feature = "gpu"))]
239        {
240            false
241        }
242    }
243
244    /// 返回底层 GPU 共享导出器可变引用(供 Rust 宿主直接注册外部零拷贝纹理或检查句柄)。
245    #[cfg(feature = "gpu")]
246    #[inline]
247    pub fn gpu_exporter_mut(&mut self) -> Option<&mut WgpuSharedExportRenderer> {
248        self.gpu_exporter.as_mut()
249    }
250
251    /// 调整嵌入视口的逻辑尺寸与缩放因子。
252    pub fn resize(&mut self, logical_width: i16, logical_height: i16, scale_factor: f32) {
253        let lw = logical_width.max(1);
254        let lh = logical_height.max(1);
255        let sf = scale_factor.clamp(0.5, 4.0);
256        let pw = ((lw as f32) * sf).round().max(1.0) as u32;
257        let ph = ((lh as f32) * sf).round().max(1.0) as u32;
258        self.scale_factor = sf;
259        self.engine.set_scale_factor(sf);
260        self.engine.resize(lw, lh);
261        if pw != self.phys_width || ph != self.phys_height {
262            self.phys_width = pw;
263            self.phys_height = ph;
264            #[cfg(feature = "gpu")]
265            if let Some(exp) = &mut self.gpu_exporter {
266                exp.resize(pw, ph);
267            }
268            if !self.backend_is_gpu() {
269                let n = (pw as usize) * (ph as usize);
270                self.sw_pixmap.resize(n, Rgba8888(0));
271                self.sw_rgba_bytes.resize(n * 4, 0);
272                self.sw_generation = self.sw_generation.wrapping_add(1).max(1);
273            }
274        }
275    }
276
277    /// 推进一帧动画与布局求解,并将有变化的画面提交至 GPU 共享槽或软件回退缓冲;返回是否有新帧产出。
278    pub fn step_frame(&mut self, dt_ms: u16) -> bool {
279        #[cfg(feature = "gpu")]
280        if let Some(exp) = &mut self.gpu_exporter {
281            return exp.step_and_render(&mut self.engine, dt_ms).is_some();
282        }
283
284        let dirty_slice = self.engine.step_frame_dt(dt_ms);
285        if dirty_slice.is_empty() {
286            return false;
287        }
288        let mut dirty_copy = Vec::with_capacity(dirty_slice.len());
289        self.dirty_rects.clear();
290        for &r in dirty_slice {
291            dirty_copy.push(r);
292            self.dirty_rects.push(CDirtyRect {
293                x: r.x,
294                y: r.y,
295                w: r.w,
296                h: r.h,
297            });
298        }
299
300        let vp = self.engine.viewport_region();
301        let ops = self.engine.cached_draw_ops();
302        let w = self.phys_width as usize;
303        if self.transparent_bg {
304            for px in &mut self.sw_pixmap {
305                *px = Rgba8888(0);
306            }
307        }
308        for reg in &dirty_copy {
309            if !reg.is_empty() {
310                rasterize_region_scaled_parallel(
311                    ops,
312                    vp,
313                    self.scale_factor,
314                    *reg,
315                    0,
316                    0,
317                    w,
318                    &mut self.sw_pixmap,
319                );
320            }
321        }
322        for (dst, px) in self
323            .sw_rgba_bytes
324            .chunks_exact_mut(4)
325            .zip(self.sw_pixmap.iter())
326        {
327            dst.copy_from_slice(&px.to_rgba_bytes());
328        }
329        self.sw_fresh = true;
330        true
331    }
332
333    /// 宿主获取最新共享帧描述(GPU 模式返回零拷贝句柄,软件模式返回 CPU RGBA 缓冲指针)。
334    pub fn acquire_shared_frame(&mut self) -> VeloxSharedFrameDesc {
335        #[cfg(feature = "gpu")]
336        if let Some(exp) = &self.gpu_exporter {
337            let lease = exp.acquire_shared_frame();
338            self.dirty_rects.clear();
339            for &r in lease.dirty_rects.as_slice() {
340                self.dirty_rects.push(CDirtyRect {
341                    x: r.x,
342                    y: r.y,
343                    w: r.w,
344                    h: r.h,
345                });
346            }
347            let (handle_kind, stride, offset, drm_format, drm_modifier) = match lease.handle {
348                ExportedHandle::Win32Dx12NtHandle { .. } => {
349                    (VeloxHandleKind::Win32Dx12NtHandle, lease.width * 4, 0, 0, 0)
350                }
351                ExportedHandle::LinuxDmaBuf {
352                    stride,
353                    offset,
354                    drm_format,
355                    modifier,
356                    ..
357                } => (
358                    VeloxHandleKind::LinuxDmaBufFd,
359                    stride,
360                    offset,
361                    drm_format,
362                    modifier,
363                ),
364                ExportedHandle::AppleIoSurface { .. } => {
365                    (VeloxHandleKind::AppleIoSurface, lease.width * 4, 0, 0, 0)
366                }
367                ExportedHandle::AndroidHardwareBuffer { .. } => (
368                    VeloxHandleKind::AndroidHardwareBuffer,
369                    lease.width * 4,
370                    0,
371                    0,
372                    0,
373                ),
374                ExportedHandle::InternalOnly => (VeloxHandleKind::None, lease.width * 4, 0, 0, 0),
375            };
376            let sync_kind = match lease.sync_handle {
377                ExternalSyncHandle::Win32Dx12FenceNtHandle(_) => {
378                    VeloxSyncKind::Win32Dx12FenceNtHandle
379                }
380                ExternalSyncHandle::LinuxSemaphoreFd(_) => VeloxSyncKind::LinuxSemaphoreFd,
381                ExternalSyncHandle::AppleMetalSharedEvent(_) => {
382                    VeloxSyncKind::AppleMetalSharedEvent
383                }
384                ExternalSyncHandle::AndroidSyncFd(_) => VeloxSyncKind::AndroidSyncFd,
385                ExternalSyncHandle::None => VeloxSyncKind::None,
386            };
387            let pixel_format = if lease.format == crate::renderers::wgpu::wgpu::TextureFormat::Bgra8Unorm {
388                1
389            } else {
390                0
391            };
392            return VeloxSharedFrameDesc {
393                generation_id: lease.generation_id,
394                slot_index: lease.slot_index,
395                is_fresh: if lease.is_fresh { 1 } else { 0 },
396                handle_kind: handle_kind as u8,
397                sync_kind: sync_kind as u8,
398                width: lease.width,
399                height: lease.height,
400                pixel_format,
401                raw_handle: lease.handle.raw_u64(),
402                sync_handle: lease.sync_handle.raw_u64(),
403                fence_value: lease.fence_value,
404                stride,
405                offset,
406                drm_format,
407                drm_modifier,
408                software_rgba_ptr: core::ptr::null(),
409                dirty_rects_ptr: self.dirty_rects.as_ptr(),
410                dirty_rect_count: self.dirty_rects.len() as u32,
411            };
412        }
413
414        let is_fresh = self.sw_fresh;
415        self.sw_fresh = false;
416        VeloxSharedFrameDesc {
417            generation_id: self.sw_generation,
418            slot_index: 0,
419            is_fresh: if is_fresh { 1 } else { 0 },
420            handle_kind: VeloxHandleKind::SoftwareRgbaPtr as u8,
421            sync_kind: VeloxSyncKind::None as u8,
422            width: self.phys_width,
423            height: self.phys_height,
424            pixel_format: 0,
425            raw_handle: 0,
426            sync_handle: 0,
427            fence_value: 0,
428            stride: self.phys_width * 4,
429            offset: 0,
430            drm_format: 0,
431            drm_modifier: 0,
432            software_rgba_ptr: self.sw_rgba_bytes.as_ptr(),
433            dirty_rects_ptr: self.dirty_rects.as_ptr(),
434            dirty_rect_count: self.dirty_rects.len() as u32,
435        }
436    }
437
438    /// 宿主归还已完成采样的共享帧租约(驱动旧 Resize 显存池安全回收)。
439    pub fn release_shared_frame(&mut self, generation_id: u32, slot_index: u8) {
440        #[cfg(feature = "gpu")]
441        if let Some(exp) = &mut self.gpu_exporter {
442            exp.release_shared_frame(generation_id, slot_index);
443        }
444        let _ = (generation_id, slot_index);
445    }
446
447    /// 注入指针事件(`phase`: `0=Down`, `1=Move`, `2=Up`, `3=Cancel`)。
448    pub fn inject_pointer(&mut self, phase: u8, x: i16, y: i16) -> bool {
449        match phase {
450            0 => self.engine.dispatch_pointer_down(x, y),
451            1 => self.engine.dispatch_pointer_move(x, y),
452            2 => self.engine.dispatch_pointer_up(x, y),
453            _ => {
454                self.engine.dispatch_pointer_up(x, y);
455                true
456            }
457        }
458    }
459
460    /// 注入滚轮事件(正值向下、负值向上)。
461    pub fn inject_wheel(&mut self, x: i16, y: i16, delta_y: i16) -> bool {
462        self.engine
463            .dispatch_event(InputEvent::Scroll { x, y, delta_y })
464    }
465
466    /// 注入键盘事件(`is_char == 1` 时按 Unicode 码点派发字符键;否则按标准键码派发导航键)。
467    pub fn inject_key(&mut self, code: u32, is_char: bool) -> bool {
468        if is_char {
469            if let Some(ch) = char::from_u32(code) {
470                return self.engine.dispatch_key(KeyCode::Char(ch));
471            }
472            return false;
473        }
474        let key = match code {
475            9 => KeyCode::Tab,
476            13 => KeyCode::Enter,
477            27 => KeyCode::Escape,
478            8 => KeyCode::Backspace,
479            46 => KeyCode::Delete,
480            37 => KeyCode::Left,
481            38 => KeyCode::Up,
482            39 => KeyCode::Right,
483            40 => KeyCode::Down,
484            36 => KeyCode::Home,
485            35 => KeyCode::End,
486            _ => return false,
487        };
488        self.engine.dispatch_key(key)
489    }
490}
491
492// ============================================================================
493// C ABI 导出符号(供 Qt6 / GTK4 / WinUI 3 / WPF / C++ / C# / Swift / Kotlin 调用)
494// ============================================================================
495
496/// 查询嵌入会话是否处于 GPU 零拷贝共享导出模式(`1 = GPU`,`0 = Software`)。
497#[unsafe(no_mangle)]
498pub unsafe extern "C" fn velox_embed_backend_is_gpu(session: *const VeloxEmbedSession) -> u8 {
499    let Some(s) = (unsafe { session.as_ref() }) else {
500        return 0;
501    };
502    if s.backend_is_gpu() { 1 } else { 0 }
503}
504
505/// 调整嵌入会话逻辑尺寸与 HiDPI 缩放比例。
506#[unsafe(no_mangle)]
507pub unsafe extern "C" fn velox_embed_resize(
508    session: *mut VeloxEmbedSession,
509    logical_width: i16,
510    logical_height: i16,
511    scale_factor: f32,
512) {
513    if let Some(s) = unsafe { session.as_mut() } {
514        s.resize(logical_width, logical_height, scale_factor);
515    }
516}
517
518/// 推进一帧嵌入引擎并提交渲染(返回 `1` 表示有新画面产出,`0` 表示静止零重绘)。
519#[unsafe(no_mangle)]
520pub unsafe extern "C" fn velox_embed_step_frame(
521    session: *mut VeloxEmbedSession,
522    dt_ms: u16,
523) -> u8 {
524    let Some(s) = (unsafe { session.as_mut() }) else {
525        return 0;
526    };
527    if s.step_frame(dt_ms) { 1 } else { 0 }
528}
529
530/// 宿主获取当前最新共享显存帧句柄(GPU 模式零拷贝,无 GPU 时返回 CPU RGBA 回退指针)。
531#[unsafe(no_mangle)]
532pub unsafe extern "C" fn velox_embed_acquire_shared_frame(
533    session: *mut VeloxEmbedSession,
534    out_frame: *mut VeloxSharedFrameDesc,
535) -> u8 {
536    let (Some(s), Some(out)) = (unsafe { session.as_mut() }, unsafe { out_frame.as_mut() }) else {
537        return 0;
538    };
539    *out = s.acquire_shared_frame();
540    1
541}
542
543/// 宿主归还已完成采样的共享帧租约。
544#[unsafe(no_mangle)]
545pub unsafe extern "C" fn velox_embed_release_shared_frame(
546    session: *mut VeloxEmbedSession,
547    generation_id: u32,
548    slot_index: u8,
549) {
550    if let Some(s) = unsafe { session.as_mut() } {
551        s.release_shared_frame(generation_id, slot_index);
552    }
553}
554
555/// 向嵌入会话注入指针输入事件。
556#[unsafe(no_mangle)]
557pub unsafe extern "C" fn velox_embed_inject_pointer(
558    session: *mut VeloxEmbedSession,
559    phase: u8,
560    x: i16,
561    y: i16,
562) -> u8 {
563    let Some(s) = (unsafe { session.as_mut() }) else {
564        return 0;
565    };
566    if s.inject_pointer(phase, x, y) { 1 } else { 0 }
567}
568
569/// 向嵌入会话注入滚轮滚动事件。
570#[unsafe(no_mangle)]
571pub unsafe extern "C" fn velox_embed_inject_wheel(
572    session: *mut VeloxEmbedSession,
573    x: i16,
574    y: i16,
575    delta_y: i16,
576) -> u8 {
577    let Some(s) = (unsafe { session.as_mut() }) else {
578        return 0;
579    };
580    if s.inject_wheel(x, y, delta_y) { 1 } else { 0 }
581}
582
583/// 向嵌入会话注入键盘按键事件。
584#[unsafe(no_mangle)]
585pub unsafe extern "C" fn velox_embed_inject_key(
586    session: *mut VeloxEmbedSession,
587    code: u32,
588    is_char: u8,
589) -> u8 {
590    let Some(s) = (unsafe { session.as_mut() }) else {
591        return 0;
592    };
593    if s.inject_key(code, is_char != 0) { 1 } else { 0 }
594}
595
596/// 销毁由 `Box::into_raw(Box::new(VeloxEmbedSession::new(...)))` 创建的嵌入会话。
597#[unsafe(no_mangle)]
598pub unsafe extern "C" fn velox_embed_destroy(session: *mut VeloxEmbedSession) {
599    if !session.is_null() {
600        unsafe {
601            drop(Box::from_raw(session));
602        }
603    }
604}
605
606/// 供 Qt6 / GTK4 / WinUI 3 / WPF / C++ / Swift 宿主直接引用的标准 C 头文件模板。
607pub const VELOX_EMBED_HEADER_H: &str = r#"#pragma once
608#include <stdint.h>
609
610#ifdef __cplusplus
611extern "C" {
612#endif
613
614typedef struct VeloxEmbedSession VeloxEmbedSession;
615
616typedef struct VeloxDirtyRect {
617    int16_t x;
618    int16_t y;
619    int16_t w;
620    int16_t h;
621} VeloxDirtyRect;
622
623typedef enum VeloxHandleKind {
624    VELOX_HANDLE_NONE = 0,
625    VELOX_HANDLE_WIN32_DX12_NT = 1,
626    VELOX_HANDLE_LINUX_DMABUF_FD = 2,
627    VELOX_HANDLE_APPLE_IOSURFACE = 3,
628    VELOX_HANDLE_ANDROID_AHB = 4,
629    VELOX_HANDLE_SOFTWARE_RGBA_PTR = 5,
630} VeloxHandleKind;
631
632typedef enum VeloxSyncKind {
633    VELOX_SYNC_NONE = 0,
634    VELOX_SYNC_WIN32_DX12_FENCE_NT = 1,
635    VELOX_SYNC_LINUX_SEMAPHORE_FD = 2,
636    VELOX_SYNC_APPLE_METAL_SHARED_EVENT = 3,
637    VELOX_SYNC_ANDROID_SYNC_FD = 4,
638} VeloxSyncKind;
639
640typedef struct VeloxHostAdapterConfig {
641    uint8_t has_luid;
642    uint8_t adapter_luid[8];
643    uint8_t has_uuid;
644    uint8_t device_uuid[16];
645    uint8_t prefer_gpu;
646    uint8_t transparent_bg;
647} VeloxHostAdapterConfig;
648
649typedef struct VeloxSharedFrameDesc {
650    uint32_t generation_id;
651    uint8_t slot_index;
652    uint8_t is_fresh;
653    uint8_t handle_kind;
654    uint8_t sync_kind;
655    uint32_t width;
656    uint32_t height;
657    uint32_t pixel_format;
658    uint64_t raw_handle;
659    uint64_t sync_handle;
660    uint64_t fence_value;
661    uint32_t stride;
662    uint32_t offset;
663    uint32_t drm_format;
664    uint64_t drm_modifier;
665    const uint8_t* software_rgba_ptr;
666    const VeloxDirtyRect* dirty_rects_ptr;
667    uint32_t dirty_rect_count;
668} VeloxSharedFrameDesc;
669
670uint8_t velox_embed_backend_is_gpu(const VeloxEmbedSession* session);
671void    velox_embed_resize(VeloxEmbedSession* session, int16_t logical_width, int16_t logical_height, float scale_factor);
672uint8_t velox_embed_step_frame(VeloxEmbedSession* session, uint16_t dt_ms);
673uint8_t velox_embed_acquire_shared_frame(VeloxEmbedSession* session, VeloxSharedFrameDesc* out_frame);
674void    velox_embed_release_shared_frame(VeloxEmbedSession* session, uint32_t generation_id, uint8_t slot_index);
675uint8_t velox_embed_inject_pointer(VeloxEmbedSession* session, uint8_t phase, int16_t x, int16_t y);
676uint8_t velox_embed_inject_wheel(VeloxEmbedSession* session, int16_t x, int16_t y, int16_t delta_y);
677uint8_t velox_embed_inject_key(VeloxEmbedSession* session, uint32_t code, uint8_t is_char);
678void    velox_embed_destroy(VeloxEmbedSession* session);
679
680#ifdef __cplusplus
681}
682#endif
683"#;