euv-core 0.48.2

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
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
use super::*;

#[link(name = "android")]
unsafe extern "C" {
    /// Body of the `ANativeWindow_getWidth` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_getWidth(window: *mut c_void) -> i32;
    /// Body of the `ANativeWindow_getHeight` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_getHeight(window: *mut c_void) -> i32;
    /// Body of the `ANativeWindow_setBuffersGeometry` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `i32` - A 32-bit signed integer (`i32`).
    /// - `i32` - A 32-bit signed integer (`i32`).
    /// - `i32` - A 32-bit signed integer (`i32`).
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_setBuffersGeometry(
        window: *mut c_void,
        width: i32,
        height: i32,
        format: i32,
    ) -> i32;
    /// Body of the `ANativeWindow_lock` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `*mut ANativeWindowBuffer` - A `*mut ANativeWindowBuffer` parameter.
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_lock(
        window: *mut c_void,
        out_buffer: *mut ANativeWindowBuffer,
        in_out_dirty_bounds: *mut c_void,
    ) -> i32;
    /// Body of the `ANativeWindow_unlockAndPost` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_unlockAndPost(window: *mut c_void) -> i32;
}

unsafe extern "C" {
    /// Dynamically opens a shared library on Android bionic.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated library name.
    /// - `i32` - Dynamic linker flags.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Library handle or null.
    fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
    /// Dynamically resolves a symbol pointer from a loaded Android shared library.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Loaded library handle.
    /// - `*const c_char` - Null-terminated symbol name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Resolved symbol pointer or null.
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}

/// Resolves and caches `ANativeWindow_setFrameRate*` symbols once from `libandroid.so` without leaking `dlopen` handles.
///
/// # Returns
///
/// - `(usize, usize)` - Cached `(setFrameRateWithChangeStrategy, setFrameRate)` function pointer addresses (`0` when absent).
fn android_cached_frame_rate_syms() -> (usize, usize) {
    *ANDROID_FRAME_RATE_SYMS.get_or_init(|| -> (usize, usize) {
        // SAFETY: Opens `libandroid.so` once for the process lifetime and resolves optional API 30+/31+ symbols.
        unsafe {
            let lib: *mut c_void = dlopen(
                ANDROID_LIB_NAME.as_ptr().cast::<c_char>(),
                ANDROID_RTLD_LAZY,
            );
            if lib.is_null() {
                return (0, 0);
            }
            let sym31: usize = dlsym(
                lib,
                SYM_ANDROID_SET_FRAME_RATE_STRATEGY
                    .as_ptr()
                    .cast::<c_char>(),
            ) as usize;
            let sym30: usize =
                dlsym(lib, SYM_ANDROID_SET_FRAME_RATE.as_ptr().cast::<c_char>()) as usize;
            (sym31, sym30)
        }
    })
}

/// Hints the preferred high-refresh frame rate to Android SurfaceFlinger via `ANativeWindow_setFrameRateWithChangeStrategy` (`CHANGE_FRAME_RATE_ALWAYS`, API 31+) or `ANativeWindow_setFrameRate` (API 30+).
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
/// - `f32` - Desired hardware refresh rate in Hertz (`60.0`..`480.0`).
///
/// # Returns
///
/// - `bool` - `true` when the NDK frame-rate hint symbol was resolved and returned status `0`.
pub fn android_set_native_window_frame_rate(native_window: usize, refresh_hz: f32) -> bool {
    if native_window == 0 || !refresh_hz.is_finite() || refresh_hz < MIN_REFRESH_RATE_HZ {
        return false;
    }
    let hz: f32 = refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
    let (sym31, sym30): (usize, usize) = android_cached_frame_rate_syms();
    // SAFETY: Invokes cached optional API 30+/31+ NDK frame-rate symbols with exact C ABI.
    unsafe {
        if sym31 != 0 {
            let func: unsafe extern "C" fn(*mut c_void, f32, i8, i8) -> i32 =
                transmute(sym31 as *const c_void);
            return func(
                native_window as *mut c_void,
                hz,
                ANDROID_FRAME_RATE_COMPAT_FIXED_SOURCE,
                ANDROID_CHANGE_FRAME_RATE_ALWAYS,
            ) == 0;
        }
        if sym30 != 0 {
            let func: unsafe extern "C" fn(*mut c_void, f32, i8) -> i32 =
                transmute(sym30 as *const c_void);
            return func(
                native_window as *mut c_void,
                hz,
                ANDROID_FRAME_RATE_COMPAT_FIXED_SOURCE,
            ) == 0;
        }
        false
    }
}

/// Decodes a packed little-endian direct `ByteBuffer` touch batch flushed once per frame over JNI.
///
/// # Arguments
///
/// - `&[u8]` - Raw byte slice containing contiguous 20-byte `AndroidTouchBatchEntry` records.
///
/// # Returns
///
/// - `Vec<AndroidTouchBatchEntry>` - Decoded touch entries in arrival order.
#[must_use]
pub fn android_decode_touch_batch(bytes: &[u8]) -> Vec<AndroidTouchBatchEntry> {
    let count: usize = bytes.len() / ANDROID_TOUCH_BATCH_RECORD_BYTES;
    let mut out: Vec<AndroidTouchBatchEntry> = Vec::with_capacity(count);
    for idx in 0..count {
        let base: usize = idx * ANDROID_TOUCH_BATCH_RECORD_BYTES;
        let action: i32 = i32::from_le_bytes([
            bytes[base],
            bytes[base + 1],
            bytes[base + 2],
            bytes[base + 3],
        ]);
        let action_index: i32 = i32::from_le_bytes([
            bytes[base + 4],
            bytes[base + 5],
            bytes[base + 6],
            bytes[base + 7],
        ]);
        let pointer_id: i32 = i32::from_le_bytes([
            bytes[base + 8],
            bytes[base + 9],
            bytes[base + 10],
            bytes[base + 11],
        ]);
        let x: f32 = f32::from_le_bytes([
            bytes[base + 12],
            bytes[base + 13],
            bytes[base + 14],
            bytes[base + 15],
        ]);
        let y: f32 = f32::from_le_bytes([
            bytes[base + 16],
            bytes[base + 17],
            bytes[base + 18],
            bytes[base + 19],
        ]);
        out.push(AndroidTouchBatchEntry {
            action,
            action_index,
            pointer_id,
            x,
            y,
        });
    }
    out
}

/// Queries physical pixel dimensions from an attached `ANativeWindow*`.
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
///
/// # Returns
///
/// - `Option<(u32, u32)>` - Physical `(width, height)` when the native window is attached.
#[must_use]
pub fn android_query_window_size(native_window: usize) -> Option<(u32, u32)> {
    if native_window == 0 {
        return None;
    }
    // SAFETY: Caller supplies a live `ANativeWindow*` owned by the Android lifecycle.
    unsafe {
        let w: i32 = ANativeWindow_getWidth(native_window as *mut c_void);
        let h: i32 = ANativeWindow_getHeight(native_window as *mut c_void);
        if w > 0 && h > 0 {
            Some((w as u32, h as u32))
        } else {
            None
        }
    }
}

/// Locks an `ANativeWindow*`, copies RGBA8 pixels (supporting dirty-rect sub-region locks), and posts the frame.
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `&mut u32` - Cached surface width avoiding redundant `ANativeWindow_setBuffersGeometry` calls.
/// - `&mut u32` - Cached surface height avoiding redundant `ANativeWindow_setBuffersGeometry` calls.
/// - `Option<Rect>` - Optional dirty pixel sub-rectangle for partial lock/copy.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn android_present_native_window(
    native_window: usize,
    framebuffer: &Framebuffer,
    cached_w: &mut u32,
    cached_h: &mut u32,
    dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
    if native_window == 0 {
        return Ok(());
    }
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    let src_w: usize = fb_w as usize;
    let src_h: usize = fb_h as usize;
    let src_bytes: &[u8] = framebuffer.get_pixels().as_slice();
    let mut buffer: ANativeWindowBuffer = ANativeWindowBuffer {
        width: 0,
        height: 0,
        stride: 0,
        format: 0,
        bits: null_mut(),
        reserved: [0; 6],
    };
    let mut bounds: AndroidRect = match dirty_rect {
        Some(r) => AndroidRect {
            left: (r.get_x().floor().max(0.0) as i32).min(fb_w as i32),
            top: (r.get_y().floor().max(0.0) as i32).min(fb_h as i32),
            right: ((r.get_x() + r.get_width()).ceil().max(0.0) as i32).min(fb_w as i32),
            bottom: ((r.get_y() + r.get_height()).ceil().max(0.0) as i32).min(fb_h as i32),
        },
        None => AndroidRect::default(),
    };
    let use_dirty: bool =
        dirty_rect.is_some() && bounds.right > bounds.left && bounds.bottom > bounds.top;
    // SAFETY: Locks the NDK hardware surface buffer, copies bounded RGBA8 scanlines, and always unlocks.
    unsafe {
        if *cached_w != fb_w || *cached_h != fb_h {
            let _: i32 = ANativeWindow_setBuffersGeometry(
                native_window as *mut c_void,
                src_w as i32,
                src_h as i32,
                ANDROID_WINDOW_FORMAT_RGBA_8888,
            );
            *cached_w = fb_w;
            *cached_h = fb_h;
        }
        let dirty_ptr: *mut c_void = if use_dirty {
            (&mut bounds as *mut AndroidRect).cast::<c_void>()
        } else {
            null_mut()
        };
        let status: i32 = ANativeWindow_lock(native_window as *mut c_void, &mut buffer, dirty_ptr);
        if status != 0 {
            return Err(PlatformError::SurfaceError(
                ERR_ANDROID_LOCK_SURFACE.to_string(),
            ));
        }
        if !buffer.bits.is_null() && buffer.stride > 0 && buffer.height > 0 {
            let max_rows: usize = src_h.min(buffer.height as usize);
            let max_cols: usize = src_w.min(buffer.width.max(0) as usize);
            let (x0, y0, x1, y1): (usize, usize, usize, usize) = if use_dirty {
                (
                    (bounds.left.max(0) as usize).min(max_cols),
                    (bounds.top.max(0) as usize).min(max_rows),
                    (bounds.right.max(0) as usize).min(max_cols),
                    (bounds.bottom.max(0) as usize).min(max_rows),
                )
            } else {
                (0, 0, max_cols, max_rows)
            };
            let dst_stride_bytes: usize = (buffer.stride as usize) * 4;
            let src_stride_bytes: usize = src_w * 4;
            let row_copy_bytes: usize = x1.saturating_sub(x0).saturating_mul(4);
            let x_off_bytes: usize = x0.saturating_mul(4);
            let dst_base: *mut u8 = buffer.bits.cast::<u8>();
            if x0 == 0
                && y0 == 0
                && x1 == src_w
                && src_stride_bytes == dst_stride_bytes
                && y1.saturating_mul(row_copy_bytes) <= src_bytes.len()
            {
                copy_nonoverlapping(
                    src_bytes.as_ptr(),
                    dst_base,
                    y1.saturating_mul(row_copy_bytes),
                );
            } else if row_copy_bytes > 0 {
                for row in y0..y1 {
                    let src_off: usize = row * src_stride_bytes + x_off_bytes;
                    let dst_off: usize = row * dst_stride_bytes + x_off_bytes;
                    if src_off + row_copy_bytes <= src_bytes.len() {
                        copy_nonoverlapping(
                            src_bytes.as_ptr().add(src_off),
                            dst_base.add(dst_off),
                            row_copy_bytes,
                        );
                    }
                }
            }
        }
        let _: i32 = ANativeWindow_unlockAndPost(native_window as *mut c_void);
    }
    Ok(())
}

/// Locks an `ANativeWindow*` and copies pixels according to an adaptive `AdaptiveUploadPlan` (`MultiRect`, `MergedBbox`, `FullFrame`, or `None`).
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `&mut u32` - Cached surface width avoiding redundant geometry reconfigurations.
/// - `&mut u32` - Cached surface height avoiding redundant geometry reconfigurations.
/// - `&AdaptiveUploadPlan` - Selected multi-rect, merged-bbox, or full-frame upload plan.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn android_present_native_window_plan(
    native_window: usize,
    framebuffer: &Framebuffer,
    cached_w: &mut u32,
    cached_h: &mut u32,
    plan: &AdaptiveUploadPlan,
) -> Result<(), PlatformError> {
    if native_window == 0 || plan.get_strategy() == MobileUploadStrategy::None {
        return Ok(());
    }
    if plan.get_strategy() == MobileUploadStrategy::FullFrame || plan.get_rects().is_empty() {
        return android_present_native_window(native_window, framebuffer, cached_w, cached_h, None);
    }
    let mut union_rect: PixelDirtyRect = plan.get_rects()[0];
    for r in plan.get_rects().iter().skip(1) {
        union_rect = union_rect.union_with(*r);
    }
    let dirty_box: Rect = Rect::new(
        union_rect.get_x() as f32,
        union_rect.get_y() as f32,
        union_rect.get_width() as f32,
        union_rect.get_height() as f32,
    );
    android_present_native_window(
        native_window,
        framebuffer,
        cached_w,
        cached_h,
        Some(dirty_box),
    )
}