-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathandroid.rs
More file actions
175 lines (150 loc) · 5.62 KB
/
android.rs
File metadata and controls
175 lines (150 loc) · 5.62 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
//! Implementation of software buffering for Android.
use std::marker::PhantomData;
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::{util, BufferInterface, Rect, SoftBufferError, SurfaceInterface};
/// The handle to a window for software buffering.
#[derive(Debug)]
pub struct AndroidImpl<D, W> {
native_window: NativeWindow,
window: W,
_display: PhantomData<D>,
}
impl<D: HasDisplayHandle, W: HasWindowHandle> SurfaceInterface<D, W> for AndroidImpl<D, W> {
type Context = D;
type Buffer<'a>
= BufferImpl<'a>
where
Self: 'a;
/// 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 {
native_window,
_display: PhantomData,
window,
})
}
#[inline]
fn window(&self) -> &W {
&self.window
}
/// Also changes the pixel format to [`HardwareBufferFormat::R8G8B8A8_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 buffer_mut(&mut self) -> Result<BufferImpl<'_>, SoftBufferError> {
let 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,
));
}
let buffer = vec![0; native_window_buffer.width() * native_window_buffer.height()];
Ok(BufferImpl {
native_window_buffer,
buffer: util::PixelBuffer(buffer),
})
}
/// Fetch the buffer from the window.
fn fetch(&mut self) -> Result<Vec<u32>, SoftBufferError> {
Err(SoftBufferError::Unimplemented)
}
}
#[derive(Debug)]
pub struct BufferImpl<'a> {
native_window_buffer: NativeWindowBufferLockGuard<'a>,
buffer: util::PixelBuffer,
}
// TODO: Move to NativeWindowBufferLockGuard?
unsafe impl Send for BufferImpl<'_> {}
impl BufferInterface for BufferImpl<'_> {
fn width(&self) -> NonZeroU32 {
NonZeroU32::new(self.native_window_buffer.width() as u32).unwrap()
}
fn height(&self) -> NonZeroU32 {
NonZeroU32::new(self.native_window_buffer.height() as u32).unwrap()
}
#[inline]
fn pixels_mut(&mut self) -> &mut [u32] {
&mut self.buffer
}
#[inline]
fn age(&self) -> u8 {
0
}
// TODO: This function is pretty slow this way
fn present(mut self) -> Result<(), SoftBufferError> {
let input_lines = self.buffer.chunks(self.native_window_buffer.width());
for (output, input) in self
.native_window_buffer
.lines()
// Unreachable as we checked before that this is a valid, mappable format
.unwrap()
.zip(input_lines)
{
// .lines() removed the stride
assert_eq!(output.len(), input.len() * 4);
for (i, pixel) in input.iter().enumerate() {
// Swizzle colors from BGR(A) to RGB(A)
let [b, g, r, a] = pixel.to_le_bytes();
output[i * 4].write(r);
output[i * 4 + 1].write(g);
output[i * 4 + 2].write(b);
output[i * 4 + 3].write(a);
}
}
Ok(())
}
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).
self.present()
}
}