1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/audio/pulse/pulse_util.h"
7 #include "base/logging.h"
8 #include "base/time/time.h"
9 #include "media/audio/audio_manager_base.h"
10 #include "media/audio/audio_parameters.h"
18 pa_channel_position
ChromiumToPAChannelPosition(Channels channel
) {
20 // PulseAudio does not differentiate between left/right and
21 // stereo-left/stereo-right, both translate to front-left/front-right.
23 return PA_CHANNEL_POSITION_FRONT_LEFT
;
25 return PA_CHANNEL_POSITION_FRONT_RIGHT
;
27 return PA_CHANNEL_POSITION_FRONT_CENTER
;
29 return PA_CHANNEL_POSITION_LFE
;
31 return PA_CHANNEL_POSITION_REAR_LEFT
;
33 return PA_CHANNEL_POSITION_REAR_RIGHT
;
35 return PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER
;
37 return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER
;
39 return PA_CHANNEL_POSITION_REAR_CENTER
;
41 return PA_CHANNEL_POSITION_SIDE_LEFT
;
43 return PA_CHANNEL_POSITION_SIDE_RIGHT
;
45 NOTREACHED() << "Invalid channel: " << channel
;
46 return PA_CHANNEL_POSITION_INVALID
;
52 // static, pa_stream_success_cb_t
53 void StreamSuccessCallback(pa_stream
* s
, int error
, void* mainloop
) {
54 pa_threaded_mainloop
* pa_mainloop
=
55 static_cast<pa_threaded_mainloop
*>(mainloop
);
56 pa_threaded_mainloop_signal(pa_mainloop
, 0);
59 // |pa_context| and |pa_stream| state changed cb.
60 void ContextStateCallback(pa_context
* context
, void* mainloop
) {
61 pa_threaded_mainloop
* pa_mainloop
=
62 static_cast<pa_threaded_mainloop
*>(mainloop
);
63 pa_threaded_mainloop_signal(pa_mainloop
, 0);
66 pa_sample_format_t
BitsToPASampleFormat(int bits_per_sample
) {
67 switch (bits_per_sample
) {
71 return PA_SAMPLE_S16LE
;
73 return PA_SAMPLE_S24LE
;
75 return PA_SAMPLE_S32LE
;
77 NOTREACHED() << "Invalid bits per sample: " << bits_per_sample
;
78 return PA_SAMPLE_INVALID
;
82 pa_channel_map
ChannelLayoutToPAChannelMap(ChannelLayout channel_layout
) {
83 pa_channel_map channel_map
;
84 pa_channel_map_init(&channel_map
);
86 channel_map
.channels
= ChannelLayoutToChannelCount(channel_layout
);
87 for (Channels ch
= LEFT
; ch
<= CHANNELS_MAX
;
88 ch
= static_cast<Channels
>(ch
+ 1)) {
89 int channel_index
= ChannelOrder(channel_layout
, ch
);
90 if (channel_index
< 0)
93 channel_map
.map
[channel_index
] = ChromiumToPAChannelPosition(ch
);
99 void WaitForOperationCompletion(pa_threaded_mainloop
* pa_mainloop
,
100 pa_operation
* operation
) {
102 DLOG(WARNING
) << "Operation is NULL";
106 while (pa_operation_get_state(operation
) == PA_OPERATION_RUNNING
)
107 pa_threaded_mainloop_wait(pa_mainloop
);
109 pa_operation_unref(operation
);
112 int GetHardwareLatencyInBytes(pa_stream
* stream
,
114 int bytes_per_frame
) {
117 pa_usec_t latency_micros
= 0;
118 if (pa_stream_get_latency(stream
, &latency_micros
, &negative
) != 0)
124 return latency_micros
* sample_rate
* bytes_per_frame
/
125 base::Time::kMicrosecondsPerSecond
;
128 // Helper macro for CreateInput/OutputStream() to avoid code spam and
130 #define RETURN_ON_FAILURE(expression, message) do { \
131 if (!(expression)) { \
132 DLOG(ERROR) << message; \
137 bool CreateInputStream(pa_threaded_mainloop
* mainloop
,
140 const AudioParameters
& params
,
141 const std::string
& device_id
,
142 pa_stream_notify_cb_t stream_callback
,
147 // Set sample specifications.
148 pa_sample_spec sample_specifications
;
149 sample_specifications
.format
= BitsToPASampleFormat(
150 params
.bits_per_sample());
151 sample_specifications
.rate
= params
.sample_rate();
152 sample_specifications
.channels
= params
.channels();
154 // Get channel mapping and open recording stream.
155 pa_channel_map source_channel_map
= ChannelLayoutToPAChannelMap(
156 params
.channel_layout());
157 pa_channel_map
* map
= (source_channel_map
.channels
!= 0) ?
158 &source_channel_map
: NULL
;
160 // Create a new recording stream.
161 *stream
= pa_stream_new(context
, "RecordStream", &sample_specifications
, map
);
162 RETURN_ON_FAILURE(*stream
, "failed to create PA recording stream");
164 pa_stream_set_state_callback(*stream
, stream_callback
, user_data
);
166 // Set server-side capture buffer metrics. Detailed documentation on what
167 // values should be chosen can be found at
168 // freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.html.
169 pa_buffer_attr buffer_attributes
;
170 const unsigned int buffer_size
= params
.GetBytesPerBuffer();
171 buffer_attributes
.maxlength
= static_cast<uint32_t>(-1);
172 buffer_attributes
.tlength
= buffer_size
;
173 buffer_attributes
.minreq
= buffer_size
;
174 buffer_attributes
.prebuf
= static_cast<uint32_t>(-1);
175 buffer_attributes
.fragsize
= buffer_size
;
176 int flags
= PA_STREAM_AUTO_TIMING_UPDATE
|
177 PA_STREAM_INTERPOLATE_TIMING
|
178 PA_STREAM_ADJUST_LATENCY
|
179 PA_STREAM_START_CORKED
;
181 pa_stream_connect_record(
183 device_id
== AudioManagerBase::kDefaultDeviceId
?
184 NULL
: device_id
.c_str(),
186 static_cast<pa_stream_flags_t
>(flags
)) == 0,
187 "pa_stream_connect_record FAILED ");
189 // Wait for the stream to be ready.
191 pa_stream_state_t stream_state
= pa_stream_get_state(*stream
);
193 PA_STREAM_IS_GOOD(stream_state
), "Invalid PulseAudio stream state");
194 if (stream_state
== PA_STREAM_READY
)
196 pa_threaded_mainloop_wait(mainloop
);
202 bool CreateOutputStream(pa_threaded_mainloop
** mainloop
,
203 pa_context
** context
,
205 const AudioParameters
& params
,
206 const std::string
& device_id
,
207 pa_stream_notify_cb_t stream_callback
,
208 pa_stream_request_cb_t write_callback
,
213 *mainloop
= pa_threaded_mainloop_new();
214 RETURN_ON_FAILURE(*mainloop
, "Failed to create PulseAudio main loop.");
216 pa_mainloop_api
* pa_mainloop_api
= pa_threaded_mainloop_get_api(*mainloop
);
217 *context
= pa_context_new(pa_mainloop_api
, "Chromium");
218 RETURN_ON_FAILURE(*context
, "Failed to create PulseAudio context.");
220 // A state callback must be set before calling pa_threaded_mainloop_lock() or
221 // pa_threaded_mainloop_wait() calls may lead to dead lock.
222 pa_context_set_state_callback(*context
, &ContextStateCallback
, *mainloop
);
224 // Lock the main loop while setting up the context. Failure to do so may lead
225 // to crashes as the PulseAudio thread tries to run before things are ready.
226 AutoPulseLock
auto_lock(*mainloop
);
228 RETURN_ON_FAILURE(pa_threaded_mainloop_start(*mainloop
) == 0,
229 "Failed to start PulseAudio main loop.");
231 pa_context_connect(*context
, NULL
, PA_CONTEXT_NOAUTOSPAWN
, NULL
) == 0,
232 "Failed to connect PulseAudio context.");
234 // Wait until |pa_context_| is ready. pa_threaded_mainloop_wait() must be
235 // called after pa_context_get_state() in case the context is already ready,
236 // otherwise pa_threaded_mainloop_wait() will hang indefinitely.
238 pa_context_state_t context_state
= pa_context_get_state(*context
);
240 PA_CONTEXT_IS_GOOD(context_state
), "Invalid PulseAudio context state.");
241 if (context_state
== PA_CONTEXT_READY
)
243 pa_threaded_mainloop_wait(*mainloop
);
246 // Set sample specifications.
247 pa_sample_spec sample_specifications
;
248 sample_specifications
.format
= BitsToPASampleFormat(
249 params
.bits_per_sample());
250 sample_specifications
.rate
= params
.sample_rate();
251 sample_specifications
.channels
= params
.channels();
253 // Get channel mapping and open playback stream.
254 pa_channel_map
* map
= NULL
;
255 pa_channel_map source_channel_map
= ChannelLayoutToPAChannelMap(
256 params
.channel_layout());
257 if (source_channel_map
.channels
!= 0) {
258 // The source data uses a supported channel map so we will use it rather
259 // than the default channel map (NULL).
260 map
= &source_channel_map
;
262 *stream
= pa_stream_new(*context
, "Playback", &sample_specifications
, map
);
263 RETURN_ON_FAILURE(*stream
, "failed to create PA playback stream");
265 pa_stream_set_state_callback(*stream
, stream_callback
, user_data
);
267 // Even though we start the stream corked above, PulseAudio will issue one
268 // stream request after setup. write_callback() must fulfill the write.
269 pa_stream_set_write_callback(*stream
, write_callback
, user_data
);
271 // Pulse is very finicky with the small buffer sizes used by Chrome. The
272 // settings below are mostly found through trial and error. Essentially we
273 // want Pulse to auto size its internal buffers, but call us back nearly every
274 // |minreq| bytes. |tlength| should be a multiple of |minreq|; too low and
275 // Pulse will issue callbacks way too fast, too high and we don't get
276 // callbacks frequently enough.
277 pa_buffer_attr pa_buffer_attributes
;
278 pa_buffer_attributes
.maxlength
= static_cast<uint32_t>(-1);
279 pa_buffer_attributes
.minreq
= params
.GetBytesPerBuffer();
280 pa_buffer_attributes
.prebuf
= static_cast<uint32_t>(-1);
281 pa_buffer_attributes
.tlength
= params
.GetBytesPerBuffer() * 3;
282 pa_buffer_attributes
.fragsize
= static_cast<uint32_t>(-1);
284 // Connect playback stream. Like pa_buffer_attr, the pa_stream_flags have a
285 // huge impact on the performance of the stream and were chosen through trial
288 pa_stream_connect_playback(
290 device_id
== AudioManagerBase::kDefaultDeviceId
?
291 NULL
: device_id
.c_str(),
292 &pa_buffer_attributes
,
293 static_cast<pa_stream_flags_t
>(
294 PA_STREAM_INTERPOLATE_TIMING
| PA_STREAM_ADJUST_LATENCY
|
295 PA_STREAM_AUTO_TIMING_UPDATE
| PA_STREAM_NOT_MONOTONIC
|
296 PA_STREAM_START_CORKED
),
299 "pa_stream_connect_playback FAILED ");
301 // Wait for the stream to be ready.
303 pa_stream_state_t stream_state
= pa_stream_get_state(*stream
);
305 PA_STREAM_IS_GOOD(stream_state
), "Invalid PulseAudio stream state");
306 if (stream_state
== PA_STREAM_READY
)
308 pa_threaded_mainloop_wait(*mainloop
);
314 #undef RETURN_ON_FAILURE