| 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 |
|
| 6 |
use crate::stream; |
| 7 |
use crate::{assert_not_in_callback, run_in_callback}; |
| 8 |
use crate::{ClientStream, AUDIOIPC_INIT_PARAMS}; |
| 9 |
#[cfg(target_os = "linux")] |
| 10 |
use audio_thread_priority::get_current_thread_info; |
| 11 |
#[cfg(not(target_os = "linux"))] |
| 12 |
use audio_thread_priority::promote_current_thread_to_real_time; |
| 13 |
use audioipc::ipccore::EventLoopHandle; |
| 14 |
use audioipc::{ipccore, rpccore, sys, PlatformHandle}; |
| 15 |
use audioipc::{ |
| 16 |
messages, messages::DeviceCollectionReq, messages::DeviceCollectionResp, ClientMessage, |
| 17 |
ServerMessage, |
| 18 |
}; |
| 19 |
use cubeb_backend::{ |
| 20 |
capi_new, ffi, Context, ContextOps, DeviceCollectionRef, DeviceId, DeviceType, Error, |
| 21 |
InputProcessingParams, Ops, Result, Stream, StreamParams, StreamParamsRef, |
| 22 |
}; |
| 23 |
use std::ffi::{CStr, CString}; |
| 24 |
use std::os::raw::c_void; |
| 25 |
use std::sync::{Arc, Mutex}; |
| 26 |
use std::thread; |
| 27 |
use std::{fmt, mem, ptr}; |
| 28 |
|
| 29 |
struct CubebClient; |
| 30 |
|
| 31 |
impl rpccore::Client for CubebClient { |
| 32 |
type ServerMessage = ServerMessage; |
| 33 |
type ClientMessage = ClientMessage; |
| 34 |
} |
| 35 |
|
| 36 |
pub const CLIENT_OPS: Ops = capi_new!(ClientContext, ClientStream); |
| 37 |
|
| 38 |
// ClientContext's layout *must* match cubeb.c's `struct cubeb` for the |
| 39 |
// common fields. |
| 40 |
#[repr(C)] |
| 41 |
pub struct ClientContext { |
| 42 |
_ops: *const Ops, |
| 43 |
rpc: rpccore::Proxy<ServerMessage, ClientMessage>, |
| 44 |
rpc_thread: ipccore::EventLoopThread, |
| 45 |
callback_thread: ipccore::EventLoopThread, |
| 46 |
backend_id: CString, |
| 47 |
device_collection_rpc: bool, |
| 48 |
input_device_callback: Arc<Mutex<DeviceCollectionCallback>>, |
| 49 |
output_device_callback: Arc<Mutex<DeviceCollectionCallback>>, |
| 50 |
} |
| 51 |
|
| 52 |
impl ClientContext { |
| 53 |
#[doc(hidden)] |
| 54 |
pub fn rpc_handle(&self) -> &EventLoopHandle { |
| 55 |
self.rpc_thread.handle() |
| 56 |
} |
| 57 |
|
| 58 |
#[doc(hidden)] |
| 59 |
pub fn rpc(&self) -> rpccore::Proxy<ServerMessage, ClientMessage> { |
| 60 |
self.rpc.clone() |
| 61 |
} |
| 62 |
|
| 63 |
#[doc(hidden)] |
| 64 |
pub fn callback_handle(&self) -> &EventLoopHandle { |
| 65 |
self.callback_thread.handle() |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
#[cfg(target_os = "linux")] |
| 70 |
fn promote_thread(rpc: &rpccore::Proxy<ServerMessage, ClientMessage>) { |
| 71 |
match get_current_thread_info() { |
| 72 |
Ok(info) => { |
| 73 |
let bytes = info.serialize(); |
| 74 |
let _ = rpc.call(ServerMessage::PromoteThreadToRealTime(bytes)); |
| 75 |
} |
| 76 |
Err(_) => { |
| 77 |
warn!("Could not remotely promote thread to RT."); |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
#[cfg(not(target_os = "linux"))] |
| 83 |
fn promote_thread(_rpc: &rpccore::Proxy<ServerMessage, ClientMessage>) { |
| 84 |
match promote_current_thread_to_real_time(0, 48000) { |
| 85 |
Ok(_) => { |
| 86 |
info!("Audio thread promoted to real-time."); |
| 87 |
} |
| 88 |
Err(_) => { |
| 89 |
warn!("Could not promote thread to real-time."); |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
fn register_thread(callback: Option<extern "C" fn(*const ::std::os::raw::c_char)>) { |
| 95 |
if let Some(func) = callback { |
| 96 |
let thr = thread::current(); |
| 97 |
let name = CString::new(thr.name().unwrap()).unwrap(); |
| 98 |
func(name.as_ptr()); |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
fn unregister_thread(callback: Option<extern "C" fn()>) { |
| 103 |
if let Some(func) = callback { |
| 104 |
func(); |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
fn promote_and_register_thread( |
| 109 |
rpc: &rpccore::Proxy<ServerMessage, ClientMessage>, |
| 110 |
callback: Option<extern "C" fn(*const ::std::os::raw::c_char)>, |
| 111 |
) { |
| 112 |
promote_thread(rpc); |
| 113 |
register_thread(callback); |
| 114 |
} |
| 115 |
|
| 116 |
#[derive(Default)] |
| 117 |
struct DeviceCollectionCallback { |
| 118 |
cb: ffi::cubeb_device_collection_changed_callback, |
| 119 |
user_ptr: usize, |
| 120 |
} |
| 121 |
|
| 122 |
struct DeviceCollectionServer { |
| 123 |
input_device_callback: Arc<Mutex<DeviceCollectionCallback>>, |
| 124 |
output_device_callback: Arc<Mutex<DeviceCollectionCallback>>, |
| 125 |
} |
| 126 |
|
| 127 |
impl rpccore::Server for DeviceCollectionServer { |
| 128 |
type ServerMessage = DeviceCollectionReq; |
| 129 |
type ClientMessage = DeviceCollectionResp; |
| 130 |
|
| 131 |
fn process(&mut self, req: Self::ServerMessage) -> Self::ClientMessage { |
| 132 |
match req { |
| 133 |
DeviceCollectionReq::DeviceChange(device_type) => { |
| 134 |
trace!( |
| 135 |
"ctx_thread: DeviceChange Callback: device_type={}", |
| 136 |
device_type |
| 137 |
); |
| 138 |
|
| 139 |
let devtype = cubeb_backend::DeviceType::from_bits_truncate(device_type); |
| 140 |
|
| 141 |
let (input_cb, input_user_ptr) = { |
| 142 |
let dcb = self.input_device_callback.lock().unwrap(); |
| 143 |
(dcb.cb, dcb.user_ptr) |
| 144 |
}; |
| 145 |
let (output_cb, output_user_ptr) = { |
| 146 |
let dcb = self.output_device_callback.lock().unwrap(); |
| 147 |
(dcb.cb, dcb.user_ptr) |
| 148 |
}; |
| 149 |
|
| 150 |
run_in_callback(|| { |
| 151 |
if devtype.contains(cubeb_backend::DeviceType::INPUT) { |
| 152 |
unsafe { input_cb.unwrap()(ptr::null_mut(), input_user_ptr as *mut c_void) } |
| 153 |
} |
| 154 |
if devtype.contains(cubeb_backend::DeviceType::OUTPUT) { |
| 155 |
unsafe { |
| 156 |
output_cb.unwrap()(ptr::null_mut(), output_user_ptr as *mut c_void) |
| 157 |
} |
| 158 |
} |
| 159 |
}); |
| 160 |
|
| 161 |
DeviceCollectionResp::DeviceChange |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
impl ContextOps for ClientContext { |
| 168 |
fn init(_context_name: Option<&CStr>) -> Result<Context> { |
| 169 |
assert_not_in_callback(); |
| 170 |
|
| 171 |
let params = AUDIOIPC_INIT_PARAMS.with(|p| p.replace(None).unwrap()); |
| 172 |
let thread_create_callback = params.thread_create_callback; |
| 173 |
let thread_destroy_callback = params.thread_destroy_callback; |
| 174 |
|
| 175 |
let server_connection = |
| 176 |
unsafe { sys::Pipe::from_raw_handle(PlatformHandle::new(params.server_connection)) }; |
| 177 |
|
| 178 |
let rpc_thread = ipccore::EventLoopThread::new( |
| 179 |
"AudioIPC Client RPC".to_string(), |
| 180 |
None, |
| 181 |
move || register_thread(thread_create_callback), |
| 182 |
move || unregister_thread(thread_destroy_callback), |
| 183 |
) |
| 184 |
.map_err(|_| Error::default())?; |
| 185 |
let rpc = rpc_thread |
| 186 |
.handle() |
| 187 |
.bind_client::<CubebClient>(server_connection) |
| 188 |
.map_err(|_| Error::default())?; |
| 189 |
let rpc2 = rpc.clone(); |
| 190 |
|
| 191 |
// Don't let errors bubble from here. Later calls against this context |
| 192 |
// will return errors the caller expects to handle. |
| 193 |
let _ = send_recv!(rpc, ClientConnect(std::process::id()) => ClientConnected); |
| 194 |
|
| 195 |
let backend_id = send_recv!(rpc, ContextGetBackendId => ContextBackendId()) |
| 196 |
.unwrap_or_else(|_| "(remote error)".to_string()); |
| 197 |
let backend_id = CString::new(backend_id).expect("backend_id query failed"); |
| 198 |
|
| 199 |
// TODO: remove params.pool_size from init params. |
| 200 |
let callback_thread = ipccore::EventLoopThread::new( |
| 201 |
"AudioIPC Client Callback".to_string(), |
| 202 |
Some(params.stack_size), |
| 203 |
move || promote_and_register_thread(&rpc2, thread_create_callback), |
| 204 |
move || unregister_thread(thread_destroy_callback), |
| 205 |
) |
| 206 |
.map_err(|_| Error::default())?; |
| 207 |
|
| 208 |
let ctx = Box::new(ClientContext { |
| 209 |
_ops: &CLIENT_OPS as *const _, |
| 210 |
rpc, |
| 211 |
rpc_thread, |
| 212 |
callback_thread, |
| 213 |
backend_id, |
| 214 |
device_collection_rpc: false, |
| 215 |
input_device_callback: Arc::new(Mutex::new(Default::default())), |
| 216 |
output_device_callback: Arc::new(Mutex::new(Default::default())), |
| 217 |
}); |
| 218 |
Ok(unsafe { Context::from_ptr(Box::into_raw(ctx) as *mut _) }) |
| 219 |
} |
| 220 |
|
| 221 |
fn backend_id(&mut self) -> &CStr { |
| 222 |
assert_not_in_callback(); |
| 223 |
self.backend_id.as_c_str() |
| 224 |
} |
| 225 |
|
| 226 |
fn max_channel_count(&mut self) -> Result<u32> { |
| 227 |
assert_not_in_callback(); |
| 228 |
send_recv!(self.rpc(), ContextGetMaxChannelCount => ContextMaxChannelCount()) |
| 229 |
} |
| 230 |
|
| 231 |
fn min_latency(&mut self, params: StreamParams) -> Result<u32> { |
| 232 |
assert_not_in_callback(); |
| 233 |
let params = messages::StreamParams::from(params.as_ref()); |
| 234 |
send_recv!(self.rpc(), ContextGetMinLatency(params) => ContextMinLatency()) |
| 235 |
} |
| 236 |
|
| 237 |
fn preferred_sample_rate(&mut self) -> Result<u32> { |
| 238 |
assert_not_in_callback(); |
| 239 |
send_recv!(self.rpc(), ContextGetPreferredSampleRate => ContextPreferredSampleRate()) |
| 240 |
} |
| 241 |
|
| 242 |
fn supported_input_processing_params(&mut self) -> Result<InputProcessingParams> { |
| 243 |
assert_not_in_callback(); |
| 244 |
send_recv!(self.rpc(), |
| 245 |
ContextGetSupportedInputProcessingParams => |
| 246 |
ContextSupportedInputProcessingParams()) |
| 247 |
.map(InputProcessingParams::from_bits_truncate) |
| 248 |
} |
| 249 |
|
| 250 |
fn enumerate_devices( |
| 251 |
&mut self, |
| 252 |
devtype: DeviceType, |
| 253 |
collection: &DeviceCollectionRef, |
| 254 |
) -> Result<()> { |
| 255 |
assert_not_in_callback(); |
| 256 |
let v: Vec<ffi::cubeb_device_info> = send_recv!( |
| 257 |
self.rpc(), ContextGetDeviceEnumeration(devtype.bits()) => ContextEnumeratedDevices())? |
| 258 |
.into_iter() |
| 259 |
.map(|i| i.into()) |
| 260 |
.collect(); |
| 261 |
let mut vs = v.into_boxed_slice(); |
| 262 |
let coll = unsafe { &mut *collection.as_ptr() }; |
| 263 |
coll.device = vs.as_mut_ptr(); |
| 264 |
coll.count = vs.len(); |
| 265 |
// Giving away the memory owned by vs. Don't free it! |
| 266 |
// Reclaimed in `device_collection_destroy`. |
| 267 |
mem::forget(vs); |
| 268 |
Ok(()) |
| 269 |
} |
| 270 |
|
| 271 |
fn device_collection_destroy(&mut self, collection: &mut DeviceCollectionRef) -> Result<()> { |
| 272 |
assert_not_in_callback(); |
| 273 |
unsafe { |
| 274 |
let coll = &mut *collection.as_ptr(); |
| 275 |
let mut devices = Vec::from_raw_parts(coll.device, coll.count, coll.count); |
| 276 |
for dev in &mut devices { |
| 277 |
if !dev.device_id.is_null() { |
| 278 |
let _ = CString::from_raw(dev.device_id as *mut _); |
| 279 |
} |
| 280 |
if !dev.group_id.is_null() { |
| 281 |
let _ = CString::from_raw(dev.group_id as *mut _); |
| 282 |
} |
| 283 |
if !dev.vendor_name.is_null() { |
| 284 |
let _ = CString::from_raw(dev.vendor_name as *mut _); |
| 285 |
} |
| 286 |
if !dev.friendly_name.is_null() { |
| 287 |
let _ = CString::from_raw(dev.friendly_name as *mut _); |
| 288 |
} |
| 289 |
} |
| 290 |
coll.device = ptr::null_mut(); |
| 291 |
coll.count = 0; |
| 292 |
Ok(()) |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
fn stream_init( |
| 297 |
&mut self, |
| 298 |
stream_name: Option<&CStr>, |
| 299 |
input_device: DeviceId, |
| 300 |
input_stream_params: Option<&StreamParamsRef>, |
| 301 |
output_device: DeviceId, |
| 302 |
output_stream_params: Option<&StreamParamsRef>, |
| 303 |
latency_frames: u32, |
| 304 |
// These params aren't sent to the server |
| 305 |
data_callback: ffi::cubeb_data_callback, |
| 306 |
state_callback: ffi::cubeb_state_callback, |
| 307 |
user_ptr: *mut c_void, |
| 308 |
) -> Result<Stream> { |
| 309 |
assert_not_in_callback(); |
| 310 |
|
| 311 |
let stream_name = stream_name.map(|name| name.to_bytes_with_nul().to_vec()); |
| 312 |
|
| 313 |
let input_stream_params = input_stream_params.map(messages::StreamParams::from); |
| 314 |
let output_stream_params = output_stream_params.map(messages::StreamParams::from); |
| 315 |
|
| 316 |
let params = messages::StreamCreateParams { |
| 317 |
stream_name, |
| 318 |
input_device: input_device as usize, |
| 319 |
input_stream_params, |
| 320 |
output_device: output_device as usize, |
| 321 |
output_stream_params, |
| 322 |
latency_frames, |
| 323 |
}; |
| 324 |
stream::init(self, params, data_callback, state_callback, user_ptr) |
| 325 |
} |
| 326 |
|
| 327 |
fn register_device_collection_changed( |
| 328 |
&mut self, |
| 329 |
devtype: DeviceType, |
| 330 |
collection_changed_callback: ffi::cubeb_device_collection_changed_callback, |
| 331 |
user_ptr: *mut c_void, |
| 332 |
) -> Result<()> { |
| 333 |
assert_not_in_callback(); |
| 334 |
|
| 335 |
if !self.device_collection_rpc { |
| 336 |
let mut fd = send_recv!(self.rpc(), |
| 337 |
ContextSetupDeviceCollectionCallback => |
| 338 |
ContextSetupDeviceCollectionCallback())?; |
| 339 |
|
| 340 |
let stream = unsafe { sys::Pipe::from_raw_handle(fd.platform_handle.take_handle()) }; |
| 341 |
|
| 342 |
let server = DeviceCollectionServer { |
| 343 |
input_device_callback: self.input_device_callback.clone(), |
| 344 |
output_device_callback: self.output_device_callback.clone(), |
| 345 |
}; |
| 346 |
|
| 347 |
self.rpc_handle() |
| 348 |
.bind_server(server, stream) |
| 349 |
.map_err(|_| Error::default())?; |
| 350 |
self.device_collection_rpc = true; |
| 351 |
} |
| 352 |
|
| 353 |
if devtype.contains(cubeb_backend::DeviceType::INPUT) { |
| 354 |
let mut cb = self.input_device_callback.lock().unwrap(); |
| 355 |
cb.cb = collection_changed_callback; |
| 356 |
cb.user_ptr = user_ptr as usize; |
| 357 |
} |
| 358 |
if devtype.contains(cubeb_backend::DeviceType::OUTPUT) { |
| 359 |
let mut cb = self.output_device_callback.lock().unwrap(); |
| 360 |
cb.cb = collection_changed_callback; |
| 361 |
cb.user_ptr = user_ptr as usize; |
| 362 |
} |
| 363 |
|
| 364 |
let enable = collection_changed_callback.is_some(); |
| 365 |
send_recv!(self.rpc(), |
| 366 |
ContextRegisterDeviceCollectionChanged(devtype.bits(), enable) => |
| 367 |
ContextRegisteredDeviceCollectionChanged) |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
impl Drop for ClientContext { |
| 372 |
fn drop(&mut self) { |
| 373 |
debug!("ClientContext dropped..."); |
| 374 |
let _ = send_recv!(self.rpc(), ClientDisconnect => ClientDisconnected); |
| 375 |
} |
| 376 |
} |
| 377 |
|
| 378 |
impl fmt::Debug for ClientContext { |
| 379 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 380 |
f.debug_struct("ClientContext") |
| 381 |
.field("_ops", &self._ops) |
| 382 |
.field("rpc", &self.rpc) |
| 383 |
.field("core", &self.rpc_thread) |
| 384 |
.field("cpu_pool", &"...") |
| 385 |
.finish() |
| 386 |
} |
| 387 |
} |