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
3 // found in the LICENSE file.
5 #include "media/audio/audio_output_controller.h"
8 #include "base/metrics/histogram_macros.h"
9 #include "base/numerics/safe_conversions.h"
10 #include "base/task_runner_util.h"
11 #include "base/threading/platform_thread.h"
12 #include "base/time/time.h"
13 #include "base/trace_event/trace_event.h"
15 using base::TimeDelta
;
19 AudioOutputController::AudioOutputController(
20 AudioManager
* audio_manager
,
21 EventHandler
* handler
,
22 const AudioParameters
& params
,
23 const std::string
& output_device_id
,
24 SyncReader
* sync_reader
)
25 : audio_manager_(audio_manager
),
28 output_device_id_(output_device_id
),
30 diverting_to_stream_(NULL
),
33 sync_reader_(sync_reader
),
34 message_loop_(audio_manager
->GetTaskRunner()),
37 TimeDelta::FromMilliseconds(kPowerMeasurementTimeConstantMillis
)),
38 on_more_io_data_called_(0) {
39 DCHECK(audio_manager
);
42 DCHECK(message_loop_
.get());
45 AudioOutputController::~AudioOutputController() {
46 DCHECK_EQ(kClosed
, state_
);
50 scoped_refptr
<AudioOutputController
> AudioOutputController::Create(
51 AudioManager
* audio_manager
,
52 EventHandler
* event_handler
,
53 const AudioParameters
& params
,
54 const std::string
& output_device_id
,
55 SyncReader
* sync_reader
) {
56 DCHECK(audio_manager
);
59 if (!params
.IsValid() || !audio_manager
)
62 scoped_refptr
<AudioOutputController
> controller(new AudioOutputController(
63 audio_manager
, event_handler
, params
, output_device_id
, sync_reader
));
64 controller
->message_loop_
->PostTask(FROM_HERE
, base::Bind(
65 &AudioOutputController::DoCreate
, controller
, false));
69 void AudioOutputController::Play() {
70 message_loop_
->PostTask(FROM_HERE
, base::Bind(
71 &AudioOutputController::DoPlay
, this));
74 void AudioOutputController::Pause() {
75 message_loop_
->PostTask(FROM_HERE
, base::Bind(
76 &AudioOutputController::DoPause
, this));
79 void AudioOutputController::Close(const base::Closure
& closed_task
) {
80 DCHECK(!closed_task
.is_null());
81 message_loop_
->PostTaskAndReply(FROM_HERE
, base::Bind(
82 &AudioOutputController::DoClose
, this), closed_task
);
85 void AudioOutputController::SetVolume(double volume
) {
86 message_loop_
->PostTask(FROM_HERE
, base::Bind(
87 &AudioOutputController::DoSetVolume
, this, volume
));
90 void AudioOutputController::GetOutputDeviceId(
91 base::Callback
<void(const std::string
&)> callback
) const {
92 base::PostTaskAndReplyWithResult(
95 base::Bind(&AudioOutputController::DoGetOutputDeviceId
, this),
99 void AudioOutputController::SwitchOutputDevice(
100 const std::string
& output_device_id
, const base::Closure
& callback
) {
101 message_loop_
->PostTaskAndReply(
103 base::Bind(&AudioOutputController::DoSwitchOutputDevice
, this,
108 void AudioOutputController::DoCreate(bool is_for_device_change
) {
109 DCHECK(message_loop_
->BelongsToCurrentThread());
110 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.CreateTime");
111 TRACE_EVENT0("audio", "AudioOutputController::DoCreate");
113 // Close() can be called before DoCreate() is executed.
114 if (state_
== kClosed
)
117 DoStopCloseAndClearStream(); // Calls RemoveOutputDeviceChangeListener().
118 DCHECK_EQ(kEmpty
, state_
);
120 stream_
= diverting_to_stream_
?
121 diverting_to_stream_
:
122 audio_manager_
->MakeAudioOutputStreamProxy(params_
, output_device_id_
);
129 if (!stream_
->Open()) {
130 DoStopCloseAndClearStream();
136 // Everything started okay, so re-register for state change callbacks if
137 // stream_ was created via AudioManager.
138 if (stream_
!= diverting_to_stream_
)
139 audio_manager_
->AddOutputDeviceChangeListener(this);
141 // We have successfully opened the stream. Set the initial volume.
142 stream_
->SetVolume(volume_
);
144 // Finally set the state to kCreated.
147 // And then report we have been created if we haven't done so already.
148 if (!is_for_device_change
)
149 handler_
->OnCreated();
152 void AudioOutputController::DoPlay() {
153 DCHECK(message_loop_
->BelongsToCurrentThread());
154 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.PlayTime");
155 TRACE_EVENT0("audio", "AudioOutputController::DoPlay");
157 // We can start from created or paused state.
158 if (state_
!= kCreated
&& state_
!= kPaused
)
161 // Ask for first packet.
162 sync_reader_
->UpdatePendingBytes(0);
166 stream_
->Start(this);
168 // For UMA tracking purposes, start the wedge detection timer. This allows us
169 // to record statistics about the number of wedged playbacks in the field.
171 // WedgeCheck() will look to see if |on_more_io_data_called_| is true after
172 // the timeout expires. Care must be taken to ensure the wedge check delay is
173 // large enough that the value isn't queried while OnMoreDataIO() is setting
176 // Timer self-manages its lifetime and WedgeCheck() will only record the UMA
177 // statistic if state is still kPlaying. Additional Start() calls will
178 // invalidate the previous timer.
179 wedge_timer_
.reset(new base::OneShotTimer
<AudioOutputController
>());
181 FROM_HERE
, TimeDelta::FromSeconds(5), this,
182 &AudioOutputController::WedgeCheck
);
184 handler_
->OnPlaying();
187 void AudioOutputController::StopStream() {
188 DCHECK(message_loop_
->BelongsToCurrentThread());
190 if (state_
== kPlaying
) {
191 wedge_timer_
.reset();
194 // A stopped stream is silent, and power_montior_.Scan() is no longer being
195 // called; so we must reset the power monitor.
196 power_monitor_
.Reset();
202 void AudioOutputController::DoPause() {
203 DCHECK(message_loop_
->BelongsToCurrentThread());
204 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.PauseTime");
205 TRACE_EVENT0("audio", "AudioOutputController::DoPause");
209 if (state_
!= kPaused
)
212 // Let the renderer know we've stopped. Necessary to let PPAPI clients know
213 // audio has been shutdown. TODO(dalecurtis): This stinks. PPAPI should have
214 // a better way to know when it should exit PPB_Audio_Shared::Run().
215 sync_reader_
->UpdatePendingBytes(kuint32max
);
217 handler_
->OnPaused();
220 void AudioOutputController::DoClose() {
221 DCHECK(message_loop_
->BelongsToCurrentThread());
222 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.CloseTime");
223 TRACE_EVENT0("audio", "AudioOutputController::DoClose");
225 if (state_
!= kClosed
) {
226 DoStopCloseAndClearStream();
227 sync_reader_
->Close();
232 void AudioOutputController::DoSetVolume(double volume
) {
233 DCHECK(message_loop_
->BelongsToCurrentThread());
235 // Saves the volume to a member first. We may not be able to set the volume
236 // right away but when the stream is created we'll set the volume.
243 stream_
->SetVolume(volume_
);
250 std::string
AudioOutputController::DoGetOutputDeviceId() const {
251 DCHECK(message_loop_
->BelongsToCurrentThread());
252 return output_device_id_
;
255 void AudioOutputController::DoSwitchOutputDevice(
256 const std::string
& output_device_id
) {
257 DCHECK(message_loop_
->BelongsToCurrentThread());
259 if (state_
== kClosed
)
262 if (output_device_id
== output_device_id_
)
265 output_device_id_
= output_device_id
;
267 // If output is currently diverted, we must not call OnDeviceChange
268 // since it would break the diverted setup. Once diversion is
269 // finished using StopDiverting() the output will switch to the new
271 if (stream_
!= diverting_to_stream_
)
275 void AudioOutputController::DoReportError() {
276 DCHECK(message_loop_
->BelongsToCurrentThread());
277 if (state_
!= kClosed
)
281 int AudioOutputController::OnMoreData(AudioBus
* dest
,
282 uint32 total_bytes_delay
) {
283 TRACE_EVENT0("audio", "AudioOutputController::OnMoreData");
285 // Indicate that we haven't wedged (at least not indefinitely, WedgeCheck()
286 // may have already fired if OnMoreData() took an abnormal amount of time).
287 // Since this thread is the only writer of |on_more_io_data_called_| once the
288 // thread starts, its safe to compare and then increment.
289 if (base::AtomicRefCountIsZero(&on_more_io_data_called_
))
290 base::AtomicRefCountInc(&on_more_io_data_called_
);
292 sync_reader_
->Read(dest
);
294 const int frames
= dest
->frames();
295 sync_reader_
->UpdatePendingBytes(base::saturated_cast
<uint32
>(
296 total_bytes_delay
+ frames
* params_
.GetBytesPerFrame()));
298 if (will_monitor_audio_levels())
299 power_monitor_
.Scan(*dest
, frames
);
304 void AudioOutputController::OnError(AudioOutputStream
* stream
) {
305 // Handle error on the audio controller thread.
306 message_loop_
->PostTask(FROM_HERE
, base::Bind(
307 &AudioOutputController::DoReportError
, this));
310 void AudioOutputController::DoStopCloseAndClearStream() {
311 DCHECK(message_loop_
->BelongsToCurrentThread());
313 // Allow calling unconditionally and bail if we don't have a stream_ to close.
315 // De-register from state change callbacks if stream_ was created via
317 if (stream_
!= diverting_to_stream_
)
318 audio_manager_
->RemoveOutputDeviceChangeListener(this);
322 if (stream_
== diverting_to_stream_
)
323 diverting_to_stream_
= NULL
;
330 void AudioOutputController::OnDeviceChange() {
331 DCHECK(message_loop_
->BelongsToCurrentThread());
332 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.DeviceChangeTime");
333 TRACE_EVENT0("audio", "AudioOutputController::OnDeviceChange");
335 // TODO(dalecurtis): Notify the renderer side that a device change has
336 // occurred. Currently querying the hardware information here will lead to
337 // crashes on OSX. See http://crbug.com/158170.
339 // Recreate the stream (DoCreate() will first shut down an existing stream).
340 // Exit if we ran into an error.
341 const State original_state
= state_
;
343 if (!stream_
|| state_
== kError
)
346 // Get us back to the original state or an equivalent state.
347 switch (original_state
) {
353 // From the outside these two states are equivalent.
356 NOTREACHED() << "Invalid original state.";
360 const AudioParameters
& AudioOutputController::GetAudioParameters() {
364 void AudioOutputController::StartDiverting(AudioOutputStream
* to_stream
) {
365 message_loop_
->PostTask(
367 base::Bind(&AudioOutputController::DoStartDiverting
, this, to_stream
));
370 void AudioOutputController::StopDiverting() {
371 message_loop_
->PostTask(
372 FROM_HERE
, base::Bind(&AudioOutputController::DoStopDiverting
, this));
375 void AudioOutputController::DoStartDiverting(AudioOutputStream
* to_stream
) {
376 DCHECK(message_loop_
->BelongsToCurrentThread());
378 if (state_
== kClosed
)
381 DCHECK(!diverting_to_stream_
);
382 diverting_to_stream_
= to_stream
;
383 // Note: OnDeviceChange() will engage the "re-create" process, which will
384 // detect and use the alternate AudioOutputStream rather than create a new one
389 void AudioOutputController::DoStopDiverting() {
390 DCHECK(message_loop_
->BelongsToCurrentThread());
392 if (state_
== kClosed
)
395 // Note: OnDeviceChange() will cause the existing stream (the consumer of the
396 // diverted audio data) to be closed, and diverting_to_stream_ will be set
399 DCHECK(!diverting_to_stream_
);
402 std::pair
<float, bool> AudioOutputController::ReadCurrentPowerAndClip() {
403 DCHECK(will_monitor_audio_levels());
404 return power_monitor_
.ReadCurrentPowerAndClip();
407 void AudioOutputController::WedgeCheck() {
408 DCHECK(message_loop_
->BelongsToCurrentThread());
410 // If we should be playing and we haven't, that's a wedge.
411 if (state_
== kPlaying
) {
412 UMA_HISTOGRAM_BOOLEAN("Media.AudioOutputControllerPlaybackStartupSuccess",
413 base::AtomicRefCountIsOne(&on_more_io_data_called_
));