Debian Codegraph @

third_party/rust/audioipc2-server/src/lib.rs

raw
1 // Copyright © 2017 Mozilla Foundation
2 //
3 // This program is made available under an ISC-style license. See the
4 // accompanying file LICENSE for details
5 #![warn(unused_extern_crates)]
6
7 #[macro_use]
8 extern crate error_chain;
9 #[macro_use]
10 extern crate log;
11
12 use audio_thread_priority::promote_current_thread_to_real_time;
13 use audioipc::ipccore;
14 use audioipc::sys;
15 use audioipc::PlatformHandleType;
16 use once_cell::sync::Lazy;
17 use std::ffi::{CStr, CString};
18 use std::os::raw::c_void;
19 use std::ptr;
20 use std::sync::Mutex;
21 use std::thread;
22
23 mod server;
24
25 struct CubebContextParams {
26 context_name: CString,
27 backend_name: Option<CString>,
28 }
29
30 static G_CUBEB_CONTEXT_PARAMS: Lazy<Mutex<CubebContextParams>> = Lazy::new(|| {
31 Mutex::new(CubebContextParams {
32 context_name: CString::new("AudioIPC Server").unwrap(),
33 backend_name: None,
34 })
35 });
36
37 #[allow(deprecated)]
38 #[allow(clippy::upper_case_acronyms)]
39 pub mod errors {
40 error_chain! {
41 links {
42 AudioIPC(::audioipc::errors::Error, ::audioipc::errors::ErrorKind);
43 }
44 foreign_links {
45 Cubeb(cubeb_core::Error);
46 Io(::std::io::Error);
47 }
48 }
49 }
50
51 use crate::errors::*;
52
53 struct ServerWrapper {
54 rpc_thread: ipccore::EventLoopThread,
55 callback_thread: ipccore::EventLoopThread,
56 device_collection_thread: ipccore::EventLoopThread,
57 }
58
59 fn register_thread(callback: Option<extern "C" fn(*const ::std::os::raw::c_char)>) {
60 if let Some(func) = callback {
61 let name = CString::new(thread::current().name().unwrap()).unwrap();
62 func(name.as_ptr());
63 }
64 }
65
66 fn unregister_thread(callback: Option<extern "C" fn()>) {
67 if let Some(func) = callback {
68 func();
69 }
70 }
71
72 fn init_threads(
73 thread_create_callback: Option<extern "C" fn(*const ::std::os::raw::c_char)>,
74 thread_destroy_callback: Option<extern "C" fn()>,
75 ) -> Result<ServerWrapper> {
76 let rpc_name = "AudioIPC Server RPC";
77 let rpc_thread = ipccore::EventLoopThread::new(
78 rpc_name.to_string(),
79 None,
80 move || {
81 trace!("Starting {} thread", rpc_name);
82 register_thread(thread_create_callback);
83 audioipc::server_platform_init();
84 },
85 move || {
86 unregister_thread(thread_destroy_callback);
87 trace!("Stopping {} thread", rpc_name);
88 },
89 )
90 .map_err(|e| {
91 debug!("Failed to start {} thread: {:?}", rpc_name, e);
92 e
93 })?;
94
95 let callback_name = "AudioIPC Server Callback";
96 let callback_thread = ipccore::EventLoopThread::new(
97 callback_name.to_string(),
98 None,
99 move || {
100 trace!("Starting {} thread", callback_name);
101 if let Err(e) = promote_current_thread_to_real_time(0, 48000) {
102 debug!(
103 "Failed to promote {} thread to real-time: {:?}",
104 callback_name, e
105 );
106 }
107 register_thread(thread_create_callback);
108 },
109 move || {
110 unregister_thread(thread_destroy_callback);
111 trace!("Stopping {} thread", callback_name);
112 },
113 )
114 .map_err(|e| {
115 debug!("Failed to start {} thread: {:?}", callback_name, e);
116 e
117 })?;
118
119 let device_collection_name = "AudioIPC DeviceCollection RPC";
120 let device_collection_thread = ipccore::EventLoopThread::new(
121 device_collection_name.to_string(),
122 None,
123 move || {
124 trace!("Starting {} thread", device_collection_name);
125 register_thread(thread_create_callback);
126 },
127 move || {
128 unregister_thread(thread_destroy_callback);
129 trace!("Stopping {} thread", device_collection_name);
130 },
131 )
132 .map_err(|e| {
133 debug!("Failed to start {} thread: {:?}", device_collection_name, e);
134 e
135 })?;
136
137 Ok(ServerWrapper {
138 rpc_thread,
139 callback_thread,
140 device_collection_thread,
141 })
142 }
143
144 #[repr(C)]
145 #[derive(Clone, Copy, Debug)]
146 pub struct AudioIpcServerInitParams {
147 // Fields only need to be public for ipctest.
148 pub thread_create_callback: Option<extern "C" fn(*const ::std::os::raw::c_char)>,
149 pub thread_destroy_callback: Option<extern "C" fn()>,
150 }
151
152 #[allow(clippy::missing_safety_doc)]
153 #[no_mangle]
154 pub unsafe extern "C" fn audioipc2_server_start(
155 context_name: *const std::os::raw::c_char,
156 backend_name: *const std::os::raw::c_char,
157 init_params: *const AudioIpcServerInitParams,
158 ) -> *mut c_void {
159 assert!(!init_params.is_null());
160 let mut params = G_CUBEB_CONTEXT_PARAMS.lock().unwrap();
161 if !context_name.is_null() {
162 CStr::from_ptr(context_name).clone_into(&mut params.context_name);
163 }
164 if !backend_name.is_null() {
165 let backend_string = CStr::from_ptr(backend_name).to_owned();
166 params.backend_name = Some(backend_string);
167 }
168 match init_threads(
169 (*init_params).thread_create_callback,
170 (*init_params).thread_destroy_callback,
171 ) {
172 Ok(server) => Box::into_raw(Box::new(server)) as *mut _,
173 Err(_) => ptr::null_mut() as *mut _,
174 }
175 }
176
177 // A `shm_area_size` of 0 allows the server to calculate an appropriate shm size for each stream.
178 // A non-zero `shm_area_size` forces all allocations to the specified size.
179 #[no_mangle]
180 pub extern "C" fn audioipc2_server_new_client(
181 p: *mut c_void,
182 shm_area_size: usize,
183 ) -> PlatformHandleType {
184 let wrapper: &ServerWrapper = unsafe { &*(p as *mut _) };
185
186 // We create a connected pair of anonymous IPC endpoints. One side
187 // is registered with the event loop core, the other side is returned
188 // to the caller to be remoted to the client to complete setup.
189 let (server_pipe, client_pipe) = match sys::make_pipe_pair() {
190 Ok((server_pipe, client_pipe)) => (server_pipe, client_pipe),
191 Err(e) => {
192 error!(
193 "audioipc_server_new_client - make_pipe_pair failed: {:?}",
194 e
195 );
196 return audioipc::INVALID_HANDLE_VALUE;
197 }
198 };
199
200 let rpc_thread = wrapper.rpc_thread.handle();
201 let callback_thread = wrapper.callback_thread.handle();
202 let device_collection_thread = wrapper.device_collection_thread.handle();
203
204 let server = server::CubebServer::new(
205 callback_thread.clone(),
206 device_collection_thread.clone(),
207 shm_area_size,
208 );
209 if let Err(e) = rpc_thread.bind_server(server, server_pipe) {
210 error!("audioipc_server_new_client - bind_server failed: {:?}", e);
211 return audioipc::INVALID_HANDLE_VALUE;
212 }
213
214 unsafe { client_pipe.into_raw() }
215 }
216
217 #[no_mangle]
218 pub extern "C" fn audioipc2_server_stop(p: *mut c_void) {
219 let wrapper = unsafe { Box::<ServerWrapper>::from_raw(p as *mut _) };
220 drop(wrapper);
221 }