Debian Codegraph @

third_party/rust/audioipc2-client/src/stream.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
6 use crate::ClientContext;
7 use crate::{assert_not_in_callback, run_in_callback};
8 use audioipc::messages::{self, CallbackReq, CallbackResp, ClientMessage, ServerMessage};
9 use audioipc::shm::SharedMem;
10 use audioipc::{rpccore, sys};
11 use cubeb_backend::{ffi, DeviceRef, Error, InputProcessingParams, Result, Stream, StreamOps};
12 use std::ffi::{CStr, CString};
13 use std::os::raw::c_void;
14 use std::ptr;
15 use std::sync::mpsc;
16 use std::sync::{Arc, Mutex};
17
18 pub struct Device(ffi::cubeb_device);
19
20 impl Drop for Device {
21 fn drop(&mut self) {
22 unsafe {
23 if !self.0.input_name.is_null() {
24 let _ = CString::from_raw(self.0.input_name as *mut _);
25 }
26 if !self.0.output_name.is_null() {
27 let _ = CString::from_raw(self.0.output_name as *mut _);
28 }
29 }
30 }
31 }
32
33 // ClientStream's layout *must* match cubeb.c's `struct cubeb_stream` for the
34 // common fields.
35 #[repr(C)]
36 #[derive(Debug)]
37 pub struct ClientStream<'ctx> {
38 // This must be a reference to Context for cubeb, cubeb accesses
39 // stream methods via stream->context->ops
40 context: &'ctx ClientContext,
41 user_ptr: *mut c_void,
42 token: usize,
43 device_change_cb: Arc<Mutex<ffi::cubeb_device_changed_callback>>,
44 // Signals ClientStream that CallbackServer has dropped.
45 shutdown_rx: mpsc::Receiver<()>,
46 }
47
48 struct CallbackServer {
49 shm: SharedMem,
50 duplex_input: Option<Vec<u8>>,
51 data_cb: ffi::cubeb_data_callback,
52 state_cb: ffi::cubeb_state_callback,
53 user_ptr: usize,
54 device_change_cb: Arc<Mutex<ffi::cubeb_device_changed_callback>>,
55 // Signals ClientStream that CallbackServer has dropped.
56 _shutdown_tx: mpsc::Sender<()>,
57 }
58
59 impl rpccore::Server for CallbackServer {
60 type ServerMessage = CallbackReq;
61 type ClientMessage = CallbackResp;
62
63 fn process(&mut self, req: Self::ServerMessage) -> Self::ClientMessage {
64 match req {
65 CallbackReq::Data {
66 nframes,
67 input_frame_size,
68 output_frame_size,
69 } => {
70 trace!(
71 "stream_thread: Data Callback: nframes={} input_fs={} output_fs={}",
72 nframes,
73 input_frame_size,
74 output_frame_size,
75 );
76
77 let input_nbytes = nframes as usize * input_frame_size;
78 let output_nbytes = nframes as usize * output_frame_size;
79
80 // Input and output reuse the same shmem backing. Unfortunately, cubeb's data_callback isn't
81 // specified in such a way that would require the callee to consume all of the input before
82 // writing to the output (i.e., it is passed as two pointers that aren't expected to alias).
83 // That means we need to copy the input here.
84 if let Some(buf) = &mut self.duplex_input {
85 assert!(input_nbytes > 0);
86 assert!(buf.capacity() >= input_nbytes);
87 unsafe {
88 let input = self.shm.get_slice(input_nbytes).unwrap();
89 ptr::copy_nonoverlapping(input.as_ptr(), buf.as_mut_ptr(), input.len());
90 }
91 }
92
93 run_in_callback(|| {
94 let nframes = unsafe {
95 let input_ptr = if input_frame_size > 0 {
96 if let Some(buf) = &mut self.duplex_input {
97 buf.as_ptr()
98 } else {
99 self.shm.get_slice(input_nbytes).unwrap().as_ptr()
100 }
101 } else {
102 ptr::null()
103 };
104 let output_ptr = if output_frame_size > 0 {
105 self.shm.get_mut_slice(output_nbytes).unwrap().as_mut_ptr()
106 } else {
107 ptr::null_mut()
108 };
109
110 self.data_cb.unwrap()(
111 ptr::null_mut(), // https://github.com/kinetiknz/cubeb/issues/518
112 self.user_ptr as *mut c_void,
113 input_ptr as *const _,
114 output_ptr as *mut _,
115 nframes as _,
116 )
117 };
118
119 CallbackResp::Data(nframes as isize)
120 })
121 }
122 CallbackReq::State(state) => {
123 trace!("stream_thread: State Callback: {:?}", state);
124 run_in_callback(|| unsafe {
125 self.state_cb.unwrap()(ptr::null_mut(), self.user_ptr as *mut _, state);
126 });
127
128 CallbackResp::State
129 }
130 CallbackReq::DeviceChange => {
131 run_in_callback(|| {
132 let cb = *self.device_change_cb.lock().unwrap();
133 if let Some(cb) = cb {
134 unsafe {
135 cb(self.user_ptr as *mut _);
136 }
137 } else {
138 warn!("DeviceChange received with null callback");
139 }
140 });
141
142 CallbackResp::DeviceChange
143 }
144 }
145 }
146 }
147
148 impl<'ctx> ClientStream<'ctx> {
149 fn init(
150 ctx: &'ctx ClientContext,
151 params: messages::StreamCreateParams,
152 data_callback: ffi::cubeb_data_callback,
153 state_callback: ffi::cubeb_state_callback,
154 user_ptr: *mut c_void,
155 ) -> Result<Stream> {
156 assert_not_in_callback();
157 let has_input = params.input_stream_params.is_some();
158 let has_output = params.output_stream_params.is_some();
159
160 let rpc = ctx.rpc();
161 let mut data = send_recv!(rpc, StreamCreate(params) => StreamCreated())?;
162
163 debug!(
164 "token = {}, handle = {:?} area_size = {:?}",
165 data.token, data.shm_handle, data.shm_area_size
166 );
167
168 let shm =
169 match unsafe { SharedMem::from(data.shm_handle.take_handle(), data.shm_area_size) } {
170 Ok(shm) => shm,
171 Err(e) => {
172 warn!(
173 "SharedMem client mapping failed (size={}, err={:?})",
174 data.shm_area_size, e
175 );
176 return Err(Error::default());
177 }
178 };
179
180 let duplex_input = if has_input && has_output {
181 let mut duplex_input = Vec::new();
182 match duplex_input.try_reserve_exact(data.shm_area_size) {
183 Ok(()) => Some(duplex_input),
184 Err(e) => {
185 warn!(
186 "duplex_input allocation failed (size={}, err={:?})",
187 data.shm_area_size, e
188 );
189 return Err(Error::default());
190 }
191 }
192 } else {
193 None
194 };
195
196 let mut stream = send_recv!(rpc, StreamInit(data.token) => StreamInitialized())?;
197 let stream = unsafe { sys::Pipe::from_raw_handle(stream.take_handle()) };
198
199 let user_data = user_ptr as usize;
200
201 let null_cb: ffi::cubeb_device_changed_callback = None;
202 let device_change_cb = Arc::new(Mutex::new(null_cb));
203
204 let (_shutdown_tx, shutdown_rx) = mpsc::channel();
205
206 let server = CallbackServer {
207 shm,
208 duplex_input,
209 data_cb: data_callback,
210 state_cb: state_callback,
211 user_ptr: user_data,
212 device_change_cb: device_change_cb.clone(),
213 _shutdown_tx,
214 };
215
216 ctx.callback_handle()
217 .bind_server(server, stream)
218 .map_err(|_| Error::default())?;
219
220 let stream = Box::into_raw(Box::new(ClientStream {
221 context: ctx,
222 user_ptr,
223 token: data.token,
224 device_change_cb,
225 shutdown_rx,
226 }));
227 Ok(unsafe { Stream::from_ptr(stream as *mut _) })
228 }
229 }
230
231 impl Drop for ClientStream<'_> {
232 fn drop(&mut self) {
233 debug!("ClientStream drop");
234 let _ = send_recv!(self.context.rpc(), StreamDestroy(self.token) => StreamDestroyed);
235 debug!("ClientStream drop - stream destroyed");
236 // Wait for CallbackServer to shutdown. The remote server drops the RPC
237 // connection during StreamDestroy, which will cause CallbackServer to drop
238 // once the connection close is detected. Dropping CallbackServer will
239 // cause the shutdown channel to error on recv, which we rely on to
240 // synchronize with CallbackServer dropping.
241 let _ = self.shutdown_rx.recv();
242 debug!("ClientStream dropped");
243 }
244 }
245
246 impl StreamOps for ClientStream<'_> {
247 fn start(&mut self) -> Result<()> {
248 assert_not_in_callback();
249 let rpc = self.context.rpc();
250 send_recv!(rpc, StreamStart(self.token) => StreamStarted)
251 }
252
253 fn stop(&mut self) -> Result<()> {
254 assert_not_in_callback();
255 let rpc = self.context.rpc();
256 send_recv!(rpc, StreamStop(self.token) => StreamStopped)
257 }
258
259 fn position(&mut self) -> Result<u64> {
260 assert_not_in_callback();
261 let rpc = self.context.rpc();
262 send_recv!(rpc, StreamGetPosition(self.token) => StreamPosition())
263 }
264
265 fn latency(&mut self) -> Result<u32> {
266 assert_not_in_callback();
267 let rpc = self.context.rpc();
268 send_recv!(rpc, StreamGetLatency(self.token) => StreamLatency())
269 }
270
271 fn input_latency(&mut self) -> Result<u32> {
272 assert_not_in_callback();
273 let rpc = self.context.rpc();
274 send_recv!(rpc, StreamGetInputLatency(self.token) => StreamInputLatency())
275 }
276
277 fn set_volume(&mut self, volume: f32) -> Result<()> {
278 assert_not_in_callback();
279 let rpc = self.context.rpc();
280 send_recv!(rpc, StreamSetVolume(self.token, volume) => StreamVolumeSet)
281 }
282
283 fn set_name(&mut self, name: &CStr) -> Result<()> {
284 assert_not_in_callback();
285 let rpc = self.context.rpc();
286 send_recv!(rpc, StreamSetName(self.token, name.to_owned()) => StreamNameSet)
287 }
288
289 fn current_device(&mut self) -> Result<&DeviceRef> {
290 assert_not_in_callback();
291 let rpc = self.context.rpc();
292 match send_recv!(rpc, StreamGetCurrentDevice(self.token) => StreamCurrentDevice()) {
293 Ok(d) => Ok(unsafe { DeviceRef::from_ptr(Box::into_raw(Box::new(d.into()))) }),
294 Err(e) => Err(e),
295 }
296 }
297
298 fn set_input_mute(&mut self, mute: bool) -> Result<()> {
299 assert_not_in_callback();
300 let rpc = self.context.rpc();
301 send_recv!(rpc, StreamSetInputMute(self.token, mute) => StreamInputMuteSet)
302 }
303
304 fn set_input_processing_params(&mut self, params: InputProcessingParams) -> Result<()> {
305 assert_not_in_callback();
306 let rpc = self.context.rpc();
307 send_recv!(rpc, StreamSetInputProcessingParams(self.token, params.bits()) => StreamInputProcessingParamsSet)
308 }
309
310 fn device_destroy(&mut self, device: &DeviceRef) -> Result<()> {
311 assert_not_in_callback();
312 if device.as_ptr().is_null() {
313 Err(Error::error())
314 } else {
315 unsafe {
316 let _: Box<Device> = Box::from_raw(device.as_ptr() as *mut _);
317 }
318 Ok(())
319 }
320 }
321
322 fn register_device_changed_callback(
323 &mut self,
324 device_changed_callback: ffi::cubeb_device_changed_callback,
325 ) -> Result<()> {
326 assert_not_in_callback();
327 let rpc = self.context.rpc();
328 let enable = device_changed_callback.is_some();
329 *self.device_change_cb.lock().unwrap() = device_changed_callback;
330 send_recv!(rpc, StreamRegisterDeviceChangeCallback(self.token, enable) => StreamRegisterDeviceChangeCallback)
331 }
332 }
333
334 pub fn init(
335 ctx: &ClientContext,
336 params: messages::StreamCreateParams,
337 data_callback: ffi::cubeb_data_callback,
338 state_callback: ffi::cubeb_state_callback,
339 user_ptr: *mut c_void,
340 ) -> Result<Stream> {
341 let stm = ClientStream::init(ctx, params, data_callback, state_callback, user_ptr)?;
342 debug_assert_eq!(stm.user_ptr(), user_ptr);
343 Ok(stm)
344 }