use std::boxed::Box;
use std::vec;
use std::vec::Vec;
use crate::display::Rgba8888;
use crate::element::View;
use crate::engine::VeloxEngine;
use crate::platform::mobile::CDirtyRect;
use crate::pod::{InputEvent, KeyCode};
use crate::renderers::software::rasterize_region_scaled_parallel;
#[cfg(feature = "gpu")]
use crate::renderers::wgpu::{ExportedHandle, ExternalSyncHandle, WgpuSharedExportRenderer};
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum VeloxHandleKind {
#[default]
None = 0,
Win32Dx12NtHandle = 1,
LinuxDmaBufFd = 2,
AppleIoSurface = 3,
AndroidHardwareBuffer = 4,
SoftwareRgbaPtr = 5,
}
#[repr(u8)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum VeloxSyncKind {
#[default]
None = 0,
Win32Dx12FenceNtHandle = 1,
LinuxSemaphoreFd = 2,
AppleMetalSharedEvent = 3,
AndroidSyncFd = 4,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct VeloxHostAdapterConfig {
pub has_luid: u8,
pub adapter_luid: [u8; 8],
pub has_uuid: u8,
pub device_uuid: [u8; 16],
pub prefer_gpu: u8,
pub transparent_bg: u8,
}
impl Default for VeloxHostAdapterConfig {
fn default() -> Self {
Self {
has_luid: 0,
adapter_luid: [0u8; 8],
has_uuid: 0,
device_uuid: [0u8; 16],
prefer_gpu: 1,
transparent_bg: 1,
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct VeloxSharedFrameDesc {
pub generation_id: u32,
pub slot_index: u8,
pub is_fresh: u8,
pub handle_kind: u8,
pub sync_kind: u8,
pub width: u32,
pub height: u32,
pub pixel_format: u32,
pub raw_handle: u64,
pub sync_handle: u64,
pub fence_value: u64,
pub stride: u32,
pub offset: u32,
pub drm_format: u32,
pub drm_modifier: u64,
pub software_rgba_ptr: *const u8,
pub dirty_rects_ptr: *const CDirtyRect,
pub dirty_rect_count: u32,
}
impl Default for VeloxSharedFrameDesc {
fn default() -> Self {
Self {
generation_id: 0,
slot_index: 0,
is_fresh: 0,
handle_kind: VeloxHandleKind::None as u8,
sync_kind: VeloxSyncKind::None as u8,
width: 0,
height: 0,
pixel_format: 0,
raw_handle: 0,
sync_handle: 0,
fence_value: 0,
stride: 0,
offset: 0,
drm_format: 0,
drm_modifier: 0,
software_rgba_ptr: core::ptr::null(),
dirty_rects_ptr: core::ptr::null(),
dirty_rect_count: 0,
}
}
}
pub struct VeloxEmbedSession {
pub engine: VeloxEngine,
scale_factor: f32,
phys_width: u32,
phys_height: u32,
transparent_bg: bool,
#[cfg(feature = "gpu")]
gpu_exporter: Option<WgpuSharedExportRenderer>,
sw_pixmap: Vec<Rgba8888>,
sw_rgba_bytes: Vec<u8>,
sw_generation: u32,
sw_fresh: bool,
dirty_rects: Vec<CDirtyRect>,
}
impl VeloxEmbedSession {
pub fn new<V: View>(
root_view: V,
logical_width: i16,
logical_height: i16,
scale_factor: f32,
config: VeloxHostAdapterConfig,
) -> Self {
let lw = logical_width.max(1);
let lh = logical_height.max(1);
let sf = scale_factor.clamp(0.5, 4.0);
let pw = ((lw as f32) * sf).round().max(1.0) as u32;
let ph = ((lh as f32) * sf).round().max(1.0) as u32;
let mut engine = VeloxEngine::new(lw, lh);
engine.set_scale_factor(sf);
let _ = engine.mount_root(root_view);
#[cfg(feature = "gpu")]
let gpu_exporter = if config.prefer_gpu != 0 {
let luid = (config.has_luid != 0).then_some(config.adapter_luid);
let uuid = (config.has_uuid != 0).then_some(config.device_uuid);
WgpuSharedExportRenderer::new(pw, ph, luid, uuid).map(|mut exp| {
if config.transparent_bg != 0 {
exp.set_clear_color(crate::renderers::wgpu::wgpu::Color::TRANSPARENT);
} else {
exp.set_clear_color(crate::renderers::wgpu::wgpu::Color::BLACK);
}
exp
})
} else {
None
};
let sw_needed = {
#[cfg(feature = "gpu")]
{
gpu_exporter.is_none()
}
#[cfg(not(feature = "gpu"))]
{
true
}
};
let (sw_pixmap, sw_rgba_bytes) = if sw_needed {
let n = (pw as usize) * (ph as usize);
(vec![Rgba8888(0); n], vec![0u8; n * 4])
} else {
(Vec::new(), Vec::new())
};
Self {
engine,
scale_factor: sf,
phys_width: pw,
phys_height: ph,
transparent_bg: config.transparent_bg != 0,
#[cfg(feature = "gpu")]
gpu_exporter,
sw_pixmap,
sw_rgba_bytes,
sw_generation: 1,
sw_fresh: false,
dirty_rects: Vec::with_capacity(8),
}
}
#[inline]
pub fn backend_is_gpu(&self) -> bool {
#[cfg(feature = "gpu")]
{
self.gpu_exporter.is_some()
}
#[cfg(not(feature = "gpu"))]
{
false
}
}
#[cfg(feature = "gpu")]
#[inline]
pub fn gpu_exporter_mut(&mut self) -> Option<&mut WgpuSharedExportRenderer> {
self.gpu_exporter.as_mut()
}
pub fn resize(&mut self, logical_width: i16, logical_height: i16, scale_factor: f32) {
let lw = logical_width.max(1);
let lh = logical_height.max(1);
let sf = scale_factor.clamp(0.5, 4.0);
let pw = ((lw as f32) * sf).round().max(1.0) as u32;
let ph = ((lh as f32) * sf).round().max(1.0) as u32;
self.scale_factor = sf;
self.engine.set_scale_factor(sf);
self.engine.resize(lw, lh);
if pw != self.phys_width || ph != self.phys_height {
self.phys_width = pw;
self.phys_height = ph;
#[cfg(feature = "gpu")]
if let Some(exp) = &mut self.gpu_exporter {
exp.resize(pw, ph);
}
if !self.backend_is_gpu() {
let n = (pw as usize) * (ph as usize);
self.sw_pixmap.resize(n, Rgba8888(0));
self.sw_rgba_bytes.resize(n * 4, 0);
self.sw_generation = self.sw_generation.wrapping_add(1).max(1);
}
}
}
pub fn step_frame(&mut self, dt_ms: u16) -> bool {
#[cfg(feature = "gpu")]
if let Some(exp) = &mut self.gpu_exporter {
return exp.step_and_render(&mut self.engine, dt_ms).is_some();
}
let dirty_slice = self.engine.step_frame_dt(dt_ms);
if dirty_slice.is_empty() {
return false;
}
let mut dirty_copy = Vec::with_capacity(dirty_slice.len());
self.dirty_rects.clear();
for &r in dirty_slice {
dirty_copy.push(r);
self.dirty_rects.push(CDirtyRect {
x: r.x,
y: r.y,
w: r.w,
h: r.h,
});
}
let vp = self.engine.viewport_region();
let ops = self.engine.cached_draw_ops();
let w = self.phys_width as usize;
if self.transparent_bg {
for px in &mut self.sw_pixmap {
*px = Rgba8888(0);
}
}
for reg in &dirty_copy {
if !reg.is_empty() {
rasterize_region_scaled_parallel(
ops,
vp,
self.scale_factor,
*reg,
0,
0,
w,
&mut self.sw_pixmap,
);
}
}
for (dst, px) in self
.sw_rgba_bytes
.chunks_exact_mut(4)
.zip(self.sw_pixmap.iter())
{
dst.copy_from_slice(&px.to_rgba_bytes());
}
self.sw_fresh = true;
true
}
pub fn acquire_shared_frame(&mut self) -> VeloxSharedFrameDesc {
#[cfg(feature = "gpu")]
if let Some(exp) = &self.gpu_exporter {
let lease = exp.acquire_shared_frame();
self.dirty_rects.clear();
for &r in lease.dirty_rects.as_slice() {
self.dirty_rects.push(CDirtyRect {
x: r.x,
y: r.y,
w: r.w,
h: r.h,
});
}
let (handle_kind, stride, offset, drm_format, drm_modifier) = match lease.handle {
ExportedHandle::Win32Dx12NtHandle { .. } => {
(VeloxHandleKind::Win32Dx12NtHandle, lease.width * 4, 0, 0, 0)
}
ExportedHandle::LinuxDmaBuf {
stride,
offset,
drm_format,
modifier,
..
} => (
VeloxHandleKind::LinuxDmaBufFd,
stride,
offset,
drm_format,
modifier,
),
ExportedHandle::AppleIoSurface { .. } => {
(VeloxHandleKind::AppleIoSurface, lease.width * 4, 0, 0, 0)
}
ExportedHandle::AndroidHardwareBuffer { .. } => (
VeloxHandleKind::AndroidHardwareBuffer,
lease.width * 4,
0,
0,
0,
),
ExportedHandle::InternalOnly => (VeloxHandleKind::None, lease.width * 4, 0, 0, 0),
};
let sync_kind = match lease.sync_handle {
ExternalSyncHandle::Win32Dx12FenceNtHandle(_) => {
VeloxSyncKind::Win32Dx12FenceNtHandle
}
ExternalSyncHandle::LinuxSemaphoreFd(_) => VeloxSyncKind::LinuxSemaphoreFd,
ExternalSyncHandle::AppleMetalSharedEvent(_) => {
VeloxSyncKind::AppleMetalSharedEvent
}
ExternalSyncHandle::AndroidSyncFd(_) => VeloxSyncKind::AndroidSyncFd,
ExternalSyncHandle::None => VeloxSyncKind::None,
};
let pixel_format = if lease.format == crate::renderers::wgpu::wgpu::TextureFormat::Bgra8Unorm {
1
} else {
0
};
return VeloxSharedFrameDesc {
generation_id: lease.generation_id,
slot_index: lease.slot_index,
is_fresh: if lease.is_fresh { 1 } else { 0 },
handle_kind: handle_kind as u8,
sync_kind: sync_kind as u8,
width: lease.width,
height: lease.height,
pixel_format,
raw_handle: lease.handle.raw_u64(),
sync_handle: lease.sync_handle.raw_u64(),
fence_value: lease.fence_value,
stride,
offset,
drm_format,
drm_modifier,
software_rgba_ptr: core::ptr::null(),
dirty_rects_ptr: self.dirty_rects.as_ptr(),
dirty_rect_count: self.dirty_rects.len() as u32,
};
}
let is_fresh = self.sw_fresh;
self.sw_fresh = false;
VeloxSharedFrameDesc {
generation_id: self.sw_generation,
slot_index: 0,
is_fresh: if is_fresh { 1 } else { 0 },
handle_kind: VeloxHandleKind::SoftwareRgbaPtr as u8,
sync_kind: VeloxSyncKind::None as u8,
width: self.phys_width,
height: self.phys_height,
pixel_format: 0,
raw_handle: 0,
sync_handle: 0,
fence_value: 0,
stride: self.phys_width * 4,
offset: 0,
drm_format: 0,
drm_modifier: 0,
software_rgba_ptr: self.sw_rgba_bytes.as_ptr(),
dirty_rects_ptr: self.dirty_rects.as_ptr(),
dirty_rect_count: self.dirty_rects.len() as u32,
}
}
pub fn release_shared_frame(&mut self, generation_id: u32, slot_index: u8) {
#[cfg(feature = "gpu")]
if let Some(exp) = &mut self.gpu_exporter {
exp.release_shared_frame(generation_id, slot_index);
}
let _ = (generation_id, slot_index);
}
pub fn inject_pointer(&mut self, phase: u8, x: i16, y: i16) -> bool {
match phase {
0 => self.engine.dispatch_pointer_down(x, y),
1 => self.engine.dispatch_pointer_move(x, y),
2 => self.engine.dispatch_pointer_up(x, y),
_ => {
self.engine.dispatch_pointer_up(x, y);
true
}
}
}
pub fn inject_wheel(&mut self, x: i16, y: i16, delta_y: i16) -> bool {
self.engine
.dispatch_event(InputEvent::Scroll { x, y, delta_y })
}
pub fn inject_key(&mut self, code: u32, is_char: bool) -> bool {
if is_char {
if let Some(ch) = char::from_u32(code) {
return self.engine.dispatch_key(KeyCode::Char(ch));
}
return false;
}
let key = match code {
9 => KeyCode::Tab,
13 => KeyCode::Enter,
27 => KeyCode::Escape,
8 => KeyCode::Backspace,
46 => KeyCode::Delete,
37 => KeyCode::Left,
38 => KeyCode::Up,
39 => KeyCode::Right,
40 => KeyCode::Down,
36 => KeyCode::Home,
35 => KeyCode::End,
_ => return false,
};
self.engine.dispatch_key(key)
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_backend_is_gpu(session: *const VeloxEmbedSession) -> u8 {
let Some(s) = (unsafe { session.as_ref() }) else {
return 0;
};
if s.backend_is_gpu() { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_resize(
session: *mut VeloxEmbedSession,
logical_width: i16,
logical_height: i16,
scale_factor: f32,
) {
if let Some(s) = unsafe { session.as_mut() } {
s.resize(logical_width, logical_height, scale_factor);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_step_frame(
session: *mut VeloxEmbedSession,
dt_ms: u16,
) -> u8 {
let Some(s) = (unsafe { session.as_mut() }) else {
return 0;
};
if s.step_frame(dt_ms) { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_acquire_shared_frame(
session: *mut VeloxEmbedSession,
out_frame: *mut VeloxSharedFrameDesc,
) -> u8 {
let (Some(s), Some(out)) = (unsafe { session.as_mut() }, unsafe { out_frame.as_mut() }) else {
return 0;
};
*out = s.acquire_shared_frame();
1
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_release_shared_frame(
session: *mut VeloxEmbedSession,
generation_id: u32,
slot_index: u8,
) {
if let Some(s) = unsafe { session.as_mut() } {
s.release_shared_frame(generation_id, slot_index);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_inject_pointer(
session: *mut VeloxEmbedSession,
phase: u8,
x: i16,
y: i16,
) -> u8 {
let Some(s) = (unsafe { session.as_mut() }) else {
return 0;
};
if s.inject_pointer(phase, x, y) { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_inject_wheel(
session: *mut VeloxEmbedSession,
x: i16,
y: i16,
delta_y: i16,
) -> u8 {
let Some(s) = (unsafe { session.as_mut() }) else {
return 0;
};
if s.inject_wheel(x, y, delta_y) { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_inject_key(
session: *mut VeloxEmbedSession,
code: u32,
is_char: u8,
) -> u8 {
let Some(s) = (unsafe { session.as_mut() }) else {
return 0;
};
if s.inject_key(code, is_char != 0) { 1 } else { 0 }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn velox_embed_destroy(session: *mut VeloxEmbedSession) {
if !session.is_null() {
unsafe {
drop(Box::from_raw(session));
}
}
}
pub const VELOX_EMBED_HEADER_H: &str = r#"#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct VeloxEmbedSession VeloxEmbedSession;
typedef struct VeloxDirtyRect {
int16_t x;
int16_t y;
int16_t w;
int16_t h;
} VeloxDirtyRect;
typedef enum VeloxHandleKind {
VELOX_HANDLE_NONE = 0,
VELOX_HANDLE_WIN32_DX12_NT = 1,
VELOX_HANDLE_LINUX_DMABUF_FD = 2,
VELOX_HANDLE_APPLE_IOSURFACE = 3,
VELOX_HANDLE_ANDROID_AHB = 4,
VELOX_HANDLE_SOFTWARE_RGBA_PTR = 5,
} VeloxHandleKind;
typedef enum VeloxSyncKind {
VELOX_SYNC_NONE = 0,
VELOX_SYNC_WIN32_DX12_FENCE_NT = 1,
VELOX_SYNC_LINUX_SEMAPHORE_FD = 2,
VELOX_SYNC_APPLE_METAL_SHARED_EVENT = 3,
VELOX_SYNC_ANDROID_SYNC_FD = 4,
} VeloxSyncKind;
typedef struct VeloxHostAdapterConfig {
uint8_t has_luid;
uint8_t adapter_luid[8];
uint8_t has_uuid;
uint8_t device_uuid[16];
uint8_t prefer_gpu;
uint8_t transparent_bg;
} VeloxHostAdapterConfig;
typedef struct VeloxSharedFrameDesc {
uint32_t generation_id;
uint8_t slot_index;
uint8_t is_fresh;
uint8_t handle_kind;
uint8_t sync_kind;
uint32_t width;
uint32_t height;
uint32_t pixel_format;
uint64_t raw_handle;
uint64_t sync_handle;
uint64_t fence_value;
uint32_t stride;
uint32_t offset;
uint32_t drm_format;
uint64_t drm_modifier;
const uint8_t* software_rgba_ptr;
const VeloxDirtyRect* dirty_rects_ptr;
uint32_t dirty_rect_count;
} VeloxSharedFrameDesc;
uint8_t velox_embed_backend_is_gpu(const VeloxEmbedSession* session);
void velox_embed_resize(VeloxEmbedSession* session, int16_t logical_width, int16_t logical_height, float scale_factor);
uint8_t velox_embed_step_frame(VeloxEmbedSession* session, uint16_t dt_ms);
uint8_t velox_embed_acquire_shared_frame(VeloxEmbedSession* session, VeloxSharedFrameDesc* out_frame);
void velox_embed_release_shared_frame(VeloxEmbedSession* session, uint32_t generation_id, uint8_t slot_index);
uint8_t velox_embed_inject_pointer(VeloxEmbedSession* session, uint8_t phase, int16_t x, int16_t y);
uint8_t velox_embed_inject_wheel(VeloxEmbedSession* session, int16_t x, int16_t y, int16_t delta_y);
uint8_t velox_embed_inject_key(VeloxEmbedSession* session, uint32_t code, uint8_t is_char);
void velox_embed_destroy(VeloxEmbedSession* session);
#ifdef __cplusplus
}
#endif
"#;