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