• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use std::ffi::c_char;
6 use std::ffi::CStr;
7 use std::ffi::CString;
8 use std::panic::catch_unwind;
9 use std::process::abort;
10 use std::ptr::NonNull;
11 use std::rc::Rc;
12 use std::slice;
13 
14 use base::error;
15 use base::AsRawDescriptor;
16 use base::Event;
17 use base::RawDescriptor;
18 use base::VolatileSlice;
19 use vm_control::gpu::DisplayParameters;
20 
21 use crate::DisplayT;
22 use crate::GpuDisplayError;
23 use crate::GpuDisplayFramebuffer;
24 use crate::GpuDisplayResult;
25 use crate::GpuDisplaySurface;
26 use crate::SurfaceType;
27 use crate::SysDisplayT;
28 
29 // Opaque blob
30 #[repr(C)]
31 pub(crate) struct AndroidDisplayContext {
32     _data: [u8; 0],
33     _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
34 }
35 
36 // Opaque blob
37 #[repr(C)]
38 pub(crate) struct ANativeWindow {
39     _data: [u8; 0],
40     _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>,
41 }
42 
43 // Should be the same as ANativeWindow_Buffer in android/native_window.h
44 // Note that this struct is part of NDK; guaranteed to be stable, so we use it directly across the
45 // FFI.
46 #[repr(C)]
47 pub(crate) struct ANativeWindow_Buffer {
48     width: i32,
49     height: i32,
50     stride: i32, // in number of pixels, NOT bytes
51     format: i32,
52     bits: *mut u8,
53     reserved: [u32; 6],
54 }
55 
56 pub(crate) type ErrorCallback = unsafe extern "C" fn(message: *const c_char);
57 
58 extern "C" {
59     /// Constructs an AndroidDisplayContext for this backend. This awlays returns a valid (ex:
60     /// non-null) handle to the context. The `name` parameter is from crosvm commandline and the
61     /// client of crosvm will use it to locate and communicate to the AndroidDisplayContext. For
62     /// example, this can be a path to UNIX domain socket where a RPC binder server listens on.
63     /// `error_callback` is a function pointer to an error reporting function, and will be used by
64     /// this and other functions below when something goes wrong. The returned context should be
65     /// destroyed by calling `destroy_android_display_context` if this backend is no longer in use.
create_android_display_context( name: *const c_char, error_callback: ErrorCallback, ) -> *mut AndroidDisplayContext66     fn create_android_display_context(
67         name: *const c_char,
68         error_callback: ErrorCallback,
69     ) -> *mut AndroidDisplayContext;
70 
71     /// Destroys the AndroidDisplayContext created from `create_android_display_context`.
destroy_android_display_context(self_: *mut AndroidDisplayContext)72     fn destroy_android_display_context(self_: *mut AndroidDisplayContext);
73 
74     /// Creates an Android Surface (which is also called as Window) of given size. If the surface
75     /// can't be created for whatever reason, null pointer is returned, in which case we shouldn't
76     /// proceed further.
create_android_surface( ctx: *mut AndroidDisplayContext, width: u32, height: u32, for_cursor: bool, ) -> *mut ANativeWindow77     fn create_android_surface(
78         ctx: *mut AndroidDisplayContext,
79         width: u32,
80         height: u32,
81         for_cursor: bool,
82     ) -> *mut ANativeWindow;
83 
84     /// Destroys the Android surface created from `create_android_surface`.
85     #[allow(dead_code)]
destroy_android_surface(ctx: *mut AndroidDisplayContext, surface: *mut ANativeWindow)86     fn destroy_android_surface(ctx: *mut AndroidDisplayContext, surface: *mut ANativeWindow);
87 
88     /// Obtains one buffer from the given Android Surface. The information about the buffer (buffer
89     /// address, size, stride, etc) is reported via the `ANativeWindow_Buffer` struct. It shouldn't
90     /// be null. The size of the buffer is guaranteed to be bigger than (width * stride * 4) bytes.
91     /// This function locks the buffer for the client, which means the caller has the exclusive
92     /// access to the buffer until it is returned back to Android display stack (surfaceflinger) by
93     /// calling `post_android_surface_buffer`. This function may fail (in which case false is
94     /// returned), then the caller shouldn't try to read `out_buffer` or use the buffer in any way.
get_android_surface_buffer( ctx: *mut AndroidDisplayContext, surface: *mut ANativeWindow, out_buffer: *mut ANativeWindow_Buffer, ) -> bool95     fn get_android_surface_buffer(
96         ctx: *mut AndroidDisplayContext,
97         surface: *mut ANativeWindow,
98         out_buffer: *mut ANativeWindow_Buffer,
99     ) -> bool;
100 
set_android_surface_position(ctx: *mut AndroidDisplayContext, x: u32, y: u32)101     fn set_android_surface_position(ctx: *mut AndroidDisplayContext, x: u32, y: u32);
102 
103     /// Posts the buffer obtained from `get_android_surface_buffer` to the Android display system
104     /// so that it can be displayed on the screen. Once this is called, the caller shouldn't use
105     /// the buffer any more.
post_android_surface_buffer(ctx: *mut AndroidDisplayContext, surface: *mut ANativeWindow)106     fn post_android_surface_buffer(ctx: *mut AndroidDisplayContext, surface: *mut ANativeWindow);
107 }
108 
error_callback(message: *const c_char)109 unsafe extern "C" fn error_callback(message: *const c_char) {
110     catch_unwind(|| {
111         error!(
112             "{}",
113             // SAFETY: message is null terminated
114             unsafe { CStr::from_ptr(message) }.to_string_lossy()
115         )
116     })
117     .unwrap_or_else(|_| abort())
118 }
119 
120 struct AndroidDisplayContextWrapper(NonNull<AndroidDisplayContext>);
121 
122 impl Drop for AndroidDisplayContextWrapper {
drop(&mut self)123     fn drop(&mut self) {
124         // SAFETY: this object is constructed from create_android_display_context
125         unsafe { destroy_android_display_context(self.0.as_ptr()) };
126     }
127 }
128 
129 impl Default for ANativeWindow_Buffer {
default() -> Self130     fn default() -> Self {
131         Self {
132             width: 0,
133             height: 0,
134             stride: 0,
135             format: 0,
136             bits: std::ptr::null_mut(),
137             reserved: [0u32; 6],
138         }
139     }
140 }
141 
142 impl From<ANativeWindow_Buffer> for GpuDisplayFramebuffer<'_> {
from(anb: ANativeWindow_Buffer) -> Self143     fn from(anb: ANativeWindow_Buffer) -> Self {
144         // TODO: check anb.format to see if it's ARGB8888?
145         // TODO: infer bpp from anb.format?
146         const BYTES_PER_PIXEL: u32 = 4;
147         let stride_bytes = BYTES_PER_PIXEL * u32::try_from(anb.stride).unwrap();
148         let buffer_size = stride_bytes * u32::try_from(anb.height).unwrap();
149         let buffer =
150             // SAFETY: get_android_surface_buffer guarantees that bits points to a valid buffer and
151             // the buffer remains available until post_android_surface_buffer is called.
152             unsafe { slice::from_raw_parts_mut(anb.bits, buffer_size.try_into().unwrap()) };
153         Self::new(VolatileSlice::new(buffer), stride_bytes, BYTES_PER_PIXEL)
154     }
155 }
156 
157 struct AndroidSurface {
158     context: Rc<AndroidDisplayContextWrapper>,
159     surface: NonNull<ANativeWindow>,
160 }
161 
162 impl GpuDisplaySurface for AndroidSurface {
framebuffer(&mut self) -> Option<GpuDisplayFramebuffer>163     fn framebuffer(&mut self) -> Option<GpuDisplayFramebuffer> {
164         let mut anb = ANativeWindow_Buffer::default();
165         // SAFETY: context and surface are opaque handles and buf is used as the out parameter to
166         // hold the return values.
167         let success = unsafe {
168             get_android_surface_buffer(
169                 self.context.0.as_ptr(),
170                 self.surface.as_ptr(),
171                 &mut anb as *mut ANativeWindow_Buffer,
172             )
173         };
174         if success {
175             Some(anb.into())
176         } else {
177             None
178         }
179     }
180 
flip(&mut self)181     fn flip(&mut self) {
182         // SAFETY: context and surface are opaque handles.
183         unsafe { post_android_surface_buffer(self.context.0.as_ptr(), self.surface.as_ptr()) }
184     }
185 
set_position(&mut self, x: u32, y: u32)186     fn set_position(&mut self, x: u32, y: u32) {
187         // SAFETY: context is an opaque handle.
188         unsafe { set_android_surface_position(self.context.0.as_ptr(), x, y) };
189     }
190 }
191 
192 pub struct DisplayAndroid {
193     context: Rc<AndroidDisplayContextWrapper>,
194     /// This event is never triggered and is used solely to fulfill AsRawDescriptor.
195     event: Event,
196 }
197 
198 impl DisplayAndroid {
new(name: &str) -> GpuDisplayResult<DisplayAndroid>199     pub fn new(name: &str) -> GpuDisplayResult<DisplayAndroid> {
200         let name = CString::new(name).unwrap();
201         let context = NonNull::new(
202             // SAFETY: service_name is not leaked outside of this function
203             unsafe { create_android_display_context(name.as_ptr(), error_callback) },
204         )
205         .ok_or(GpuDisplayError::Unsupported)?;
206         let context = AndroidDisplayContextWrapper(context);
207         let event = Event::new().map_err(|_| GpuDisplayError::CreateEvent)?;
208         Ok(DisplayAndroid {
209             context: context.into(),
210             event,
211         })
212     }
213 }
214 
215 impl DisplayT for DisplayAndroid {
create_surface( &mut self, parent_surface_id: Option<u32>, _surface_id: u32, _scanout_id: Option<u32>, display_params: &DisplayParameters, _surf_type: SurfaceType, ) -> GpuDisplayResult<Box<dyn GpuDisplaySurface>>216     fn create_surface(
217         &mut self,
218         parent_surface_id: Option<u32>,
219         _surface_id: u32,
220         _scanout_id: Option<u32>,
221         display_params: &DisplayParameters,
222         _surf_type: SurfaceType,
223     ) -> GpuDisplayResult<Box<dyn GpuDisplaySurface>> {
224         let (requested_width, requested_height) = display_params.get_virtual_display_size();
225         // SAFETY: context is an opaque handle.
226         let surface = NonNull::new(unsafe {
227             create_android_surface(
228                 self.context.0.as_ptr(),
229                 requested_width,
230                 requested_height,
231                 parent_surface_id.is_some(),
232             )
233         })
234         .ok_or(GpuDisplayError::CreateSurface)?;
235 
236         Ok(Box::new(AndroidSurface {
237             context: self.context.clone(),
238             surface,
239         }))
240     }
241 }
242 
243 impl SysDisplayT for DisplayAndroid {}
244 
245 impl AsRawDescriptor for DisplayAndroid {
as_raw_descriptor(&self) -> RawDescriptor246     fn as_raw_descriptor(&self) -> RawDescriptor {
247         self.event.as_raw_descriptor()
248     }
249 }
250