Debian Codegraph @

third_party/rust/cubeb/src/stream.rs

raw
1 // Copyright © 2017-2018 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 cubeb_core;
7 use ffi;
8 use std::ffi::CString;
9 use std::marker::PhantomData;
10 use std::mem::ManuallyDrop;
11 use std::os::raw::{c_long, c_void};
12 use std::slice::{from_raw_parts, from_raw_parts_mut};
13 use std::{ops, panic, ptr};
14 use {ContextRef, DeviceId, Error, Result, State, StreamParamsRef};
15
16 /// User supplied data callback.
17 ///
18 /// - Calling other cubeb functions from this callback is unsafe.
19 /// - The code in the callback should be non-blocking.
20 /// - Returning less than the number of frames this callback asks for or
21 /// provides puts the stream in drain mode. This callback will not be called
22 /// again, and the state callback will be called with CUBEB_STATE_DRAINED when
23 /// all the frames have been output.
24 ///
25 /// # Arguments
26 ///
27 /// - `input_buffer`: A slice containing the input data, zero-len if this is an output-only stream.
28 /// - `output_buffer`: A mutable slice to be filled with audio samples, zero-len if this is an input-only stream.
29 ///
30 /// # Return value
31 ///
32 /// If the stream has output, this is the number of frames written to the output buffer. In this
33 /// case, if this number is less than the length of the output buffer, then the stream will start to
34 /// drain.
35 ///
36 /// If the stream is input only, then returning the length of the input buffer indicates data has
37 /// been read. In this case, a value less than that will result in the stream being stopped.
38 pub type DataCallback<F> = dyn FnMut(&[F], &mut [F]) -> isize + Send + Sync + 'static;
39
40 /// User supplied state callback.
41 ///
42 /// # Arguments
43 ///
44 /// `state`: The new state of the stream
45 pub type StateCallback = dyn FnMut(State) + Send + Sync + 'static;
46
47 /// User supplied callback called when the underlying device changed.
48 pub type DeviceChangedCallback = dyn FnMut() + Send + Sync + 'static;
49
50 pub struct StreamCallbacks<F> {
51 pub(crate) data: Box<DataCallback<F>>,
52 pub(crate) state: Box<StateCallback>,
53 pub(crate) device_changed: Option<Box<DeviceChangedCallback>>,
54 }
55
56 /// Audio input/output stream
57 ///
58 /// # Example
59 /// ```no_run
60 /// extern crate cubeb;
61 /// use std::thread;
62 /// use std::time::Duration;
63 ///
64 /// type Frame = cubeb::MonoFrame<f32>;
65 ///
66 /// fn main() {
67 /// let ctx = cubeb::init("Cubeb tone example").unwrap();
68 ///
69 /// let params = cubeb::StreamParamsBuilder::new()
70 /// .format(cubeb::SampleFormat::Float32LE)
71 /// .rate(44_100)
72 /// .channels(1)
73 /// .layout(cubeb::ChannelLayout::MONO)
74 /// .prefs(cubeb::StreamPrefs::NONE)
75 /// .take();
76 ///
77 /// let phase_inc = 440.0 / 44_100.0;
78 /// let mut phase = 0.0;
79 /// let volume = 0.25;
80 ///
81 /// let mut builder = cubeb::StreamBuilder::<Frame>::new();
82 /// builder
83 /// .name("Cubeb Square Wave")
84 /// .default_output(&params)
85 /// .latency(0x1000)
86 /// .data_callback(move |_, output| {
87 /// // Generate a square wave
88 /// for x in output.iter_mut() {
89 /// x.m = if phase < 0.5 { volume } else { -volume };
90 /// phase = (phase + phase_inc) % 1.0;
91 /// }
92 ///
93 /// output.len() as isize
94 /// })
95 /// .state_callback(|state| {
96 /// println!("stream {:?}", state);
97 /// });
98 /// let stream = builder.init(&ctx).expect("Failed to create stream.");
99 ///
100 /// // Start playback
101 /// stream.start().unwrap();
102 ///
103 /// // Play for 1/2 second
104 /// thread::sleep(Duration::from_millis(500));
105 ///
106 /// // Shutdown
107 /// stream.stop().unwrap();
108 /// }
109 /// ```
110 pub struct Stream<F>(ManuallyDrop<cubeb_core::Stream>, PhantomData<*const F>);
111
112 impl<F> Stream<F> {
113 fn new(s: cubeb_core::Stream) -> Stream<F> {
114 Stream(ManuallyDrop::new(s), PhantomData)
115 }
116 }
117
118 impl<F> Drop for Stream<F> {
119 fn drop(&mut self) {
120 let user_ptr = self.user_ptr();
121 unsafe { ManuallyDrop::drop(&mut self.0) };
122 let _ = unsafe { Box::from_raw(user_ptr as *mut StreamCallbacks<F>) };
123 }
124 }
125
126 impl<F> ops::Deref for Stream<F> {
127 type Target = cubeb_core::Stream;
128
129 fn deref(&self) -> &Self::Target {
130 &self.0
131 }
132 }
133
134 /// Stream builder
135 ///
136 /// ```no_run
137 /// use cubeb::{Context, MonoFrame, Sample};
138 /// use std::f32::consts::PI;
139 /// use std::thread;
140 /// use std::time::Duration;
141 ///
142 /// const SAMPLE_FREQUENCY: u32 = 48_000;
143 /// const STREAM_FORMAT: cubeb::SampleFormat = cubeb::SampleFormat::S16LE;
144 /// type Frame = MonoFrame<i16>;
145 ///
146 /// let ctx = Context::init(None, None).unwrap();
147 ///
148 /// let params = cubeb::StreamParamsBuilder::new()
149 /// .format(STREAM_FORMAT)
150 /// .rate(SAMPLE_FREQUENCY)
151 /// .channels(1)
152 /// .layout(cubeb::ChannelLayout::MONO)
153 /// .take();
154 ///
155 /// let mut position = 0u32;
156 ///
157 /// let mut builder = cubeb::StreamBuilder::<Frame>::new();
158 /// builder
159 /// .name("Cubeb tone (mono)")
160 /// .default_output(&params)
161 /// .latency(0x1000)
162 /// .data_callback(move |_, output| {
163 /// // generate our test tone on the fly
164 /// for f in output.iter_mut() {
165 /// // North American dial tone
166 /// let t1 = (2.0 * PI * 350.0 * position as f32 / SAMPLE_FREQUENCY as f32).sin();
167 /// let t2 = (2.0 * PI * 440.0 * position as f32 / SAMPLE_FREQUENCY as f32).sin();
168 ///
169 /// f.m = i16::from_float(0.5 * (t1 + t2));
170 ///
171 /// position += 1;
172 /// }
173 /// output.len() as isize
174 /// })
175 /// .state_callback(|state| {
176 /// println!("stream {:?}", state);
177 /// });
178 ///
179 /// let stream = builder.init(&ctx).expect("Failed to create cubeb stream");
180 /// ```
181 pub struct StreamBuilder<'a, F> {
182 name: Option<CString>,
183 input: Option<(DeviceId, &'a StreamParamsRef)>,
184 output: Option<(DeviceId, &'a StreamParamsRef)>,
185 latency: Option<u32>,
186 data_cb: Option<Box<DataCallback<F>>>,
187 state_cb: Option<Box<StateCallback>>,
188 device_changed_cb: Option<Box<DeviceChangedCallback>>,
189 }
190
191 impl<'a, F> StreamBuilder<'a, F> {
192 pub fn new() -> StreamBuilder<'a, F> {
193 Default::default()
194 }
195
196 /// User supplied data callback, see [`DataCallback`]
197 pub fn data_callback<D>(&mut self, cb: D) -> &mut Self
198 where
199 D: FnMut(&[F], &mut [F]) -> isize + Send + Sync + 'static,
200 {
201 self.data_cb = Some(Box::new(cb) as Box<DataCallback<F>>);
202 self
203 }
204
205 /// User supplied state callback, see [`StateCallback`]
206 pub fn state_callback<S>(&mut self, cb: S) -> &mut Self
207 where
208 S: FnMut(State) + Send + Sync + 'static,
209 {
210 self.state_cb = Some(Box::new(cb) as Box<StateCallback>);
211 self
212 }
213
214 /// A name for this stream.
215 pub fn name<T: Into<Vec<u8>>>(&mut self, name: T) -> &mut Self {
216 self.name = Some(CString::new(name).unwrap());
217 self
218 }
219
220 /// Use the default input device with `params`
221 ///
222 /// Optional if the stream is output only
223 pub fn default_input(&mut self, params: &'a StreamParamsRef) -> &mut Self {
224 self.input = Some((ptr::null(), params));
225 self
226 }
227
228 /// Use a specific input device with `params`
229 ///
230 /// Optional if the stream is output only
231 pub fn input(&mut self, device: DeviceId, params: &'a StreamParamsRef) -> &mut Self {
232 self.input = Some((device, params));
233 self
234 }
235
236 /// Use the default output device with `params`
237 ///
238 /// Optional if the stream is input only
239 pub fn default_output(&mut self, params: &'a StreamParamsRef) -> &mut Self {
240 self.output = Some((ptr::null(), params));
241 self
242 }
243
244 /// Use a specific output device with `params`
245 ///
246 /// Optional if the stream is input only
247 pub fn output(&mut self, device: DeviceId, params: &'a StreamParamsRef) -> &mut Self {
248 self.output = Some((device, params));
249 self
250 }
251
252 /// Stream latency in frames.
253 ///
254 /// Valid range is [1, 96000].
255 pub fn latency(&mut self, latency: u32) -> &mut Self {
256 self.latency = Some(latency);
257 self
258 }
259
260 /// User supplied callback called when the underlying device changed.
261 ///
262 /// See [`StateCallback`]
263 ///
264 /// Optional
265 pub fn device_changed_cb<CB>(&mut self, cb: CB) -> &mut Self
266 where
267 CB: FnMut() + Send + Sync + 'static,
268 {
269 self.device_changed_cb = Some(Box::new(cb) as Box<DeviceChangedCallback>);
270 self
271 }
272
273 /// Build the stream
274 pub fn init(self, ctx: &ContextRef) -> Result<Stream<F>> {
275 if self.data_cb.is_none() || self.state_cb.is_none() {
276 return Err(Error::error());
277 }
278
279 let has_device_changed = self.device_changed_cb.is_some();
280 let cbs = Box::into_raw(Box::new(StreamCallbacks {
281 data: self.data_cb.unwrap(),
282 state: self.state_cb.unwrap(),
283 device_changed: self.device_changed_cb,
284 }));
285
286 let stream_name = self.name.as_deref();
287 let (input_device, input_stream_params) =
288 self.input.map_or((ptr::null(), None), |x| (x.0, Some(x.1)));
289 let (output_device, output_stream_params) = self
290 .output
291 .map_or((ptr::null(), None), |x| (x.0, Some(x.1)));
292 let latency = self.latency.unwrap_or(1);
293 let data_callback: ffi::cubeb_data_callback = Some(data_cb_c::<F>);
294 let state_callback: ffi::cubeb_state_callback = Some(state_cb_c::<F>);
295
296 let stream = unsafe {
297 ctx.stream_init(
298 stream_name,
299 input_device,
300 input_stream_params,
301 output_device,
302 output_stream_params,
303 latency,
304 data_callback,
305 state_callback,
306 cbs as *mut _,
307 )?
308 };
309 if has_device_changed {
310 let device_changed_callback: ffi::cubeb_device_changed_callback =
311 Some(device_changed_cb_c::<F>);
312 stream.register_device_changed_callback(device_changed_callback)?;
313 }
314 Ok(Stream::new(stream))
315 }
316 }
317
318 impl<'a, F> Default for StreamBuilder<'a, F> {
319 fn default() -> Self {
320 StreamBuilder {
321 name: None,
322 input: None,
323 output: None,
324 latency: None,
325 data_cb: None,
326 state_cb: None,
327 device_changed_cb: None,
328 }
329 }
330 }
331
332 // C callable callbacks
333 unsafe extern "C" fn data_cb_c<F>(
334 _: *mut ffi::cubeb_stream,
335 user_ptr: *mut c_void,
336 input_buffer: *const c_void,
337 output_buffer: *mut c_void,
338 nframes: c_long,
339 ) -> c_long {
340 let ok = panic::catch_unwind(|| {
341 let cbs = &mut *(user_ptr as *mut StreamCallbacks<F>);
342 let input: &[F] = if input_buffer.is_null() {
343 &[]
344 } else {
345 from_raw_parts(input_buffer as *const _, nframes as usize)
346 };
347 let output: &mut [F] = if output_buffer.is_null() {
348 &mut []
349 } else {
350 from_raw_parts_mut(output_buffer as *mut _, nframes as usize)
351 };
352 (cbs.data)(input, output) as c_long
353 });
354 ok.unwrap_or(0)
355 }
356
357 unsafe extern "C" fn state_cb_c<F>(
358 _: *mut ffi::cubeb_stream,
359 user_ptr: *mut c_void,
360 state: ffi::cubeb_state,
361 ) {
362 let ok = panic::catch_unwind(|| {
363 let state = State::from(state);
364 let cbs = &mut *(user_ptr as *mut StreamCallbacks<F>);
365 (cbs.state)(state);
366 });
367 ok.expect("State callback panicked");
368 }
369
370 unsafe extern "C" fn device_changed_cb_c<F>(user_ptr: *mut c_void) {
371 let ok = panic::catch_unwind(|| {
372 let cbs = &mut *(user_ptr as *mut StreamCallbacks<F>);
373 if let Some(ref mut device_changed) = cbs.device_changed {
374 device_changed();
375 }
376 });
377 ok.expect("Device changed callback panicked");
378 }