-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathandroid.rs
More file actions
212 lines (180 loc) · 7.45 KB
/
android.rs
File metadata and controls
212 lines (180 loc) · 7.45 KB
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
//! Implementation of software buffering for Android.
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::num::{NonZeroI32, NonZeroU32};
use ndk::{
hardware_buffer_format::HardwareBufferFormat,
native_window::{NativeWindow, NativeWindowBufferLockGuard},
};
#[cfg(doc)]
use raw_window_handle::AndroidNdkWindowHandle;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawWindowHandle};
use crate::error::InitError;
use crate::{BufferInterface, Pixel, Rect, SoftBufferError, SurfaceInterface};
const PIXEL_SIZE: usize = size_of::<Pixel>();
/// The handle to a window for software buffering.
#[derive(Debug)]
pub struct AndroidImpl<D, W> {
// Must be first in the struct to guarantee being dropped and unlocked before the `NativeWindow` reference
in_progress_buffer: Option<NativeWindowBufferLockGuard<'static>>,
native_window: NativeWindow,
window: W,
_display: PhantomData<D>,
}
// TODO: Move to NativeWindowBufferLockGuard?
unsafe impl<D, W> Send for AndroidImpl<D, W> {}
impl<D: HasDisplayHandle, W: HasWindowHandle> SurfaceInterface<D, W> for AndroidImpl<D, W> {
type Context = D;
type Buffer<'surface>
= BufferImpl<'surface>
where
Self: 'surface;
/// Create a new [`AndroidImpl`] from an [`AndroidNdkWindowHandle`].
fn new(window: W, _display: &Self::Context) -> Result<Self, InitError<W>> {
let raw = window.window_handle()?.as_raw();
let RawWindowHandle::AndroidNdk(a) = raw else {
return Err(InitError::Unsupported(window));
};
// Acquire a new owned reference to the window, that will be freed on drop.
// SAFETY: We have confirmed that the window handle is valid.
let native_window = unsafe { NativeWindow::clone_from_ptr(a.a_native_window.cast()) };
Ok(Self {
in_progress_buffer: None,
native_window,
_display: PhantomData,
window,
})
}
#[inline]
fn window(&self) -> &W {
&self.window
}
/// Also changes the pixel format to [`HardwareBufferFormat::R8G8B8X8_UNORM`].
fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) -> Result<(), SoftBufferError> {
let (width, height) = (|| {
let width = NonZeroI32::try_from(width).ok()?;
let height = NonZeroI32::try_from(height).ok()?;
Some((width, height))
})()
.ok_or(SoftBufferError::SizeOutOfRange { width, height })?;
self.native_window
.set_buffers_geometry(
width.into(),
height.into(),
// Default is typically R5G6B5 16bpp, switch to 32bpp
Some(HardwareBufferFormat::R8G8B8X8_UNORM),
)
.map_err(|err| {
SoftBufferError::PlatformError(
Some("Failed to set buffer geometry on ANativeWindow".to_owned()),
Some(Box::new(err)),
)
})
}
fn next_buffer(&mut self) -> Result<BufferImpl<'_>, SoftBufferError> {
if self.in_progress_buffer.is_some() {
return Ok(BufferImpl {
native_window_buffer: &mut self.in_progress_buffer,
});
}
let mut native_window_buffer = self.native_window.lock(None).map_err(|err| {
SoftBufferError::PlatformError(
Some("Failed to lock ANativeWindow".to_owned()),
Some(Box::new(err)),
)
})?;
if !matches!(
native_window_buffer.format(),
// These are the only formats we support
HardwareBufferFormat::R8G8B8A8_UNORM | HardwareBufferFormat::R8G8B8X8_UNORM
) {
return Err(SoftBufferError::PlatformError(
Some(format!(
"Unexpected buffer format {:?}, please call \
.resize() first to change it to RGBx8888",
native_window_buffer.format()
)),
None,
));
}
assert_eq!(
native_window_buffer.format().bytes_per_pixel(),
Some(PIXEL_SIZE)
);
let native_buffer = native_window_buffer.bytes().unwrap();
// Zero-initialize the buffer, allowing it to be cast away from MaybeUninit and mapped as a Pixel slice
native_buffer.fill(MaybeUninit::new(0));
assert_eq!(
native_buffer.len(),
native_window_buffer.stride() * native_window_buffer.height() * PIXEL_SIZE
);
// SAFETY: We guarantee that the guard isn't actually held longer than this owned handle of
// the `NativeWindow` (which is trivially cloneable), by means of having BufferImpl take a
// mutable borrow on AndroidImpl which owns the NativeWindow and LockGuard.
let native_window_buffer = unsafe {
std::mem::transmute::<
NativeWindowBufferLockGuard<'_>,
NativeWindowBufferLockGuard<'static>,
>(native_window_buffer)
};
self.in_progress_buffer = Some(native_window_buffer);
Ok(BufferImpl {
native_window_buffer: &mut self.in_progress_buffer,
})
}
/// Fetch the buffer from the window.
fn fetch(&mut self) -> Result<Vec<Pixel>, SoftBufferError> {
Err(SoftBufferError::Unimplemented)
}
}
#[derive(Debug)]
pub struct BufferImpl<'surface> {
// This Option will always be Some until present_with_damage() is called
native_window_buffer: &'surface mut Option<NativeWindowBufferLockGuard<'static>>,
}
// TODO: Move to NativeWindowBufferLockGuard?
unsafe impl Send for BufferImpl<'_> {}
impl BufferInterface for BufferImpl<'_> {
fn byte_stride(&self) -> NonZeroU32 {
NonZeroU32::new((self.native_window_buffer.as_ref().unwrap().stride() * PIXEL_SIZE) as u32)
.unwrap()
}
fn width(&self) -> NonZeroU32 {
NonZeroU32::new(self.native_window_buffer.as_ref().unwrap().width() as u32).unwrap()
}
fn height(&self) -> NonZeroU32 {
NonZeroU32::new(self.native_window_buffer.as_ref().unwrap().height() as u32).unwrap()
}
#[inline]
fn pixels_mut(&mut self) -> &mut [Pixel] {
let native_buffer = self.native_window_buffer.as_mut().unwrap().bytes().unwrap();
// SAFETY: The buffer was zero-initialized and its length is always a multiple of the pixel
// size (4 bytes), even when stride is applied
unsafe {
std::slice::from_raw_parts_mut(
native_buffer.as_mut_ptr().cast(),
native_buffer.len() / PIXEL_SIZE,
)
}
}
#[inline]
fn age(&self) -> u8 {
0
}
// TODO: This function is pretty slow this way
fn present_with_damage(self, damage: &[Rect]) -> Result<(), SoftBufferError> {
// TODO: Android requires the damage rect _at lock time_
// Since we're faking the backing buffer _anyway_, we could even fake the surface lock
// and lock it here (if it doesn't influence timings).
//
// Android seems to do this because the region can be expanded by the
// system, requesting the user to actually redraw a larger region.
// It's unclear if/when this is used, or if corruption/artifacts occur
// when the enlarged damage region is not re-rendered?
let _ = damage;
// The surface will be presented when it is unlocked, which happens when the owned guard
// is dropped.
self.native_window_buffer.take();
Ok(())
}
}