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

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

Issue 11098031: Get PulseAudio implementation working. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Cork. BeginWrite. Cleanup. Created 8 years, 2 months 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) 2012 The Chromium Authors. All rights reserved. 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 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/pulse/pulse_output.h" 5 #include "media/audio/pulse/pulse_output.h"
6 6
7 #include "base/bind.h" 7 #include "media/audio/audio_manager_base.h"
8 #include "base/message_loop.h"
9 #include "media/audio/audio_parameters.h" 8 #include "media/audio/audio_parameters.h"
10 #include "media/audio/audio_util.h" 9 #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 10
19 namespace media { 11 namespace media {
20 12
21 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) { 13 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {
22 switch (bits_per_sample) { 14 switch (bits_per_sample) {
23 // Unsupported sample formats shown for reference. I am assuming we want
24 // signed and little endian because that is what we gave to ALSA.
25 case 8: 15 case 8:
26 return PA_SAMPLE_U8; 16 return PA_SAMPLE_U8;
27 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
28 case 16: 17 case 16:
29 return PA_SAMPLE_S16LE; 18 return PA_SAMPLE_S16LE;
30 // Also 16-bits: PA_SAMPLE_S16BE (big endian).
31 case 24: 19 case 24:
32 return PA_SAMPLE_S24LE; 20 return PA_SAMPLE_S24LE;
33 // Also 24-bits: PA_SAMPLE_S24BE (big endian).
34 // Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian),
35 // and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
36 case 32: 21 case 32:
37 return PA_SAMPLE_S32LE; 22 return PA_SAMPLE_S32LE;
38 // Also 32-bits: PA_SAMPLE_S32BE (big endian),
39 // PA_SAMPLE_FLOAT32LE (floating point little endian),
40 // and PA_SAMPLE_FLOAT32BE (floating point big endian).
41 default: 23 default:
24 NOTREACHED() << "Invalid bits per sample: " << bits_per_sample;
42 return PA_SAMPLE_INVALID; 25 return PA_SAMPLE_INVALID;
43 } 26 }
44 } 27 }
45 28
46 static pa_channel_position ChromiumToPAChannelPosition(Channels channel) { 29 static pa_channel_position ChromiumToPAChannelPosition(Channels channel) {
47 switch (channel) { 30 switch (channel) {
48 // PulseAudio does not differentiate between left/right and 31 // PulseAudio does not differentiate between left/right and
49 // stereo-left/stereo-right, both translate to front-left/front-right. 32 // stereo-left/stereo-right, both translate to front-left/front-right.
50 case LEFT: 33 case LEFT:
51 case STEREO_LEFT: 34 case STEREO_LEFT:
(...skipping 14 matching lines...) Expand all
66 case RIGHT_OF_CENTER: 49 case RIGHT_OF_CENTER:
67 return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER; 50 return PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
68 case BACK_CENTER: 51 case BACK_CENTER:
69 return PA_CHANNEL_POSITION_REAR_CENTER; 52 return PA_CHANNEL_POSITION_REAR_CENTER;
70 case SIDE_LEFT: 53 case SIDE_LEFT:
71 return PA_CHANNEL_POSITION_SIDE_LEFT; 54 return PA_CHANNEL_POSITION_SIDE_LEFT;
72 case SIDE_RIGHT: 55 case SIDE_RIGHT:
73 return PA_CHANNEL_POSITION_SIDE_RIGHT; 56 return PA_CHANNEL_POSITION_SIDE_RIGHT;
74 case CHANNELS_MAX: 57 case CHANNELS_MAX:
75 return PA_CHANNEL_POSITION_INVALID; 58 return PA_CHANNEL_POSITION_INVALID;
59 default:
60 NOTREACHED() << "Invalid channel: " << channel;
61 return PA_CHANNEL_POSITION_INVALID;
76 } 62 }
77 NOTREACHED() << "Invalid channel " << channel;
78 return PA_CHANNEL_POSITION_INVALID;
79 } 63 }
80 64
81 static pa_channel_map ChannelLayoutToPAChannelMap( 65 static pa_channel_map ChannelLayoutToPAChannelMap(
82 ChannelLayout channel_layout) { 66 ChannelLayout channel_layout) {
83 // Initialize channel map. 67 // Initialize channel map.
84 pa_channel_map channel_map; 68 pa_channel_map channel_map;
85 pa_channel_map_init(&channel_map); 69 pa_channel_map_init(&channel_map);
86 70
87 channel_map.channels = ChannelLayoutToChannelCount(channel_layout); 71 channel_map.channels = ChannelLayoutToChannelCount(channel_layout);
88 72
(...skipping 12 matching lines...) Expand all
101 85
102 // Fill in the rest of the unused channels. 86 // Fill in the rest of the unused channels.
103 for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX; 87 for (unsigned int channel = CHANNELS_MAX; channel != PA_CHANNELS_MAX;
104 ++channel) { 88 ++channel) {
105 channel_map.map[channel] = PA_CHANNEL_POSITION_MONO; 89 channel_map.map[channel] = PA_CHANNEL_POSITION_MONO;
106 } 90 }
107 91
108 return channel_map; 92 return channel_map;
109 } 93 }
110 94
111 static size_t MicrosecondsToBytes(
112 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
113 return microseconds * sample_rate * bytes_per_frame /
114 base::Time::kMicrosecondsPerSecond;
115 }
116
117 // static
118 void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
119 void* state_addr) {
120 pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr);
121 *state = pa_context_get_state(context);
122 }
123
124 // static 95 // static
125 void PulseAudioOutputStream::WriteRequestCallback(pa_stream* playback_handle, 96 void PulseAudioOutputStream::WriteRequestCallback(pa_stream* playback_handle,
126 size_t length, 97 size_t length, void* p_this) {
127 void* stream_addr) { 98 // Fulfill write request; must always result in a pa_stream_write() call.
128 PulseAudioOutputStream* stream = 99 PulseAudioOutputStream* stream = static_cast<PulseAudioOutputStream*>(p_this);
129 reinterpret_cast<PulseAudioOutputStream*>(stream_addr);
130
131 DCHECK(stream->manager_->GetMessageLoop()->BelongsToCurrentThread());
132
133 stream->write_callback_handled_ = true;
134
135 // Fulfill write request.
136 stream->FulfillWriteRequest(length); 100 stream->FulfillWriteRequest(length);
137 } 101 }
138 102
139 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params, 103 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
140 AudioManagerPulse* manager) 104 AudioManagerBase* manager)
141 : channel_layout_(params.channel_layout()), 105 : params_(params),
142 channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
143 sample_format_(BitsToPASampleFormat(params.bits_per_sample())),
144 sample_rate_(params.sample_rate()),
145 bytes_per_frame_(params.GetBytesPerFrame()),
146 manager_(manager), 106 manager_(manager),
147 pa_context_(NULL), 107 pa_context_(NULL),
148 pa_mainloop_(NULL), 108 pa_mainloop_(NULL),
149 playback_handle_(NULL), 109 playback_handle_(NULL),
150 packet_size_(params.GetBytesPerBuffer()),
151 frames_per_packet_(packet_size_ / bytes_per_frame_),
152 client_buffer_(NULL),
153 volume_(1.0f), 110 volume_(1.0f),
154 stream_stopped_(true),
155 write_callback_handled_(false),
156 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
157 source_callback_(NULL) { 111 source_callback_(NULL) {
158 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 112 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
159 113
160 // TODO(slock): Sanity check input values. 114 CHECK(params_.IsValid());
115 audio_bus_ = AudioBus::Create(params_);
161 } 116 }
162 117
163 PulseAudioOutputStream::~PulseAudioOutputStream() { 118 PulseAudioOutputStream::~PulseAudioOutputStream() {
164 // All internal structures should already have been freed in Close(), 119 // All internal structures should already have been freed in Close(),
165 // which calls AudioManagerPulse::Release which deletes this object. 120 // which calls AudioManagerPulse::Release which deletes this object.
166 DCHECK(!playback_handle_); 121 DCHECK(!playback_handle_);
167 DCHECK(!pa_context_); 122 DCHECK(!pa_context_);
168 DCHECK(!pa_mainloop_); 123 DCHECK(!pa_mainloop_);
169 } 124 }
170 125
126 // Helper macro for Open() to avoid code spam and string bloat.
127 #define PULSE_CHECK(expression, message) \
scherkus (not reviewing) 2012/10/11 20:19:31 this isn't really a CHECK... a more appropriate na
DaleCurtis 2012/10/12 00:09:12 PULSE_CHECK sounds cooler though! :) Sadly, done.
128 if (expression) { \
scherkus (not reviewing) 2012/10/11 20:19:31 you should check for the negated expression readi
scherkus (not reviewing) 2012/10/11 20:19:31 this should be wrapped in a do { ... } while (0)
DaleCurtis 2012/10/12 00:09:12 That's not necessary here since the code's already
DaleCurtis 2012/10/12 00:09:12 Done.
129 if (pa_context_) { \
130 pa_threaded_mainloop_unlock(pa_mainloop_); \
scherkus (not reviewing) 2012/10/11 20:19:31 how about declaring AutoPulseAudioLock helper at t
DaleCurtis 2012/10/12 00:09:12 Done.
131 DLOG(ERROR) << message << pa_context_errno(pa_context_); \
scherkus (not reviewing) 2012/10/11 20:19:31 this forces log messages to know that the context
DaleCurtis 2012/10/12 00:09:12 Done.
132 } else { \
133 DLOG(ERROR) << message; \
134 } \
135 return false; \
136 }
137
171 bool PulseAudioOutputStream::Open() { 138 bool PulseAudioOutputStream::Open() {
172 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 139 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
173 140
174 // TODO(slock): Possibly move most of this to an OpenPlaybackDevice function 141 // Create a mainloop API and connect to the default server.
175 // in a new class 'pulse_util', like alsa_util. 142 pa_mainloop_ = pa_threaded_mainloop_new();
143 PULSE_CHECK(!pa_mainloop_, "Failed to create PulseAudio mainloop.");
176 144
177 // Create a mainloop API and connect to the default server. 145 pa_mainloop_api* pa_mainloop_api = pa_threaded_mainloop_get_api(pa_mainloop_);
178 pa_mainloop_ = pa_mainloop_new();
179 pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_);
180 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium"); 146 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
181 pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED; 147 PULSE_CHECK(!pa_context_, "Failed to create PulseAudio context.");
182 pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL); 148
149 // Lock the mainloop while we setup our context. Failing to do so will lead
150 // to crashes as the PulseAudio thread tries to run before things are ready.
151 pa_threaded_mainloop_lock(pa_mainloop_);
152
153 PULSE_CHECK(pa_threaded_mainloop_start(pa_mainloop_) < 0,
154 "Failed to start PulseAudio mainloop: ");
155 PULSE_CHECK(pa_context_connect(
156 pa_context_, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL) < 0,
157 "Failed to connect PulseAudio context: ");
183 158
184 // Wait until PulseAudio is ready. 159 // Wait until PulseAudio is ready.
185 pa_context_set_state_callback(pa_context_, &ContextStateCallback, 160 pa_context_state_t context_state;
186 &pa_context_state); 161 do {
187 while (pa_context_state != PA_CONTEXT_READY) { 162 pa_threaded_mainloop_wait(pa_mainloop_);
scherkus (not reviewing) 2012/10/11 20:19:31 should we wait before checking the state? i.e., w
DaleCurtis 2012/10/12 00:09:12 No we shouldn't, this will hang. Fixed.
188 pa_mainloop_iterate(pa_mainloop_, 1, NULL); 163 context_state = pa_context_get_state(pa_context_);
189 if (pa_context_state == PA_CONTEXT_FAILED || 164 PULSE_CHECK(!PA_CONTEXT_IS_GOOD(context_state),
190 pa_context_state == PA_CONTEXT_TERMINATED) { 165 "Invalid PulseAudio context state: ");
191 Reset(); 166 } while (context_state != PA_CONTEXT_READY);
192 return false;
193 }
194 }
195 167
196 // Set sample specifications. 168 // Set sample specifications.
197 pa_sample_spec pa_sample_specifications; 169 pa_sample_spec pa_sample_specifications;
198 pa_sample_specifications.format = sample_format_; 170 pa_sample_specifications.format = BitsToPASampleFormat(
199 pa_sample_specifications.rate = sample_rate_; 171 params_.bits_per_sample());
200 pa_sample_specifications.channels = channel_count_; 172 pa_sample_specifications.rate = params_.sample_rate();
173 pa_sample_specifications.channels = params_.channels();
201 174
202 // Get channel mapping and open playback stream. 175 // Get channel mapping and open playback stream.
176 // TODO(dalecurtis): Is this section correct?
scherkus (not reviewing) 2012/10/11 20:19:31 can you elaborate as to what might be incorrect?
DaleCurtis 2012/10/12 00:09:12 No, I just haven't reviewed it thoroughly. Removed
203 pa_channel_map* map = NULL; 177 pa_channel_map* map = NULL;
204 pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap( 178 pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap(
205 channel_layout_); 179 params_.channel_layout());
206 if (source_channel_map.channels != 0) { 180 if (source_channel_map.channels != 0) {
207 // The source data uses a supported channel map so we will use it rather 181 // The source data uses a supported channel map so we will use it rather
208 // than the default channel map (NULL). 182 // than the default channel map (NULL).
209 map = &source_channel_map; 183 map = &source_channel_map;
210 } 184 }
211 playback_handle_ = pa_stream_new(pa_context_, "Playback", 185 playback_handle_ = pa_stream_new(pa_context_, "Playback",
212 &pa_sample_specifications, map); 186 &pa_sample_specifications, map);
187 PULSE_CHECK(!playback_handle_, "Failed to create PulseAudio stream: ");
213 188
214 // Initialize client buffer. 189 // Setup callbacks.
215 uint32 output_packet_size = frames_per_packet_ * bytes_per_frame_;
216 client_buffer_.reset(new media::SeekableBuffer(0, output_packet_size));
217
218 // Set write callback.
219 pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this); 190 pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
220 191
221 // Set server-side buffer attributes. 192 // Tell pulse audio we only want callbacks of a certain size.
222 // (uint32_t)-1 is the default and recommended value from PulseAudio's
223 // documentation, found at:
224 // http://freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.h tml.
225 pa_buffer_attr pa_buffer_attributes; 193 pa_buffer_attr pa_buffer_attributes;
226 pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1); 194 pa_buffer_attributes.maxlength = params_.GetBytesPerBuffer();
227 pa_buffer_attributes.tlength = output_packet_size; 195 pa_buffer_attributes.tlength = params_.GetBytesPerBuffer();
228 pa_buffer_attributes.prebuf = static_cast<uint32_t>(-1); 196 pa_buffer_attributes.prebuf = params_.GetBytesPerBuffer();
229 pa_buffer_attributes.minreq = static_cast<uint32_t>(-1); 197 pa_buffer_attributes.minreq = params_.GetBytesPerBuffer();
230 pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1); 198 pa_buffer_attributes.fragsize = static_cast<uint32_t>(-1);
231 199
232 // Connect playback stream. 200 // Connect playback stream.
233 pa_stream_connect_playback(playback_handle_, NULL, 201 PULSE_CHECK(pa_stream_connect_playback(
234 &pa_buffer_attributes, 202 playback_handle_, NULL, &pa_buffer_attributes,
235 (pa_stream_flags_t) 203 static_cast<pa_stream_flags_t>(
scherkus (not reviewing) 2012/10/11 20:19:31 nit: construct flags variable outside of this func
DaleCurtis 2012/10/12 00:09:12 Removed them all except PA_STREAM_START_CORKED as
236 (PA_STREAM_INTERPOLATE_TIMING | 204 PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY |
237 PA_STREAM_ADJUST_LATENCY | 205 PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_START_CORKED),
238 PA_STREAM_AUTO_TIMING_UPDATE), 206 NULL, NULL) < 0,
239 NULL, NULL); 207 "Failed to connect PulseAudio stream: ");
240 208
241 if (!playback_handle_) { 209 // Wait for the stream to be ready.
242 Reset(); 210 pa_stream_state_t stream_state;
243 return false; 211 do {
244 } 212 pa_threaded_mainloop_wait(pa_mainloop_);
scherkus (not reviewing) 2012/10/11 20:19:31 ditto
DaleCurtis 2012/10/12 00:09:12 Done.
213 stream_state = pa_stream_get_state(playback_handle_);
214 PULSE_CHECK(!PA_STREAM_IS_GOOD(stream_state),
215 "Invalid PulseAudio stream state: ");
216 } while (stream_state != PA_STREAM_READY);
217
218 // Unlock the mainloop now that everything is setup.
219 pa_threaded_mainloop_unlock(pa_mainloop_);
245 220
246 return true; 221 return true;
247 } 222 }
248 223
224 #undef PULSE_CHECK
225
249 void PulseAudioOutputStream::Reset() { 226 void PulseAudioOutputStream::Reset() {
250 stream_stopped_ = true; 227 if (!pa_mainloop_) {
228 DCHECK(!playback_handle_);
229 DCHECK(!pa_context_);
230 return;
231 }
232
233 pa_threaded_mainloop_lock(pa_mainloop_);
251 234
252 // Close the stream. 235 // Close the stream.
253 if (playback_handle_) { 236 if (playback_handle_) {
254 pa_stream_flush(playback_handle_, NULL, NULL); 237 // Ensure all samples are played out before shutdown.
255 pa_stream_disconnect(playback_handle_); 238 WaitForPulseOperation(pa_stream_flush(playback_handle_, NULL, NULL));
256 239
257 // Release PulseAudio structures. 240 // Release PulseAudio structures.
241 pa_stream_disconnect(playback_handle_);
258 pa_stream_unref(playback_handle_); 242 pa_stream_unref(playback_handle_);
259 playback_handle_ = NULL; 243 playback_handle_ = NULL;
260 } 244 }
245
261 if (pa_context_) { 246 if (pa_context_) {
247 pa_context_disconnect(pa_context_);
262 pa_context_unref(pa_context_); 248 pa_context_unref(pa_context_);
263 pa_context_ = NULL; 249 pa_context_ = NULL;
264 } 250 }
265 if (pa_mainloop_) {
266 pa_mainloop_free(pa_mainloop_);
267 pa_mainloop_ = NULL;
268 }
269 251
270 // Release internal buffer. 252 pa_threaded_mainloop_unlock(pa_mainloop_);
271 client_buffer_.reset(); 253 pa_threaded_mainloop_stop(pa_mainloop_);
254 pa_threaded_mainloop_free(pa_mainloop_);
255 pa_mainloop_ = NULL;
272 } 256 }
273 257
274 void PulseAudioOutputStream::Close() { 258 void PulseAudioOutputStream::Close() {
275 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 259 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
276 260
277 Reset(); 261 Reset();
278 262
279 // Signal to the manager that we're closed and can be removed. 263 // Signal to the manager that we're closed and can be removed.
280 // This should be the last call in the function as it deletes "this". 264 // This should be the last call in the function as it deletes "this".
281 manager_->ReleaseOutputStream(this); 265 manager_->ReleaseOutputStream(this);
282 } 266 }
283 267
284 void PulseAudioOutputStream::WaitForWriteRequest() { 268 int PulseAudioOutputStream::GetHardwareLatencyInBytes() {
285 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 269 int negative = 0;
270 pa_usec_t pa_latency_micros = 0;
271 if (pa_stream_get_latency(playback_handle_, &pa_latency_micros,
272 &negative) != 0 || negative)
scherkus (not reviewing) 2012/10/11 20:19:31 can you split this into two ifs? it's a bit subtl
DaleCurtis 2012/10/12 00:09:12 Done.
273 return 0;
286 274
287 if (stream_stopped_) 275 return (pa_latency_micros * params_.sample_rate() *
288 return; 276 params_.GetBytesPerFrame()) / base::Time::kMicrosecondsPerSecond;
289
290 // Iterate the PulseAudio mainloop. If PulseAudio doesn't request a write,
291 // post a task to iterate the mainloop again.
292 write_callback_handled_ = false;
293 pa_mainloop_iterate(pa_mainloop_, 1, NULL);
294 if (!write_callback_handled_) {
295 manager_->GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
296 &PulseAudioOutputStream::WaitForWriteRequest,
297 weak_factory_.GetWeakPtr()));
298 }
299 } 277 }
300 278
301 bool PulseAudioOutputStream::BufferPacketFromSource() { 279 int PulseAudioOutputStream::FillBuffer(void* buffer, size_t buffer_size) {
302 uint32 buffer_delay = client_buffer_->forward_bytes(); 280 CHECK(source_callback_);
303 pa_usec_t pa_latency_micros; 281 int frames_filled = source_callback_->OnMoreData(
304 int negative; 282 audio_bus_.get(), AudioBuffersState(0, GetHardwareLatencyInBytes()));
305 pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
306 uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
307 sample_rate_,
308 bytes_per_frame_);
309 // TODO(slock): Deal with negative latency (negative == 1). This has yet
310 // to happen in practice though.
311 scoped_refptr<media::DataBuffer> packet =
312 new media::DataBuffer(packet_size_);
313 int frames_filled = RunDataCallback(
314 audio_bus_.get(), AudioBuffersState(buffer_delay, hardware_delay));
315 size_t packet_size = frames_filled * bytes_per_frame_;
316 283
317 DCHECK_LE(packet_size, packet_size_); 284 int packet_size = frames_filled * params_.GetBytesPerFrame();
285 if (packet_size == 0)
286 return 0;
287
318 // Note: If this ever changes to output raw float the data must be clipped and 288 // Note: If this ever changes to output raw float the data must be clipped and
319 // sanitized since it may come from an untrusted source such as NaCl. 289 // sanitized since it may come from an untrusted source such as NaCl.
320 audio_bus_->ToInterleaved( 290 CHECK_LE(static_cast<size_t>(packet_size), buffer_size);
321 frames_filled, bytes_per_frame_ / channel_count_, 291 audio_bus_->ToInterleaved(frames_filled, params_.bits_per_sample(), buffer);
322 packet->GetWritableData());
323 292
324 if (packet_size == 0) 293 media::AdjustVolume(buffer, packet_size, params_.channels(),
325 return false; 294 params_.bits_per_sample(), volume_);
326 295 return packet_size;
327 media::AdjustVolume(packet->GetWritableData(),
328 packet_size,
329 channel_count_,
330 bytes_per_frame_ / channel_count_,
331 volume_);
332 packet->SetDataSize(packet_size);
333 // Add the packet to the buffer.
334 client_buffer_->Append(packet);
335 return true;
336 } 296 }
337 297
338 void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) { 298 void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
339 // If we have enough data to fulfill the request, we can finish the write. 299 // Let pa_stream_begin_write auto detect the buffer size, it should choose the
scherkus (not reviewing) 2012/10/11 20:19:31 add ()
DaleCurtis 2012/10/12 00:09:12 Done.
340 if (stream_stopped_) 300 // same size as the callback request. We CHECK() to make sure it does.
341 return; 301 size_t bytes_available = static_cast<size_t>(-1);
302 void* audio_buffer = NULL;
342 303
343 // Request more data from the source until we can fulfill the request or 304 // Request a buffer from PulseAudio and ensure it's the correct size.
344 // fail to receive anymore data. 305 CHECK_GE(pa_stream_begin_write(
345 bool buffering_successful = true; 306 playback_handle_, &audio_buffer, &bytes_available), 0);
346 size_t forward_bytes = static_cast<size_t>(client_buffer_->forward_bytes()); 307 CHECK_EQ(bytes_available, requested_bytes);
347 while (forward_bytes < requested_bytes && buffering_successful) { 308 CHECK_EQ(requested_bytes, static_cast<size_t>(params_.GetBytesPerBuffer()));
348 buffering_successful = BufferPacketFromSource();
349 }
350 309
351 size_t bytes_written = 0; 310 int bytes_filled = FillBuffer(audio_buffer, bytes_available);
352 if (client_buffer_->forward_bytes() > 0) { 311 pa_stream_write(playback_handle_, audio_buffer, bytes_filled, NULL, 0LL,
scherkus (not reviewing) 2012/10/11 20:19:31 check return value?
DaleCurtis 2012/10/12 00:09:12 Done. Add a lot of error handling elsewhere too.
353 // Try to fulfill the request by writing as many of the requested bytes to 312 PA_SEEK_RELATIVE);
354 // the stream as we can.
355 WriteToStream(requested_bytes, &bytes_written);
356 }
357
358 if (bytes_written < requested_bytes) {
359 // We weren't able to buffer enough data to fulfill the request. Try to
360 // fulfill the rest of the request later.
361 manager_->GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
362 &PulseAudioOutputStream::FulfillWriteRequest,
363 weak_factory_.GetWeakPtr(),
364 requested_bytes - bytes_written));
365 } else {
366 // Continue playback.
367 manager_->GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
368 &PulseAudioOutputStream::WaitForWriteRequest,
369 weak_factory_.GetWeakPtr()));
370 }
371 }
372
373 void PulseAudioOutputStream::WriteToStream(size_t bytes_to_write,
374 size_t* bytes_written) {
375 *bytes_written = 0;
376 while (*bytes_written < bytes_to_write) {
377 const uint8* chunk;
378 int chunk_size;
379
380 // Stop writing if there is no more data available.
381 if (!client_buffer_->GetCurrentChunk(&chunk, &chunk_size))
382 break;
383
384 // Write data to stream.
385 pa_stream_write(playback_handle_, chunk, chunk_size,
386 NULL, 0LL, PA_SEEK_RELATIVE);
387 client_buffer_->Seek(chunk_size);
388 *bytes_written += chunk_size;
389 }
390 } 313 }
391 314
392 void PulseAudioOutputStream::Start(AudioSourceCallback* callback) { 315 void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
393 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 316 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
394 CHECK(callback); 317 CHECK(callback);
395 DLOG_IF(ERROR, !playback_handle_) 318 CHECK(playback_handle_);
396 << "Open() has not been called successfully";
397 if (!playback_handle_)
398 return;
399 319
400 source_callback_ = callback; 320 source_callback_ = callback;
401 321
402 // Clear buffer, it might still have data in it. 322 // Uncork (resume) the stream.
403 client_buffer_->Clear(); 323 pa_threaded_mainloop_lock(pa_mainloop_);
404 stream_stopped_ = false; 324 WaitForPulseOperation(pa_stream_cork(playback_handle_, 0, NULL, NULL));
405 325 pa_threaded_mainloop_unlock(pa_mainloop_);
406 // Start playback.
407 manager_->GetMessageLoop()->PostTask(FROM_HERE, base::Bind(
408 &PulseAudioOutputStream::WaitForWriteRequest,
409 weak_factory_.GetWeakPtr()));
410 } 326 }
411 327
412 void PulseAudioOutputStream::Stop() { 328 void PulseAudioOutputStream::Stop() {
413 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 329 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
414 330
415 stream_stopped_ = true; 331 // Cork (pause) the stream. Waiting for the mainloop lock (should) ensure
332 // outstanding callbacks have completed.
333 pa_threaded_mainloop_lock(pa_mainloop_);
334 WaitForPulseOperation(pa_stream_cork(playback_handle_, 1, NULL, NULL));
335 pa_threaded_mainloop_unlock(pa_mainloop_);
336
337 source_callback_ = NULL;
416 } 338 }
417 339
418 void PulseAudioOutputStream::SetVolume(double volume) { 340 void PulseAudioOutputStream::SetVolume(double volume) {
419 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 341 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
420 342
421 volume_ = static_cast<float>(volume); 343 volume_ = static_cast<float>(volume);
422 } 344 }
423 345
424 void PulseAudioOutputStream::GetVolume(double* volume) { 346 void PulseAudioOutputStream::GetVolume(double* volume) {
425 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread()); 347 DCHECK(manager_->GetMessageLoop()->BelongsToCurrentThread());
426 348
427 *volume = volume_; 349 *volume = volume_;
428 } 350 }
429 351
430 int PulseAudioOutputStream::RunDataCallback( 352 void PulseAudioOutputStream::WaitForPulseOperation(pa_operation* op) {
scherkus (not reviewing) 2012/10/11 20:19:31 this function assumes that the caller has locked t
DaleCurtis 2012/10/12 00:09:12 I'm pretty sure those calls need the lock too sinc
431 AudioBus* audio_bus, AudioBuffersState buffers_state) { 353 CHECK(op);
432 if (source_callback_) 354 while (pa_operation_get_state(op) == PA_OPERATION_RUNNING)
433 return source_callback_->OnMoreData(audio_bus, buffers_state); 355 pa_threaded_mainloop_wait(pa_mainloop_);
434 356 pa_operation_unref(op);
435 return 0;
436 } 357 }
437 358
438 } // namespace media 359 } // namespace media
OLDNEW
« media/audio/pulse/pulse_output.h ('K') | « media/audio/pulse/pulse_output.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698