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

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

Issue 8496007: A patch making the pulseaudio working with the threaded mainloop. (Closed) Base URL: http://src.chromium.org/svn/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
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "media/audio/linux/pulse_output.h" 5 #include "media/audio/linux/pulse_output.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/message_loop.h" 8 #include "base/message_loop.h"
9 #include "media/audio/audio_parameters.h" 9 #include "media/audio/audio_parameters.h"
10 #include "media/audio/audio_util.h" 10 #include "media/audio/audio_util.h"
11 #include "media/audio/linux/audio_manager_linux.h" 11 #include "media/audio/linux/audio_manager_linux.h"
12 #include "media/base/data_buffer.h" 12 #include "media/base/data_buffer.h"
13 #include "media/base/seekable_buffer.h" 13 #include "media/base/seekable_buffer.h"
14 14
15 // TODO(xians): Do we support sample format rather than PA_SAMPLE_S16LE?
tommi (sloooow) - chröme 2011/11/08 10:51:36 which sample format?
no longer working on chromium 2011/11/09 12:57:33 Done.
15 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) { 16 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {
16 switch (bits_per_sample) { 17 switch (bits_per_sample) {
17 // Unsupported sample formats shown for reference. I am assuming we want 18 // 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 // signed and little endian because that is what we gave to ALSA.
19 case 8: 20 case 8:
20 return PA_SAMPLE_U8; 21 return PA_SAMPLE_U8;
21 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW 22 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
22 case 16: 23 case 16:
23 return PA_SAMPLE_S16LE; 24 return PA_SAMPLE_S16LE;
24 // Also 16-bits: PA_SAMPLE_S16BE (big endian). 25 // Also 16-bits: PA_SAMPLE_S16BE (big endian).
25 case 24: 26 case 24:
26 return PA_SAMPLE_S24LE; 27 return PA_SAMPLE_S24LE;
27 // Also 24-bits: PA_SAMPLE_S24BE (big endian). 28 // Also 24-bits: PA_SAMPLE_S24BE (big endian).
28 // Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian), 29 // 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 // and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
30 case 32: 31 case 32:
31 return PA_SAMPLE_S32LE; 32 return PA_SAMPLE_S32LE;
32 // Also 32-bits: PA_SAMPLE_S32BE (big endian), 33 // Also 32-bits: PA_SAMPLE_S32BE (big endian),
33 // PA_SAMPLE_FLOAT32LE (floating point little endian), 34 // PA_SAMPLE_FLOAT32LE (floating point little endian),
34 // and PA_SAMPLE_FLOAT32BE (floating point big endian). 35 // and PA_SAMPLE_FLOAT32BE (floating point big endian).
35 default: 36 default:
36 return PA_SAMPLE_INVALID; 37 return PA_SAMPLE_INVALID;
37 } 38 }
38 } 39 }
39 40
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( 41 static size_t MicrosecondsToBytes(
106 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) { 42 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
107 return microseconds * sample_rate * bytes_per_frame / 43 return microseconds * sample_rate * bytes_per_frame /
108 base::Time::kMicrosecondsPerSecond; 44 base::Time::kMicrosecondsPerSecond;
109 } 45 }
110 46
111 void PulseAudioOutputStream::ContextStateCallback(pa_context* context, 47 void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
112 void* state_addr) { 48 void* p_this) {
113 pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr); 49 PulseAudioOutputStream* audio_stream =
114 *state = pa_context_get_state(context); 50 static_cast<PulseAudioOutputStream*>(p_this);
tommi (sloooow) - chröme 2011/11/08 10:51:36 this should be reinterpret_cast. static_cast shoul
no longer working on chromium 2011/11/09 12:57:33 Done.
51 pa_context_state_t state = pa_context_get_state(context);
52 switch (state) {
53 case PA_CONTEXT_UNCONNECTED:
54 case PA_CONTEXT_CONNECTING:
55 case PA_CONTEXT_AUTHORIZING:
56 case PA_CONTEXT_SETTING_NAME:
57 default:
tommi (sloooow) - chröme 2011/11/08 10:51:36 default label should be last.
no longer working on chromium 2011/11/09 12:57:33 Done.
58 break;
59 case PA_CONTEXT_FAILED:
60 case PA_CONTEXT_TERMINATED:
61 audio_stream->context_state_changed_ = true;
62 break;
63 case PA_CONTEXT_READY:
64 audio_stream->context_state_changed_ = true;
65 break;
66 }
115 } 67 }
116 68
117 void PulseAudioOutputStream::WriteRequestCallback( 69 void PulseAudioOutputStream::WriteRequestCallback(
118 pa_stream* playback_handle, size_t length, void* stream_addr) { 70 pa_stream* playback_handle, size_t length, void* p_this) {
119 PulseAudioOutputStream* stream = 71 PulseAudioOutputStream* audio_stream =
120 static_cast<PulseAudioOutputStream*>(stream_addr); 72 static_cast<PulseAudioOutputStream*>(p_this);
tommi (sloooow) - chröme 2011/11/08 10:51:36 reinterpret_cast
no longer working on chromium 2011/11/09 12:57:33 Done.
121 73
122 DCHECK_EQ(stream->message_loop_, MessageLoop::current()); 74 audio_stream->FulfillWriteRequest(length);
123
124 stream->write_callback_handled_ = true;
125
126 // Fulfill write request.
127 stream->FulfillWriteRequest(length);
128 } 75 }
129 76
130 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params, 77 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
131 AudioManagerLinux* manager, 78 AudioManagerLinux* manager,
132 MessageLoop* message_loop) 79 MessageLoop* message_loop)
133 : channel_layout_(params.channel_layout), 80 : channels_(params.channels),
134 channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
135 sample_format_(BitsToPASampleFormat(params.bits_per_sample)), 81 sample_format_(BitsToPASampleFormat(params.bits_per_sample)),
136 sample_rate_(params.sample_rate), 82 sample_rate_(params.sample_rate),
137 bytes_per_frame_(params.channels * params.bits_per_sample / 8), 83 bytes_per_frame_(params.channels * params.bits_per_sample / 8),
84 packet_size_(params.GetPacketSize()),
85 frames_per_packet_(packet_size_ / bytes_per_frame_),
138 manager_(manager), 86 manager_(manager),
139 pa_context_(NULL), 87 pa_context_(NULL),
140 pa_mainloop_(NULL), 88 pa_glib_mainloop_(NULL),
141 playback_handle_(NULL), 89 playback_handle_(NULL),
142 packet_size_(params.GetPacketSize()), 90 pa_buffer_size_(0),
143 frames_per_packet_(packet_size_ / bytes_per_frame_), 91 buffer_(NULL),
144 client_buffer_(NULL),
145 volume_(1.0f), 92 volume_(1.0f),
146 stream_stopped_(true), 93 stream_stopped_(true),
147 write_callback_handled_(false), 94 context_state_changed_(false),
148 message_loop_(message_loop), 95 message_loop_(message_loop),
149 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), 96 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
150 source_callback_(NULL) { 97 source_callback_(NULL) {
151 DCHECK_EQ(message_loop_, MessageLoop::current()); 98 DCHECK_EQ(message_loop_, MessageLoop::current());
152 DCHECK(manager_); 99 DCHECK(manager_);
153 100
154 // TODO(slock): Sanity check input values. 101 // TODO(slock): Sanity check input values.
102
103 // TODO(xians): Check if PA is available here in runtime, and fall back
104 // to ALSA if not available.
155 } 105 }
156 106
157 PulseAudioOutputStream::~PulseAudioOutputStream() { 107 PulseAudioOutputStream::~PulseAudioOutputStream() {
158 // All internal structures should already have been freed in Close(), 108 // All internal structures should already have been freed in Close(),
159 // which calls AudioManagerLinux::Release which deletes this object. 109 // which calls AudioManagerLinux::Release which deletes this object.
160 DCHECK(!playback_handle_); 110 DCHECK(!playback_handle_);
161 DCHECK(!pa_context_); 111 DCHECK(!pa_context_);
162 DCHECK(!pa_mainloop_); 112 DCHECK(!pa_glib_mainloop_);
163 } 113 }
164 114
165 bool PulseAudioOutputStream::Open() { 115 bool PulseAudioOutputStream::Open() {
166 DCHECK_EQ(message_loop_, MessageLoop::current()); 116 DCHECK_EQ(message_loop_, MessageLoop::current());
167 117
168 // TODO(slock): Possibly move most of this to an OpenPlaybackDevice function 118 // Use glib mainloop that we don't need to care about any processing.
169 // in a new class 'pulse_util', like alsa_util. 119 pa_glib_mainloop_ = pa_glib_mainloop_new(NULL);
tommi (sloooow) - chröme 2011/11/08 10:51:36 first DCHECK that pa_glib_mainloop_ is NULL
no longer working on chromium 2011/11/09 12:57:33 Done.
120 DCHECK(pa_glib_mainloop_);
tommi (sloooow) - chröme 2011/11/08 10:51:36 this and the DLOG below cover the same case. You
no longer working on chromium 2011/11/09 12:57:33 Done.
121 if (!pa_glib_mainloop_) {
122 DLOG(ERROR) << "Open: failed to create PA glib mainloop";
123 return false;
124 }
170 125
171 // Create a mainloop API and connect to the default server. 126 // TODO(xians): Figure out if we can share one pa_context_ for streams.
172 pa_mainloop_ = pa_mainloop_new(); 127 pa_mainloop_api* pa_mainloop_api =
173 pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_); 128 pa_glib_mainloop_get_api(pa_glib_mainloop_);
174 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium"); 129 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
175 pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED; 130 if (!pa_context_) {
176 pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL); 131 DLOG(ERROR) << "Open: failed to create PA context";
tommi (sloooow) - chröme 2011/11/08 10:51:36 DCHECK?
132 Reset();
133 return false;
134 }
177 135
178 // Wait until PulseAudio is ready. 136 // Set the |context_state_changed_| to false and connect the context to
179 pa_context_set_state_callback(pa_context_, &ContextStateCallback, 137 // the server.
180 &pa_context_state); 138 context_state_changed_ = false;
181 while (pa_context_state != PA_CONTEXT_READY) { 139 pa_context_set_state_callback(pa_context_, &ContextStateCallback, this);
182 pa_mainloop_iterate(pa_mainloop_, 1, NULL); 140 if (pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL)) {
183 if (pa_context_state == PA_CONTEXT_FAILED || 141 DLOG(ERROR) << "Open: failed to connect to the context";
184 pa_context_state == PA_CONTEXT_TERMINATED) { 142 Reset();
185 Reset(); 143 return false;
186 return false; 144 }
187 } 145
146 // Wait for state change.
147 while (!context_state_changed_) {
148 base::PlatformThread::Sleep(2);
tommi (sloooow) - chröme 2011/11/08 10:51:36 Is using Sleep the only option? I'll leave this t
enal1 2011/11/08 17:22:06 Sleep() may be not the best, but definitely simple
no longer working on chromium 2011/11/09 12:57:33 Use a WaitableEvent, hope it is fine.
no longer working on chromium 2011/11/09 12:57:33 Use a WaitableEvent with a timeout for 200ms, hope
149 }
150 if (pa_context_get_state(pa_context_) != PA_CONTEXT_READY) {
151 DLOG(ERROR) << "Open: unknown problem connecting to PulseAudio server";
152 Reset();
153 return false;
188 } 154 }
189 155
190 // Set sample specifications. 156 // Set sample specifications.
191 pa_sample_spec pa_sample_specifications; 157 pa_sample_spec pa_sample_specifications;
192 pa_sample_specifications.format = sample_format_; 158 pa_sample_specifications.format = sample_format_;
193 pa_sample_specifications.rate = sample_rate_; 159 pa_sample_specifications.rate = sample_rate_;
194 pa_sample_specifications.channels = channel_count_; 160 pa_sample_specifications.channels = channels_;
195 161
196 // Get channel mapping and open playback stream. 162 // Create a new play stream
197 pa_channel_map* map = NULL; 163 playback_handle_ = pa_stream_new(pa_context_, "PlayStream",
198 pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap( 164 &pa_sample_specifications, NULL);
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_) { 165 if (!playback_handle_) {
166 DLOG(ERROR) << "Open: failed to create PA stream";
236 Reset(); 167 Reset();
237 return false; 168 return false;
238 } 169 }
239 170
171 pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
172 buffer_.reset(new media::SeekableBuffer(0, packet_size_));
240 return true; 173 return true;
241 } 174 }
242 175
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() { 176 void PulseAudioOutputStream::Close() {
269 DCHECK_EQ(message_loop_, MessageLoop::current()); 177 DCHECK_EQ(message_loop_, MessageLoop::current());
270 178
271 Reset(); 179 Reset();
272 180
273 // Signal to the manager that we're closed and can be removed. 181 // 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". 182 // This should be the last call in the function as it deletes "this".
275 manager_->ReleaseOutputStream(this); 183 manager_->ReleaseOutputStream(this);
276 } 184 }
277 185
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) { 186 void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
381 DCHECK_EQ(message_loop_, MessageLoop::current()); 187 DCHECK_EQ(message_loop_, MessageLoop::current());
382 188
383 CHECK(callback); 189 if (!stream_stopped_)
384 source_callback_ = callback; 190 return;
385
386 // Clear buffer, it might still have data in it.
387 client_buffer_->Clear();
388 stream_stopped_ = false; 191 stream_stopped_ = false;
389 192
390 // Start playback. 193 CHECK(callback);
tommi (sloooow) - chröme 2011/11/08 10:51:36 did you mean DCHECK? CHECK also applies to releas
no longer working on chromium 2011/11/09 12:57:33 It should be CHECK(), since it is not designed to
391 message_loop_->PostTask(FROM_HERE, base::Bind( 194
392 &PulseAudioOutputStream::WaitForWriteRequest, 195 // First time to start the stream.
393 weak_factory_.GetWeakPtr())); 196 if (!source_callback_) {
197 source_callback_ = callback;
198
199 // Set server-side playback buffer metrics. Detailed documentation on what
200 // values should be chosen can be found at
201 // freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.html.
202 pa_buffer_attr pa_buffer_attributes;
203 pa_buffer_size_ = packet_size_;
204 pa_buffer_attributes.maxlength = (uint32_t) -1;
tommi (sloooow) - chröme 2011/11/08 10:51:36 static_cast (never use C style cast)
no longer working on chromium 2011/11/09 12:57:33 Done.
205 pa_buffer_attributes.tlength = pa_buffer_size_;
206 pa_buffer_attributes.minreq = pa_buffer_size_ / 2;
207 pa_buffer_attributes.prebuf =
208 pa_buffer_attributes.tlength - pa_buffer_attributes.minreq;
209 pa_buffer_attributes.fragsize = packet_size_;
210 int err = pa_stream_connect_playback(playback_handle_, NULL,
211 &pa_buffer_attributes,
212 (pa_stream_flags_t)0,
tommi (sloooow) - chröme 2011/11/08 10:51:36 static_cast
no longer working on chromium 2011/11/09 12:57:33 Done.
213 NULL,
214 NULL);
215 if (err) {
216 DLOG(ERROR) << "pa_stream_connect_playback FAILED " << err;
217 Reset();
218 return;
219 }
220 } else { // Resume the playout stream.
221 // Flush the stream.
tommi (sloooow) - chröme 2011/11/08 10:51:36 should we [D]CHECK here that source_callback_ == c
no longer working on chromium 2011/11/09 12:57:33 I moved the source_callback_ = callback; out of th
222 pa_operation* operation = pa_stream_flush(playback_handle_, NULL, NULL);
223 if (!operation) {
224 DLOG(ERROR) << "PulseAudioOutputStream: failed to flush the playout "
225 << "stream";
226 return;
227 }
228 // Do not need to wait for the operation.
229 pa_operation_unref(operation);
230
231 // Start the stream.
232 operation = pa_stream_cork(playback_handle_, 0, NULL, NULL);
233 if (!operation) {
234 DLOG(ERROR) << "PulseAudioOutputStream: failed to start the playout "
235 << "stream";
236 return;
237 }
238 pa_operation_unref(operation);
239
240 operation = pa_stream_trigger(playback_handle_, NULL, NULL);
241 if (!operation) {
242 DLOG(ERROR) << "PulseAudioOutputStream: failed to trigger the playout "
243 << "callback";
244 return;
245 }
246 pa_operation_unref(operation);
247 }
248
249 // Before starting, the buffer might have audio from previous user of this
250 // device.
251 buffer_->Clear();
394 } 252 }
395 253
396 void PulseAudioOutputStream::Stop() { 254 void PulseAudioOutputStream::Stop() {
397 DCHECK_EQ(message_loop_, MessageLoop::current()); 255 DCHECK_EQ(message_loop_, MessageLoop::current());
256 // Set the flag to false to stop filling new data to soundcard.
257 stream_stopped_ = true;
398 258
399 stream_stopped_ = true; 259 if (!playback_handle_)
260 return;
261
262 // Stop the stream.
263 pa_operation* operation = pa_stream_cork(playback_handle_, 1, NULL, NULL);
264 if (!operation) {
265 DLOG(ERROR) << "PulseAudioOutputStream: failed to stop the playout";
266 return;
267 }
268 // Do not need to wait for the operation.
269 pa_operation_unref(operation);
400 } 270 }
401 271
402 void PulseAudioOutputStream::SetVolume(double volume) { 272 void PulseAudioOutputStream::SetVolume(double volume) {
403 DCHECK_EQ(message_loop_, MessageLoop::current()); 273 DCHECK_EQ(message_loop_, MessageLoop::current());
404 274
405 volume_ = static_cast<float>(volume); 275 volume_ = static_cast<float>(volume);
406 } 276 }
407 277
408 void PulseAudioOutputStream::GetVolume(double* volume) { 278 void PulseAudioOutputStream::GetVolume(double* volume) {
409 DCHECK_EQ(message_loop_, MessageLoop::current()); 279 DCHECK_EQ(message_loop_, MessageLoop::current());
410 280
411 *volume = volume_; 281 *volume = volume_;
412 } 282 }
413 283
414 uint32 PulseAudioOutputStream::RunDataCallback( 284 void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
415 uint8* dest, uint32 max_size, AudioBuffersState buffers_state) { 285 // Update the delay.
416 if (source_callback_) 286 pa_usec_t pa_latency_micros;
417 return source_callback_->OnMoreData(this, dest, max_size, buffers_state); 287 int negative;
288 pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
289 uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
290 sample_rate_,
291 bytes_per_frame_);
292 // TODO(slock): Deal with negative latency (negative == 1). This has yet
293 // to happen in practice though.
418 294
419 return 0; 295 // Request more data from the source until we can fulfill the request or
296 // fail to receive anymore data.
297 scoped_refptr<media::DataBuffer> packet =
tommi (sloooow) - chröme 2011/11/08 10:51:36 nit: prefer constructor syntax for types that have
no longer working on chromium 2011/11/09 12:57:33 Done.
298 new media::DataBuffer(packet_size_);
299 size_t filled = 0;
300 int bytes_to_fill = requested_bytes;
301
302 while ((bytes_to_fill > 0)) {
303 // Request more data if we have capacity.
304 if (buffer_->forward_capacity() > buffer_->forward_bytes()) {
305 if (buffer_->forward_bytes() < (unsigned int)bytes_to_fill) {
tommi (sloooow) - chröme 2011/11/08 10:51:36 static_cast
no longer working on chromium 2011/11/09 12:57:33 Done.
306 if (!stream_stopped_ && source_callback_)
307 filled = source_callback_->OnMoreData(
308 this,
309 packet->GetWritableData(),
310 packet->GetBufferSize(),
311 AudioBuffersState(0, hardware_delay));
312 if (!filled && !buffer_->forward_bytes()) {
313 // In order to keep the callback running, we need to provide a
314 // positive amount of data to the audio queue. To simulate the
315 // behavior of Windows, we write a duration of 10ms silence to the
316 // soundcard. This value is chosen by experiments and Ubuntu 10.04
317 // cannot keep up with anything less than 10ms.
318 filled = bytes_per_frame_ * sample_rate_ * 10 / 1000;
319 // Assume unsigned audio.
320 int silence_value = 128;
321 if (sample_format_ != PA_SAMPLE_U8) {
322 // When bits per channel is greater than 8, audio is signed.
323 silence_value = 0;
324 }
325 // Set bytes_to_fill to 10ms so that it will quite the loop after
326 // writing the silence to the soundcard.
327 memset(packet->GetWritableData(), silence_value, filled);
328 DLOG(WARNING) << "FulfillWriteRequest: writing 10ms silent data";
329 }
330 packet->SetDataSize(filled);
331 buffer_->Append(packet);
332 }
333 }
334
335 const uint8* buffer_data;
336 size_t buffer_size;
337 if (buffer_->GetCurrentChunk(&buffer_data, &buffer_size)) {
338 if (buffer_size < (unsigned int)bytes_to_fill)
tommi (sloooow) - chröme 2011/11/08 10:51:36 cast
no longer working on chromium 2011/11/09 12:57:33 Done.
339 filled = buffer_size;
340 else
341 filled = bytes_to_fill;
342
343 // Write data to stream.
344 if (pa_stream_write(playback_handle_, buffer_data, filled,
345 NULL, 0, PA_SEEK_RELATIVE)) {
346 DLOG(WARNING) << "FulfillWriteRequest: failed to write "
347 << filled << " bytes of data";
348 }
349
350 // Seek forward in the buffer after we've written some data to ALSA.
351 buffer_->Seek(filled);
352 bytes_to_fill -= filled;
353 }
354 }
420 } 355 }
356
357 void PulseAudioOutputStream::Reset() {
358 stream_stopped_ = true;
359
360 // Close the stream.
361 if (playback_handle_) {
362 // Disable all the callbacks before disconnecting.
363 pa_stream_set_state_callback(playback_handle_, NULL, NULL);
364
365 pa_stream_flush(playback_handle_, NULL, NULL);
366 pa_stream_disconnect(playback_handle_);
367
368 // Release PulseAudio structures.
369 pa_stream_unref(playback_handle_);
370 playback_handle_ = NULL;
371 }
372 if (pa_context_) {
373 pa_context_unref(pa_context_);
374 pa_context_ = NULL;
375 }
376 if (pa_glib_mainloop_) {
377 pa_glib_mainloop_free(pa_glib_mainloop_);
378 pa_glib_mainloop_ = NULL;
379 }
380 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698