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

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
« no previous file with comments | « media/audio/linux/pulse_output.h ('k') | media/media.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 "base/synchronization/waitable_event.h"
9 #include "media/audio/audio_parameters.h" 10 #include "media/audio/audio_parameters.h"
10 #include "media/audio/audio_util.h" 11 #include "media/audio/audio_util.h"
11 #include "media/audio/linux/audio_manager_linux.h" 12 #include "media/audio/linux/audio_manager_linux.h"
12 #include "media/base/data_buffer.h" 13 #include "media/base/data_buffer.h"
13 #include "media/base/seekable_buffer.h" 14 #include "media/base/seekable_buffer.h"
14 15
16 // TODO(xians): Do we support any sample format rather than PA_SAMPLE_S16LE?
tommi (sloooow) - chröme 2011/11/09 13:57:58 rather -> other
15 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) { 17 static pa_sample_format_t BitsToPASampleFormat(int bits_per_sample) {
16 switch (bits_per_sample) { 18 switch (bits_per_sample) {
17 // Unsupported sample formats shown for reference. I am assuming we want 19 // Unsupported sample formats shown for reference. I am assuming we want
18 // signed and little endian because that is what we gave to ALSA. 20 // signed and little endian because that is what we gave to ALSA.
19 case 8: 21 case 8:
20 return PA_SAMPLE_U8; 22 return PA_SAMPLE_U8;
21 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW 23 // Also 8-bits: PA_SAMPLE_ALAW and PA_SAMPLE_ULAW
enal1 2011/11/11 17:08:07 I used to having comments before the related code.
22 case 16: 24 case 16:
23 return PA_SAMPLE_S16LE; 25 return PA_SAMPLE_S16LE;
24 // Also 16-bits: PA_SAMPLE_S16BE (big endian). 26 // Also 16-bits: PA_SAMPLE_S16BE (big endian).
25 case 24: 27 case 24:
26 return PA_SAMPLE_S24LE; 28 return PA_SAMPLE_S24LE;
27 // Also 24-bits: PA_SAMPLE_S24BE (big endian). 29 // Also 24-bits: PA_SAMPLE_S24BE (big endian).
28 // Other cases: PA_SAMPLE_24_32LE (in LSB of 32-bit field, little endian), 30 // 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), 31 // and PA_SAMPLE_24_32BE (in LSB of 32-bit field, big endian),
30 case 32: 32 case 32:
31 return PA_SAMPLE_S32LE; 33 return PA_SAMPLE_S32LE;
32 // Also 32-bits: PA_SAMPLE_S32BE (big endian), 34 // Also 32-bits: PA_SAMPLE_S32BE (big endian),
33 // PA_SAMPLE_FLOAT32LE (floating point little endian), 35 // PA_SAMPLE_FLOAT32LE (floating point little endian),
34 // and PA_SAMPLE_FLOAT32BE (floating point big endian). 36 // and PA_SAMPLE_FLOAT32BE (floating point big endian).
35 default: 37 default:
36 return PA_SAMPLE_INVALID; 38 return PA_SAMPLE_INVALID;
37 } 39 }
38 } 40 }
39 41
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( 42 static size_t MicrosecondsToBytes(
106 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) { 43 uint32 microseconds, uint32 sample_rate, size_t bytes_per_frame) {
107 return microseconds * sample_rate * bytes_per_frame / 44 return microseconds * sample_rate * bytes_per_frame /
108 base::Time::kMicrosecondsPerSecond; 45 base::Time::kMicrosecondsPerSecond;
109 } 46 }
110 47
111 void PulseAudioOutputStream::ContextStateCallback(pa_context* context, 48 void PulseAudioOutputStream::ContextStateCallback(pa_context* context,
112 void* state_addr) { 49 void* user_data) {
113 pa_context_state_t* state = static_cast<pa_context_state_t*>(state_addr); 50 base::WaitableEvent* completion =
114 *state = pa_context_get_state(context); 51 reinterpret_cast< base::WaitableEvent*>(user_data);
52 pa_context_state_t state = pa_context_get_state(context);
53 switch (state) {
54 case PA_CONTEXT_TERMINATED:
55 completion->Signal();
56 break;
57 case PA_CONTEXT_READY:
58 completion->Signal();
59 break;
60 case PA_CONTEXT_UNCONNECTED:
61 case PA_CONTEXT_CONNECTING:
62 case PA_CONTEXT_AUTHORIZING:
63 case PA_CONTEXT_SETTING_NAME:
64 case PA_CONTEXT_FAILED:
65 default:
66 break;
67 }
115 } 68 }
116 69
117 void PulseAudioOutputStream::WriteRequestCallback( 70 void PulseAudioOutputStream::WriteRequestCallback(
118 pa_stream* playback_handle, size_t length, void* stream_addr) { 71 pa_stream* playback_handle, size_t length, void* user_data) {
119 PulseAudioOutputStream* stream = 72 PulseAudioOutputStream* audio_stream =
120 static_cast<PulseAudioOutputStream*>(stream_addr); 73 reinterpret_cast<PulseAudioOutputStream*>(user_data);
121 74
122 DCHECK_EQ(stream->message_loop_, MessageLoop::current()); 75 audio_stream->FulfillWriteRequest(length);
123
124 stream->write_callback_handled_ = true;
125
126 // Fulfill write request.
127 stream->FulfillWriteRequest(length);
128 } 76 }
129 77
130 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params, 78 PulseAudioOutputStream::PulseAudioOutputStream(const AudioParameters& params,
131 AudioManagerLinux* manager, 79 AudioManagerLinux* manager,
132 MessageLoop* message_loop) 80 MessageLoop* message_loop)
133 : channel_layout_(params.channel_layout), 81 : channels_(params.channels),
134 channel_count_(ChannelLayoutToChannelCount(channel_layout_)),
135 sample_format_(BitsToPASampleFormat(params.bits_per_sample)), 82 sample_format_(BitsToPASampleFormat(params.bits_per_sample)),
136 sample_rate_(params.sample_rate), 83 sample_rate_(params.sample_rate),
137 bytes_per_frame_(params.channels * params.bits_per_sample / 8), 84 bytes_per_frame_(params.channels * params.bits_per_sample / 8),
85 packet_size_(params.GetPacketSize()),
86 frames_per_packet_(packet_size_ / bytes_per_frame_),
138 manager_(manager), 87 manager_(manager),
139 pa_context_(NULL), 88 pa_context_(NULL),
140 pa_mainloop_(NULL), 89 pa_glib_mainloop_(NULL),
141 playback_handle_(NULL), 90 playback_handle_(NULL),
142 packet_size_(params.GetPacketSize()), 91 pa_buffer_size_(0),
143 frames_per_packet_(packet_size_ / bytes_per_frame_), 92 buffer_(NULL),
144 client_buffer_(NULL),
145 volume_(1.0f), 93 volume_(1.0f),
146 stream_stopped_(true), 94 stream_stopped_(true),
147 write_callback_handled_(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());
117 DCHECK(!pa_glib_mainloop_);
167 118
168 // TODO(slock): Possibly move most of this to an OpenPlaybackDevice function 119 // Use glib mainloop that we don't need to care about any processing.
169 // in a new class 'pulse_util', like alsa_util. 120 pa_glib_mainloop_ = pa_glib_mainloop_new(NULL);
121 DCHECK(pa_glib_mainloop_) << "Failed to create PA glib mainloop";
122 if (!pa_glib_mainloop_)
123 return false;
170 124
171 // Create a mainloop API and connect to the default server. 125 // TODO(xians): Figure out if we can share one pa_context_ for streams.
172 pa_mainloop_ = pa_mainloop_new(); 126 pa_mainloop_api* pa_mainloop_api =
173 pa_mainloop_api* pa_mainloop_api = pa_mainloop_get_api(pa_mainloop_); 127 pa_glib_mainloop_get_api(pa_glib_mainloop_);
174 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium"); 128 pa_context_ = pa_context_new(pa_mainloop_api, "Chromium");
175 pa_context_state_t pa_context_state = PA_CONTEXT_UNCONNECTED; 129 DCHECK(pa_context_) << "Failed to create PA context";
176 pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL); 130 if (!pa_context_) {
131 Reset();
132 return false;
133 }
177 134
178 // Wait until PulseAudio is ready. 135 base::WaitableEvent state_changed(false, false);
179 pa_context_set_state_callback(pa_context_, &ContextStateCallback, 136 pa_context_set_state_callback(pa_context_, &ContextStateCallback,
180 &pa_context_state); 137 &state_changed);
181 while (pa_context_state != PA_CONTEXT_READY) { 138 if (pa_context_connect(pa_context_, NULL, PA_CONTEXT_NOFLAGS, NULL)) {
182 pa_mainloop_iterate(pa_mainloop_, 1, NULL); 139 DLOG(ERROR) << "Failed to connect to the context";
183 if (pa_context_state == PA_CONTEXT_FAILED || 140 Reset();
184 pa_context_state == PA_CONTEXT_TERMINATED) { 141 return false;
185 Reset(); 142 }
186 return false; 143
187 } 144 // Wait for state change.
145 const base::TimeDelta kMaxTimeOut = base::TimeDelta::FromMilliseconds(200);
146 if(!state_changed.TimedWait(kMaxTimeOut)) {
147 DLOG(ERROR) << "Timeout when waiting for context state change";
148 return false;
149 }
150
151 if (pa_context_get_state(pa_context_) != PA_CONTEXT_READY) {
152 DLOG(ERROR) << "Unknown problem connecting to PulseAudio server";
153 Reset();
154 return false;
188 } 155 }
189 156
190 // Set sample specifications. 157 // Set sample specifications.
191 pa_sample_spec pa_sample_specifications; 158 pa_sample_spec pa_sample_specifications;
192 pa_sample_specifications.format = sample_format_; 159 pa_sample_specifications.format = sample_format_;
193 pa_sample_specifications.rate = sample_rate_; 160 pa_sample_specifications.rate = sample_rate_;
194 pa_sample_specifications.channels = channel_count_; 161 pa_sample_specifications.channels = channels_;
195 162
196 // Get channel mapping and open playback stream. 163 // Create a new play stream
197 pa_channel_map* map = NULL; 164 playback_handle_ = pa_stream_new(pa_context_, "PlayStream",
198 pa_channel_map source_channel_map = ChannelLayoutToPAChannelMap( 165 &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_) { 166 if (!playback_handle_) {
167 DLOG(ERROR) << "Open: failed to create PA stream";
236 Reset(); 168 Reset();
237 return false; 169 return false;
238 } 170 }
239 171
172 pa_stream_set_write_callback(playback_handle_, &WriteRequestCallback, this);
173 buffer_.reset(new media::SeekableBuffer(0, packet_size_));
240 return true; 174 return true;
241 } 175 }
242 176
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() { 177 void PulseAudioOutputStream::Close() {
269 DCHECK_EQ(message_loop_, MessageLoop::current()); 178 DCHECK_EQ(message_loop_, MessageLoop::current());
270 179
271 Reset(); 180 Reset();
272 181
273 // Signal to the manager that we're closed and can be removed. 182 // 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". 183 // This should be the last call in the function as it deletes "this".
275 manager_->ReleaseOutputStream(this); 184 manager_->ReleaseOutputStream(this);
276 } 185 }
277 186
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) { 187 void PulseAudioOutputStream::Start(AudioSourceCallback* callback) {
381 DCHECK_EQ(message_loop_, MessageLoop::current()); 188 DCHECK_EQ(message_loop_, MessageLoop::current());
189 CHECK(callback);
382 190
383 CHECK(callback); 191 if (!stream_stopped_)
192 return;
193 stream_stopped_ = false;
194
195 // First time to start the stream.
196 if (!source_callback_) {
197 // Set server-side playback buffer metrics. Detailed documentation on what
198 // values should be chosen can be found at
199 // freedesktop.org/software/pulseaudio/doxygen/structpa__buffer__attr.html.
200 pa_buffer_attr pa_buffer_attributes;
201 pa_buffer_size_ = packet_size_;
202 pa_buffer_attributes.maxlength = static_cast<uint32_t>(-1);
203 pa_buffer_attributes.tlength = pa_buffer_size_;
204 pa_buffer_attributes.minreq = pa_buffer_size_ / 2;
205 pa_buffer_attributes.prebuf =
206 pa_buffer_attributes.tlength - pa_buffer_attributes.minreq;
207 pa_buffer_attributes.fragsize = packet_size_;
208 int err = pa_stream_connect_playback(playback_handle_,
209 NULL, // Default device.
210 &pa_buffer_attributes,
211 static_cast<pa_stream_flags_t>(0),
212 NULL, // Default volume.
213 NULL // Standalone stream.
214 );
tommi (sloooow) - chröme 2011/11/09 13:57:58 just keep ); on the preceding line
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.
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
384 source_callback_ = callback; 249 source_callback_ = callback;
385 250
386 // Clear buffer, it might still have data in it. 251 // Before starting, the buffer might have audio from previous user of this
387 client_buffer_->Clear(); 252 // device.
388 stream_stopped_ = false; 253 buffer_->Clear();
389
390 // Start playback.
391 message_loop_->PostTask(FROM_HERE, base::Bind(
392 &PulseAudioOutputStream::WaitForWriteRequest,
393 weak_factory_.GetWeakPtr()));
394 } 254 }
395 255
396 void PulseAudioOutputStream::Stop() { 256 void PulseAudioOutputStream::Stop() {
397 DCHECK_EQ(message_loop_, MessageLoop::current()); 257 DCHECK_EQ(message_loop_, MessageLoop::current());
258 // Set the flag to false to stop filling new data to soundcard.
259 stream_stopped_ = true;
398 260
399 stream_stopped_ = true; 261 if (!playback_handle_)
262 return;
263
264 // Stop the stream.
265 pa_operation* operation = pa_stream_cork(playback_handle_, 1, NULL, NULL);
266 if (!operation) {
267 DLOG(ERROR) << "PulseAudioOutputStream: failed to stop the playout";
268 return;
269 }
270 // Do not need to wait for the operation.
271 pa_operation_unref(operation);
400 } 272 }
401 273
402 void PulseAudioOutputStream::SetVolume(double volume) { 274 void PulseAudioOutputStream::SetVolume(double volume) {
403 DCHECK_EQ(message_loop_, MessageLoop::current()); 275 DCHECK_EQ(message_loop_, MessageLoop::current());
404 276
405 volume_ = static_cast<float>(volume); 277 volume_ = static_cast<float>(volume);
406 } 278 }
407 279
408 void PulseAudioOutputStream::GetVolume(double* volume) { 280 void PulseAudioOutputStream::GetVolume(double* volume) {
409 DCHECK_EQ(message_loop_, MessageLoop::current()); 281 DCHECK_EQ(message_loop_, MessageLoop::current());
410 282
411 *volume = volume_; 283 *volume = volume_;
412 } 284 }
413 285
414 uint32 PulseAudioOutputStream::RunDataCallback( 286 void PulseAudioOutputStream::FulfillWriteRequest(size_t requested_bytes) {
415 uint8* dest, uint32 max_size, AudioBuffersState buffers_state) { 287 // Update the delay.
416 if (source_callback_) 288 pa_usec_t pa_latency_micros;
417 return source_callback_->OnMoreData(this, dest, max_size, buffers_state); 289 int negative;
290 pa_stream_get_latency(playback_handle_, &pa_latency_micros, &negative);
291 uint32 hardware_delay = MicrosecondsToBytes(pa_latency_micros,
292 sample_rate_,
293 bytes_per_frame_);
294 // TODO(slock): Deal with negative latency (negative == 1). This has yet
295 // to happen in practice though.
418 296
419 return 0; 297 // Request more data from the source until we can fulfill the request or
298 // fail to receive anymore data.
299 scoped_refptr<media::DataBuffer> packet(new media::DataBuffer(packet_size_));
300 size_t filled = 0;
301 int bytes_to_fill = requested_bytes;
302
303 while (bytes_to_fill > 0) {
304 // Request more data if we have capacity.
305 if (!buffer_->forward_bytes() && bytes_to_fill) {
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) {
313 packet->SetDataSize(filled);
314 buffer_->Append(packet);
315 }
316 }
317
318 const uint8* buffer_data;
319 size_t buffer_size;
320 if (buffer_->GetCurrentChunk(&buffer_data, &buffer_size)) {
321 if (buffer_size < static_cast<unsigned int>(bytes_to_fill))
322 filled = buffer_size;
323 else
324 filled = bytes_to_fill;
325
326 // Write data to stream.
327 if (pa_stream_write(playback_handle_, buffer_data, filled,
328 NULL, 0, PA_SEEK_RELATIVE)) {
329 DLOG(WARNING) << "FulfillWriteRequest: failed to write "
330 << filled << " bytes of data";
331 }
332
333 // Seek forward in the buffer after we've written some data to ALSA.
334 buffer_->Seek(filled);
335 bytes_to_fill -= filled;
336 }
337 }
420 } 338 }
339
340 void PulseAudioOutputStream::Reset() {
341 stream_stopped_ = true;
342
343 // Close the stream.
344 if (playback_handle_) {
345 // Disable all the callbacks before disconnecting.
346 pa_stream_set_state_callback(playback_handle_, NULL, NULL);
347
348 pa_stream_flush(playback_handle_, NULL, NULL);
349 pa_stream_disconnect(playback_handle_);
350
351 // Release PulseAudio structures.
352 pa_stream_unref(playback_handle_);
353 playback_handle_ = NULL;
354 }
355 if (pa_context_) {
356 pa_context_unref(pa_context_);
357 pa_context_ = NULL;
358 }
359 if (pa_glib_mainloop_) {
360 pa_glib_mainloop_free(pa_glib_mainloop_);
361 pa_glib_mainloop_ = NULL;
362 }
363 }
OLDNEW
« no previous file with comments | « media/audio/linux/pulse_output.h ('k') | media/media.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698