/
output.rs
345 lines (285 loc) · 12.7 KB
/
output.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Symphonia
// Copyright (c) 2019-2021 The Project Symphonia Developers.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Platform-dependant Audio Outputs
use std::result;
use symphonia::core::audio::{AudioBufferRef, SignalSpec};
use symphonia::core::units::Duration;
pub trait AudioOutput {
fn write(&mut self, decoded: AudioBufferRef<'_>) -> Result<()>;
fn flush(&mut self);
}
#[allow(dead_code)]
#[allow(clippy::enum_variant_names)]
#[derive(Debug)]
pub enum AudioOutputError {
OpenStreamError,
PlayStreamError,
StreamClosedError,
}
pub type Result<T> = result::Result<T, AudioOutputError>;
#[cfg(target_os = "linux")]
mod pulseaudio {
use super::{AudioOutput, AudioOutputError, Result};
use symphonia::core::audio::*;
use symphonia::core::units::Duration;
use libpulse_binding as pulse;
use libpulse_simple_binding as psimple;
use log::{error, warn};
pub struct PulseAudioOutput {
pa: psimple::Simple,
sample_buf: RawSampleBuffer<f32>,
}
impl PulseAudioOutput {
pub fn try_open(spec: SignalSpec, duration: Duration) -> Result<Box<dyn AudioOutput>> {
// An interleaved buffer is required to send data to PulseAudio. Use a SampleBuffer to
// move data between Symphonia AudioBuffers and the byte buffers required by PulseAudio.
let sample_buf = RawSampleBuffer::<f32>::new(duration, spec);
// Create a PulseAudio stream specification.
let pa_spec = pulse::sample::Spec {
format: pulse::sample::Format::FLOAT32NE,
channels: spec.channels.count() as u8,
rate: spec.rate,
};
assert!(pa_spec.is_valid());
let pa_ch_map = map_channels_to_pa_channelmap(spec.channels);
// PulseAudio seems to not play very short audio buffers, use these custom buffer
// attributes for very short audio streams.
//
// let pa_buf_attr = pulse::def::BufferAttr {
// maxlength: std::u32::MAX,
// tlength: 1024,
// prebuf: std::u32::MAX,
// minreq: std::u32::MAX,
// fragsize: std::u32::MAX,
// };
// Create a PulseAudio connection.
let pa_result = psimple::Simple::new(
None, // Use default server
"Symphonia Player", // Application name
pulse::stream::Direction::Playback, // Playback stream
None, // Default playback device
"Music", // Description of the stream
&pa_spec, // Signal specificaiton
pa_ch_map.as_ref(), // Channel map
None // Custom buffering attributes
);
match pa_result {
Ok(pa) => {
Ok(Box::new(PulseAudioOutput { pa, sample_buf }))
}
Err(err) => {
error!("audio output stream open error: {}", err);
Err(AudioOutputError::OpenStreamError)
}
}
}
}
impl AudioOutput for PulseAudioOutput {
fn write(&mut self, decoded: AudioBufferRef<'_>) -> Result<()> {
// Do nothing if there are no audio frames.
if decoded.frames() == 0 {
return Ok(())
}
// Interleave samples from the audio buffer into the sample buffer.
self.sample_buf.copy_interleaved_ref(decoded);
// Write interleaved samples to PulseAudio.
match self.pa.write(self.sample_buf.as_bytes()) {
Err(err) => {
error!("audio output stream write error: {}", err);
Err(AudioOutputError::StreamClosedError)
}
_ => Ok(())
}
}
fn flush(&mut self) {
// Flush is best-effort, ignore the returned result.
let _ = self.pa.drain();
}
}
/// Maps a set of Symphonia `Channels` to a PulseAudio channel map.
fn map_channels_to_pa_channelmap(channels: Channels) -> Option<pulse::channelmap::Map> {
let mut map: pulse::channelmap::Map = Default::default();
map.init();
map.set_len(channels.count() as u8);
let is_mono = channels.count() == 1;
for (i, channel) in channels.iter().enumerate() {
map.get_mut()[i] = match channel {
Channels::FRONT_LEFT if is_mono => pulse::channelmap::Position::Mono,
Channels::FRONT_LEFT => pulse::channelmap::Position::FrontLeft,
Channels::FRONT_RIGHT => pulse::channelmap::Position::FrontRight,
Channels::FRONT_CENTRE => pulse::channelmap::Position::FrontCenter,
Channels::REAR_LEFT => pulse::channelmap::Position::RearLeft,
Channels::REAR_CENTRE => pulse::channelmap::Position::RearCenter,
Channels::REAR_RIGHT => pulse::channelmap::Position::RearRight,
Channels::LFE1 => pulse::channelmap::Position::Lfe,
Channels::FRONT_LEFT_CENTRE => pulse::channelmap::Position::FrontLeftOfCenter,
Channels::FRONT_RIGHT_CENTRE => pulse::channelmap::Position::FrontRightOfCenter,
Channels::SIDE_LEFT => pulse::channelmap::Position::SideLeft,
Channels::SIDE_RIGHT => pulse::channelmap::Position::SideRight,
Channels::TOP_CENTRE => pulse::channelmap::Position::TopCenter,
Channels::TOP_FRONT_LEFT => pulse::channelmap::Position::TopFrontLeft,
Channels::TOP_FRONT_CENTRE => pulse::channelmap::Position::TopFrontCenter,
Channels::TOP_FRONT_RIGHT => pulse::channelmap::Position::TopFrontRight,
Channels::TOP_REAR_LEFT => pulse::channelmap::Position::TopRearLeft,
Channels::TOP_REAR_CENTRE => pulse::channelmap::Position::TopRearCenter,
Channels::TOP_REAR_RIGHT => pulse::channelmap::Position::TopRearRight,
_ => {
// If a Symphonia channel cannot map to a PulseAudio position then return None
// because PulseAudio will not be able to open a stream with invalid channels.
warn!("failed to map channel {:?} to output", channel);
return None;
}
}
}
Some(map)
}
}
#[cfg(not(target_os = "linux"))]
mod cpal {
use super::{AudioOutput, AudioOutputError, Result};
use symphonia::core::audio::{AudioBufferRef, SampleBuffer, SignalSpec, RawSample};
use symphonia::core::conv::ConvertibleSample;
use symphonia::core::units::Duration;
use cpal;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use rb::*;
use log::error;
pub struct CpalAudioOutput;
trait AudioOutputSample :
cpal::Sample +
ConvertibleSample +
RawSample +
std::marker::Send +
'static {}
impl AudioOutputSample for f32 { }
impl AudioOutputSample for i16 { }
impl AudioOutputSample for u16 { }
impl CpalAudioOutput {
pub fn try_open(spec: SignalSpec, duration: Duration) -> Result<Box<dyn AudioOutput>> {
// Get default host.
let host = cpal::default_host();
// Get the default audio output device.
let device = match host.default_output_device() {
Some(device) => device,
_ => {
error!("failed to get default audio output device");
return Err(AudioOutputError::OpenStreamError);
}
};
let config = match device.default_output_config() {
Ok(config) => config,
Err(err) => {
error!("failed to get default audio output device config: {}", err);
return Err(AudioOutputError::OpenStreamError);
}
};
// Select proper playback routine based on sample format.
match config.sample_format() {
cpal::SampleFormat::F32 => {
CpalAudioOutputImpl::<f32>::try_open(spec, duration, &device)
}
cpal::SampleFormat::I16 => {
CpalAudioOutputImpl::<i16>::try_open(spec, duration, &device)
}
cpal::SampleFormat::U16 => {
CpalAudioOutputImpl::<u16>::try_open(spec, duration, &device)
}
}
}
}
struct CpalAudioOutputImpl<T: AudioOutputSample>
where
T: AudioOutputSample
{
ring_buf_producer: rb::Producer<T>,
sample_buf: SampleBuffer<T>,
stream: cpal::Stream,
}
impl<T: AudioOutputSample> CpalAudioOutputImpl<T>
{
pub fn try_open(
spec: SignalSpec,
duration: Duration,
device: &cpal::Device
) -> Result<Box<dyn AudioOutput>>
{
// Output audio stream config.
let config = cpal::StreamConfig {
channels: spec.channels.count() as cpal::ChannelCount,
sample_rate: cpal::SampleRate(spec.rate),
buffer_size: cpal::BufferSize::Default,
};
// Instantiate a ring buffer capable of buffering 8K (arbitrarily chosen) samples.
let ring_buf = SpscRb::new(8 * 1024);
let (ring_buf_producer, ring_buf_consumer) = (ring_buf.producer(), ring_buf.consumer());
let stream_result = device.build_output_stream(
&config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
// Write out as many samples as possible from the ring buffer to the audio
// output.
let written = ring_buf_consumer.read(data).unwrap_or(0);
// Mute any remaining samples.
data[written..].iter_mut().for_each(|s| *s = T::MID);
},
move |err| {
error!("audio output error: {}", err)
},
);
if let Err(err) = stream_result {
error!("audio output stream open error: {}", err);
return Err(AudioOutputError::OpenStreamError);
}
let stream = stream_result.unwrap();
// Start the output stream.
if let Err(err) = stream.play() {
error!("audio output stream play error: {}", err);
return Err(AudioOutputError::PlayStreamError);
}
let sample_buf = SampleBuffer::<T>::new(duration, spec);
Ok(Box::new(CpalAudioOutputImpl { ring_buf_producer, sample_buf, stream }))
}
}
impl<T: AudioOutputSample> AudioOutput for CpalAudioOutputImpl<T>
{
fn write(&mut self, decoded: AudioBufferRef<'_>) -> Result<()> {
// Do nothing if there are no audio frames.
if decoded.frames() == 0 {
return Ok(())
}
// Audio samples must be interleaved for cpal. Interleave the samples in the audio
// buffer into the sample buffer.
self.sample_buf.copy_interleaved_ref(decoded);
let mut i = 0;
// Write out all samples in the sample buffer to the ring buffer.
while i < self.sample_buf.len() {
let writeable_samples = &self.sample_buf.samples()[i..];
// Write as many samples as possible to the ring buffer. This blocks until some
// samples are written or the consumer has been destroyed (None is returned).
if let Some(written) = self.ring_buf_producer.write_blocking(writeable_samples) {
i += written;
}
else {
// Consumer destroyed, return an error.
return Err(AudioOutputError::StreamClosedError);
}
}
Ok(())
}
fn flush(&mut self) {
// Flush is best-effort, ignore the returned result.
let _ = self.stream.pause();
}
}
}
#[cfg(target_os = "linux")]
pub fn try_open(spec: SignalSpec, duration: Duration) -> Result<Box<dyn AudioOutput>> {
pulseaudio::PulseAudioOutput::try_open(spec, duration)
}
#[cfg(not(target_os = "linux"))]
pub fn try_open(spec: SignalSpec, duration: Duration) -> Result<Box<dyn AudioOutput>> {
cpal::CpalAudioOutput::try_open(spec, duration)
}