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

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

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

Powered by Google App Engine
This is Rietveld 408576698