Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(158)

Side by Side Diff: media/audio/linux/pulse_output.cc

Issue 8499029: make pulseaudio available for all posix platforms because it's not linux only (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: re-sync with the linux code Created 9 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright (c) 2011 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.
4
5 #include "media/audio/linux/pulse_output.h"
6
7 #include "base/bind.h"
8 #include "base/message_loop.h"
9 #include "media/audio/audio_parameters.h"
10 #include "media/audio/audio_util.h"
11 #include "media/audio/linux/audio_manager_linux.h"
12 #include "media/base/data_buffer.h"
13 #include "media/base/seekable_buffer.h"
14
15 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {
16 switch (bits_per_sample) {
17 // Unsupported sample formats shown for reference. I am assuming we want
18 // signed and little endian because that is what we gave to ALSA.
19 case 8:
20 return PA_SAMPLE_U8;
21 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
22 case 16:
23 return PA_SAMPLE_S16LE;
24 // Also 16-bits: PA_SAMPLE_S16BE (big endian).
25 case 24:
26 return PA_SAMPLE_S24LE;
27 // Also 24-bits: PA_SAMPLE_S24BE (big endian).
28 // Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),
29 // and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
30 case 32:
31 return PA_SAMPLE_S32LE;
32 // Also 32-bits: PA_SAMPLE_S32BE (big endian),
33 // PA_SAMPLE_FLOAT32LE (floating point little endian),
34 // and PA_SAMPLE_FLOAT32BE (floating point big endian).
35 default:
36 return PA_SAMPLE_INVALID;
37 }
38 }
39
40 static pa_channel_position ChromiumToPAChannelPosition(Channels channel) {
41 switch (channel) {
42 // PulseAudio does not differentiate between left/right and
43 // stereo-left/stereo-right, both translate to front-left/front-right.
44 case LEFT:
45 case STEREO_LEFT:
46 return PA_CHANNEL_POSITION_FRONT_LEFT;
47 case RIGHT:
48 case STEREO_RIGHT:
49 return PA_CHANNEL_POSITION_FRONT_RIGHT;
50 case CENTER:
51 return PA_CHANNEL_POSITION_FRONT_CENTER;
52 case LFE:
53 return PA_CHANNEL_POSITION_LFE;
54 case BACK_LEFT:
55 return PA_CHANNEL_POSITION_REAR_LEFT;
56 case BACK_RIGHT:
57 return PA_CHANNEL_POSITION_REAR_RIGHT;
58 case LEFT_OF_CENTER:
59 return PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
60 case RIGHT_OF_CENTER:
61 return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
62 case BACK_CENTER:
63 return PA_CHANNEL_POSITION_REAR_CENTER;
64 case SIDE_LEFT:
65 return PA_CHANNEL_POSITION_SIDE_LEFT;
66 case SIDE_RIGHT:
67 return PA_CHANNEL_POSITION_SIDE_RIGHT;
68 case CHANNELS_MAX:
69 return PA_CHANNEL_POSITION_INVALID;
70 }
71 NOTREACHED() << "Invalid channel " << channel;
72 return PA_CHANNEL_POSITION_INVALID;
73 }
74
75 static pa_channel_map ChannelLayoutToPAChannelMap(
76 ChannelLayout channel_layout) {
77 // Initialize channel map.
78 pa_channel_map channel_map;
79 pa_channel_map_init(&channel_map);
80
81 channel_map.channels = ChannelLayoutToChannelCount(channel_layout);
82
83 // All channel maps have the same size array of channel positions.
84 for (unsigned int channel = 0; channel != CHANNELS_MAX; ++channel) {
85 int channel_position = kChannelOrderings[channel_layout][channel];
86 if (channel_position > -1) {
87 channel_map.map[channel_position] = ChromiumToPAChannelPosition(
88 static_cast<Channels>(channel));
89 } else {
90 // PulseAudio expects unused channels in channel maps to be filled with
91 // PA_CHANNEL_POSITION_MONO.
92 channel_map.map[channel_position] = PA_CHANNEL_POSITION_MONO;
93 }
94 }
95
96 // Fill in the rest of the unused channels.
97 for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX;
98 ++channel) {
99 channel_map.map[channel] = PA_CHANNEL_POSITION_MONO;
100 }
101
102 return channel_map;
103 }
104
105 static size_t MicrosecondsToBytes(
106 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
107 return microseconds * sample_rate * bytes_per_frame /
108 base::Time::kMicrosecondsPerSecond;
109 }
110
111 void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
112 void* state_addr) {
113 pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);
114 *state = pa_context_get_state(context);
115 }
116
117 void PulseAudioOutputStream::WriteRequestCallback(
118 pa_stream* playback_handle, size_t length, void* stream_addr) {
119 PulseAudioOutputStream* stream =
120 static_cast<PulseAudioOutputStream*>(stream_addr);
121
122 DCHECK_EQ(stream->message_loop_, MessageLoop::current());
123
124 stream->write_callback_handled_ = true;
125
126 // Fulfill write request.
127 stream->FulfillWriteRequest(length);
128 }
129
130 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
131 AudioManagerLinux* manager,
132 MessageLoop* message_loop)
133 : channel_layout_(params.channel_layout),
134 channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
135 sample_format_(BitsToPASampleFormat(params.bits_per_sample)),
136 sample_rate_(params.sample_rate),
137 bytes_per_frame_(params.channels * params.bits_per_sample / 8),
138 manager_(manager),
139 pa_context_(NULL),
140 pa_mainloop_(NULL),
141 playback_handle_(NULL),
142 packet_size_(params.GetPacketSize()),
143 frames_per_packet_(packet_size_ / bytes_per_frame_),
144 client_buffer_(NULL),
145 volume_(1.0f),
146 stream_stopped_(true),
147 write_callback_handled_(false),
148 message_loop_(message_loop),
149 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
150 source_callback_(NULL) {
151 DCHECK_EQ(message_loop_, MessageLoop::current());
152 DCHECK(manager_);
153
154 // TODO(slock): Sanity check input values.
155 }
156
157 PulseAudioOutputStream::~PulseAudioOutputStream() {
158 // All internal structures should already have been freed in Close(),
159 // which calls AudioManagerLinux::Release which deletes this object.
160 DCHECK(!playback_handle_);
161 DCHECK(!pa_context_);
162 DCHECK(!pa_mainloop_);
163 }
164
165 bool PulseAudioOutputStream::Open() {
166 DCHECK_EQ(message_loop_, MessageLoop::current());
167
168 // TODO(slock): Possibly move most of this to an OpenPlaybackDevice function
169 // in a new class 'pulse_util', like alsa_util.
170
171 // Create a mainloop API and connect to the default server.
172 pa_mainloop_ = pa_mainloop_new();
173 pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);
174 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
175 pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED;
176 pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL);
177
178 // Wait until PulseAudio is ready.
179 pa_context_set_state_callback(pa_context_, &ContextStateCallback,
180 &pa_context_state);
181 while (pa_context_state != PA_CONTEXT_READY) {
182 pa_mainloop_iterate(pa_mainloop_, 1, NULL);
183 if (pa_context_state == PA_CONTEXT_FAILED ||
184 pa_context_state == PA_CONTEXT_TERMINATED) {
185 Reset();
186 return false;
187 }
188 }
189
190 // Set sample specifications.
191 pa_sample_spec pa_sample_specifications;
192 pa_sample_specifications.format = sample_format_;
193 pa_sample_specifications.rate = sample_rate_;
194 pa_sample_specifications.channels = channel_count_;
195
196 // Get channel mapping and open playback stream.
197 pa_channel_map* map = NULL;
198 pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap(
199 channel_layout_);
200 if (source_channel_map.channels != 0) {
201 // The source data uses a supported channel map so we will use it rather
202 // than the default channel map (NULL).
203 map = &source_channel_map;
204 }
205 playback_handle_ = pa_stream_new(pa_context_, "Playback",
206 &pa_sample_specifications, map);
207
208 // Initialize client buffer.
209 uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;
210 client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));
211
212 // Set write callback.
213 pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
214
215 // Set server-side buffer attributes.
216 // (uint32_t)-1 is the default and recommended value from PulseAudio's
217 // documentation, found at:
218 // http://freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.h tml.
219 pa_buffer_attr pa_buffer_attributes;
220 pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);
221 pa_buffer_attributes.tlength = output_packet_size;
222 pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1);
223 pa_buffer_attributes.minreq = static_cast<uint32_t>(-1);
224 pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);
225
226 // Connect playback stream.
227 pa_stream_connect_playback(playback_handle_, NULL,
228 &pa_buffer_attributes,
229 (pa_stream_flags_t)
230 (PA_STREAM_INTERPOLATE_TIMING |
231 PA_STREAM_ADJUST_LATENCY |
232 PA_STREAM_AUTO_TIMING_UPDATE),
233 NULL, NULL);
234
235 if (!playback_handle_) {
236 Reset();
237 return false;
238 }
239
240 return true;
241 }
242
243 void PulseAudioOutputStream::Reset() {
244 stream_stopped_ = true;
245
246 // Close the stream.
247 if (playback_handle_) {
248 pa_stream_flush(playback_handle_, NULL, NULL);
249 pa_stream_disconnect(playback_handle_);
250
251 // Release PulseAudio structures.
252 pa_stream_unref(playback_handle_);
253 playback_handle_ = NULL;
254 }
255 if (pa_context_) {
256 pa_context_unref(pa_context_);
257 pa_context_ = NULL;
258 }
259 if (pa_mainloop_) {
260 pa_mainloop_free(pa_mainloop_);
261 pa_mainloop_ = NULL;
262 }
263
264 // Release internal buffer.
265 client_buffer_.reset();
266 }
267
268 void PulseAudioOutputStream::Close() {
269 DCHECK_EQ(message_loop_, MessageLoop::current());
270
271 Reset();
272
273 // Signal to the manager that we're closed and can be removed.
274 // This should be the last call in the function as it deletes "this".
275 manager_->ReleaseOutputStream(this);
276 }
277
278 void PulseAudioOutputStream::WaitForWriteRequest() {
279 DCHECK_EQ(message_loop_, MessageLoop::current());
280
281 if (stream_stopped_)
282 return;
283
284 // Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,
285 // post a task to iterate the mainloop again.
286 write_callback_handled_ = false;
287 pa_mainloop_iterate(pa_mainloop_, 1, NULL);
288 if (!write_callback_handled_) {
289 message_loop_->PostTask(FROM_HERE, base::Bind(
290 &PulseAudioOutputStream::WaitForWriteRequest,
291 weak_factory_.GetWeakPtr()));
292 }
293 }
294
295 bool PulseAudioOutputStream::BufferPacketFromSource() {
296 uint32 buffer_delay = client_buffer_->forward_bytes();
297 pa_usec_t pa_latency_micros;
298 int negative;
299 pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
300 uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
301 sample_rate_,
302 bytes_per_frame_);
303 // TODO(slock): Deal with negative latency (negative == 1). This has yet
304 // to happen in practice though.
305 scoped_refptr<media::DataBuffer> packet =
306 new media::DataBuffer(packet_size_);
307 size_t packet_size = RunDataCallback(packet->GetWritableData(),
308 packet->GetBufferSize(),
309 AudioBuffersState(buffer_delay,
310 hardware_delay));
311
312 if (packet_size == 0)
313 return false;
314
315 media::AdjustVolume(packet->GetWritableData(),
316 packet_size,
317 channel_count_,
318 bytes_per_frame_ / channel_count_,
319 volume_);
320 packet->SetDataSize(packet_size);
321 // Add the packet to the buffer.
322 client_buffer_->Append(packet);
323 return true;
324 }
325
326 void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
327 // If we have enough data to fulfill the request, we can finish the write.
328 if (stream_stopped_)
329 return;
330
331 // Request more data from the source until we can fulfill the request or
332 // fail to receive anymore data.
333 bool buffering_successful = true;
334 while (client_buffer_->forward_bytes() < requested_bytes &&
335 buffering_successful) {
336 buffering_successful = BufferPacketFromSource();
337 }
338
339 size_t bytes_written = 0;
340 if (client_buffer_->forward_bytes() > 0) {
341 // Try to fulfill the request by writing as many of the requested bytes to
342 // the stream as we can.
343 WriteToStream(requested_bytes, &bytes_written);
344 }
345
346 if (bytes_written < requested_bytes) {
347 // We weren't able to buffer enough data to fulfill the request. Try to
348 // fulfill the rest of the request later.
349 message_loop_->PostTask(FROM_HERE, base::Bind(
350 &PulseAudioOutputStream::FulfillWriteRequest,
351 weak_factory_.GetWeakPtr(),
352 requested_bytes - bytes_written));
353 } else {
354 // Continue playback.
355 message_loop_->PostTask(FROM_HERE, base::Bind(
356 &PulseAudioOutputStream::WaitForWriteRequest,
357 weak_factory_.GetWeakPtr()));
358 }
359 }
360
361 void PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,
362 size_t* bytes_written) {
363 *bytes_written = 0;
364 while (*bytes_written < bytes_to_write) {
365 const uint8* chunk;
366 size_t chunk_size;
367
368 // Stop writing if there is no more data available.
369 if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))
370 break;
371
372 // Write data to stream.
373 pa_stream_write(playback_handle_, chunk, chunk_size,
374 NULL, 0LL, PA_SEEK_RELATIVE);
375 client_buffer_->Seek(chunk_size);
376 *bytes_written += chunk_size;
377 }
378 }
379
380 void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
381 DCHECK_EQ(message_loop_, MessageLoop::current());
382
383 CHECK(callback);
384 source_callback_ = callback;
385
386 // Clear buffer, it might still have data in it.
387 client_buffer_->Clear();
388 stream_stopped_ = false;
389
390 // Start playback.
391 message_loop_->PostTask(FROM_HERE, base::Bind(
392 &PulseAudioOutputStream::WaitForWriteRequest,
393 weak_factory_.GetWeakPtr()));
394 }
395
396 void PulseAudioOutputStream::Stop() {
397 DCHECK_EQ(message_loop_, MessageLoop::current());
398
399 stream_stopped_ = true;
400 }
401
402 void PulseAudioOutputStream::SetVolume(double volume) {
403 DCHECK_EQ(message_loop_, MessageLoop::current());
404
405 volume_ = static_cast<float>(volume);
406 }
407
408 void PulseAudioOutputStream::GetVolume(double* volume) {
409 DCHECK_EQ(message_loop_, MessageLoop::current());
410
411 *volume = volume_;
412 }
413
414 uint32 PulseAudioOutputStream::RunDataCallback(
415 uint8* dest, uint32 max_size, AudioBuffersState buffers_state) {
416 if (source_callback_)
417 return source_callback_->OnMoreData(this, dest, max_size, buffers_state);
418
419 return 0;
420 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698