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/debug/trace_event.h"
9 #include "base/metrics/histogram.h"
10 #include "base/numerics/safe_conversions.h"
11 #include "base/task_runner_util.h"
12 #include "base/threading/platform_thread.h"
13 #include "base/time/time.h"
14 #include "build/build_config.h"
15 #include "media/base/scoped_histogram_timer.h"
17 using base::TimeDelta
;
21 AudioOutputController::AudioOutputController(
22 AudioManager
* audio_manager
,
23 EventHandler
* handler
,
24 const AudioParameters
& params
,
25 const std::string
& output_device_id
,
26 SyncReader
* sync_reader
)
27 : audio_manager_(audio_manager
),
30 output_device_id_(output_device_id
),
32 diverting_to_stream_(NULL
),
35 sync_reader_(sync_reader
),
36 message_loop_(audio_manager
->GetTaskRunner()),
39 TimeDelta::FromMilliseconds(kPowerMeasurementTimeConstantMillis
)),
40 on_more_io_data_called_(0) {
41 DCHECK(audio_manager
);
44 DCHECK(message_loop_
.get());
47 AudioOutputController::~AudioOutputController() {
48 DCHECK_EQ(kClosed
, state_
);
52 scoped_refptr
<AudioOutputController
> AudioOutputController::Create(
53 AudioManager
* audio_manager
,
54 EventHandler
* event_handler
,
55 const AudioParameters
& params
,
56 const std::string
& output_device_id
,
57 SyncReader
* sync_reader
) {
58 DCHECK(audio_manager
);
61 if (!params
.IsValid() || !audio_manager
)
64 scoped_refptr
<AudioOutputController
> controller(new AudioOutputController(
65 audio_manager
, event_handler
, params
, output_device_id
, sync_reader
));
66 controller
->message_loop_
->PostTask(FROM_HERE
, base::Bind(
67 &AudioOutputController::DoCreate
, controller
, false));
71 void AudioOutputController::Play() {
72 message_loop_
->PostTask(FROM_HERE
, base::Bind(
73 &AudioOutputController::DoPlay
, this));
76 void AudioOutputController::Pause() {
77 message_loop_
->PostTask(FROM_HERE
, base::Bind(
78 &AudioOutputController::DoPause
, this));
81 void AudioOutputController::Close(const base::Closure
& closed_task
) {
82 DCHECK(!closed_task
.is_null());
83 message_loop_
->PostTaskAndReply(FROM_HERE
, base::Bind(
84 &AudioOutputController::DoClose
, this), closed_task
);
87 void AudioOutputController::SetVolume(double volume
) {
88 message_loop_
->PostTask(FROM_HERE
, base::Bind(
89 &AudioOutputController::DoSetVolume
, this, volume
));
92 void AudioOutputController::GetOutputDeviceId(
93 base::Callback
<void(const std::string
&)> callback
) const {
94 base::PostTaskAndReplyWithResult(
97 base::Bind(&AudioOutputController::DoGetOutputDeviceId
, this),
101 void AudioOutputController::SwitchOutputDevice(
102 const std::string
& output_device_id
, const base::Closure
& callback
) {
103 message_loop_
->PostTaskAndReply(
105 base::Bind(&AudioOutputController::DoSwitchOutputDevice
, this,
110 void AudioOutputController::DoCreate(bool is_for_device_change
) {
111 DCHECK(message_loop_
->BelongsToCurrentThread());
112 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.CreateTime");
113 TRACE_EVENT0("audio", "AudioOutputController::DoCreate");
115 // Close() can be called before DoCreate() is executed.
116 if (state_
== kClosed
)
119 DoStopCloseAndClearStream(); // Calls RemoveOutputDeviceChangeListener().
120 DCHECK_EQ(kEmpty
, state_
);
122 stream_
= diverting_to_stream_
?
123 diverting_to_stream_
:
124 audio_manager_
->MakeAudioOutputStreamProxy(params_
, output_device_id_
);
131 if (!stream_
->Open()) {
132 DoStopCloseAndClearStream();
138 // Everything started okay, so re-register for state change callbacks if
139 // stream_ was created via AudioManager.
140 if (stream_
!= diverting_to_stream_
)
141 audio_manager_
->AddOutputDeviceChangeListener(this);
143 // We have successfully opened the stream. Set the initial volume.
144 stream_
->SetVolume(volume_
);
146 // Finally set the state to kCreated.
149 // And then report we have been created if we haven't done so already.
150 if (!is_for_device_change
)
151 handler_
->OnCreated();
154 void AudioOutputController::DoPlay() {
155 DCHECK(message_loop_
->BelongsToCurrentThread());
156 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.PlayTime");
157 TRACE_EVENT0("audio", "AudioOutputController::DoPlay");
159 // We can start from created or paused state.
160 if (state_
!= kCreated
&& state_
!= kPaused
)
163 // Ask for first packet.
164 sync_reader_
->UpdatePendingBytes(0);
168 stream_
->Start(this);
170 // For UMA tracking purposes, start the wedge detection timer. This allows us
171 // to record statistics about the number of wedged playbacks in the field.
173 // WedgeCheck() will look to see if |on_more_io_data_called_| is true after
174 // the timeout expires. Care must be taken to ensure the wedge check delay is
175 // large enough that the value isn't queried while OnMoreDataIO() is setting
178 // Timer self-manages its lifetime and WedgeCheck() will only record the UMA
179 // statistic if state is still kPlaying. Additional Start() calls will
180 // invalidate the previous timer.
181 wedge_timer_
.reset(new base::OneShotTimer
<AudioOutputController
>());
183 FROM_HERE
, TimeDelta::FromSeconds(5), this,
184 &AudioOutputController::WedgeCheck
);
186 handler_
->OnPlaying();
189 void AudioOutputController::StopStream() {
190 DCHECK(message_loop_
->BelongsToCurrentThread());
192 if (state_
== kPlaying
) {
193 wedge_timer_
.reset();
196 // A stopped stream is silent, and power_montior_.Scan() is no longer being
197 // called; so we must reset the power monitor.
198 power_monitor_
.Reset();
204 void AudioOutputController::DoPause() {
205 DCHECK(message_loop_
->BelongsToCurrentThread());
206 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.PauseTime");
207 TRACE_EVENT0("audio", "AudioOutputController::DoPause");
211 if (state_
!= kPaused
)
214 // Let the renderer know we've stopped. Necessary to let PPAPI clients know
215 // audio has been shutdown. TODO(dalecurtis): This stinks. PPAPI should have
216 // a better way to know when it should exit PPB_Audio_Shared::Run().
217 sync_reader_
->UpdatePendingBytes(kuint32max
);
219 handler_
->OnPaused();
222 void AudioOutputController::DoClose() {
223 DCHECK(message_loop_
->BelongsToCurrentThread());
224 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.CloseTime");
225 TRACE_EVENT0("audio", "AudioOutputController::DoClose");
227 if (state_
!= kClosed
) {
228 DoStopCloseAndClearStream();
229 sync_reader_
->Close();
234 void AudioOutputController::DoSetVolume(double volume
) {
235 DCHECK(message_loop_
->BelongsToCurrentThread());
237 // Saves the volume to a member first. We may not be able to set the volume
238 // right away but when the stream is created we'll set the volume.
245 stream_
->SetVolume(volume_
);
252 std::string
AudioOutputController::DoGetOutputDeviceId() const {
253 DCHECK(message_loop_
->BelongsToCurrentThread());
254 return output_device_id_
;
257 void AudioOutputController::DoSwitchOutputDevice(
258 const std::string
& output_device_id
) {
259 DCHECK(message_loop_
->BelongsToCurrentThread());
261 if (state_
== kClosed
)
264 if (output_device_id
== output_device_id_
)
267 output_device_id_
= output_device_id
;
269 // If output is currently diverted, we must not call OnDeviceChange
270 // since it would break the diverted setup. Once diversion is
271 // finished using StopDiverting() the output will switch to the new
273 if (stream_
!= diverting_to_stream_
)
277 void AudioOutputController::DoReportError() {
278 DCHECK(message_loop_
->BelongsToCurrentThread());
279 if (state_
!= kClosed
)
283 int AudioOutputController::OnMoreData(AudioBus
* dest
,
284 uint32 total_bytes_delay
) {
285 TRACE_EVENT0("audio", "AudioOutputController::OnMoreData");
287 // Indicate that we haven't wedged (at least not indefinitely, WedgeCheck()
288 // may have already fired if OnMoreData() took an abnormal amount of time).
289 // Since this thread is the only writer of |on_more_io_data_called_| once the
290 // thread starts, its safe to compare and then increment.
291 if (base::AtomicRefCountIsZero(&on_more_io_data_called_
))
292 base::AtomicRefCountInc(&on_more_io_data_called_
);
294 sync_reader_
->Read(dest
);
296 const int frames
= dest
->frames();
297 sync_reader_
->UpdatePendingBytes(base::saturated_cast
<uint32
>(
298 total_bytes_delay
+ frames
* params_
.GetBytesPerFrame()));
300 if (will_monitor_audio_levels())
301 power_monitor_
.Scan(*dest
, frames
);
306 void AudioOutputController::OnError(AudioOutputStream
* stream
) {
307 // Handle error on the audio controller thread.
308 message_loop_
->PostTask(FROM_HERE
, base::Bind(
309 &AudioOutputController::DoReportError
, this));
312 void AudioOutputController::DoStopCloseAndClearStream() {
313 DCHECK(message_loop_
->BelongsToCurrentThread());
315 // Allow calling unconditionally and bail if we don't have a stream_ to close.
317 // De-register from state change callbacks if stream_ was created via
319 if (stream_
!= diverting_to_stream_
)
320 audio_manager_
->RemoveOutputDeviceChangeListener(this);
324 if (stream_
== diverting_to_stream_
)
325 diverting_to_stream_
= NULL
;
332 void AudioOutputController::OnDeviceChange() {
333 DCHECK(message_loop_
->BelongsToCurrentThread());
334 SCOPED_UMA_HISTOGRAM_TIMER("Media.AudioOutputController.DeviceChangeTime");
335 TRACE_EVENT0("audio", "AudioOutputController::OnDeviceChange");
337 // TODO(dalecurtis): Notify the renderer side that a device change has
338 // occurred. Currently querying the hardware information here will lead to
339 // crashes on OSX. See http://crbug.com/158170.
341 // Recreate the stream (DoCreate() will first shut down an existing stream).
342 // Exit if we ran into an error.
343 const State original_state
= state_
;
345 if (!stream_
|| state_
== kError
)
348 // Get us back to the original state or an equivalent state.
349 switch (original_state
) {
355 // From the outside these two states are equivalent.
358 NOTREACHED() << "Invalid original state.";
362 const AudioParameters
& AudioOutputController::GetAudioParameters() {
366 void AudioOutputController::StartDiverting(AudioOutputStream
* to_stream
) {
367 message_loop_
->PostTask(
369 base::Bind(&AudioOutputController::DoStartDiverting
, this, to_stream
));
372 void AudioOutputController::StopDiverting() {
373 message_loop_
->PostTask(
374 FROM_HERE
, base::Bind(&AudioOutputController::DoStopDiverting
, this));
377 void AudioOutputController::DoStartDiverting(AudioOutputStream
* to_stream
) {
378 DCHECK(message_loop_
->BelongsToCurrentThread());
380 if (state_
== kClosed
)
383 DCHECK(!diverting_to_stream_
);
384 diverting_to_stream_
= to_stream
;
385 // Note: OnDeviceChange() will engage the "re-create" process, which will
386 // detect and use the alternate AudioOutputStream rather than create a new one
391 void AudioOutputController::DoStopDiverting() {
392 DCHECK(message_loop_
->BelongsToCurrentThread());
394 if (state_
== kClosed
)
397 // Note: OnDeviceChange() will cause the existing stream (the consumer of the
398 // diverted audio data) to be closed, and diverting_to_stream_ will be set
401 DCHECK(!diverting_to_stream_
);
404 std::pair
<float, bool> AudioOutputController::ReadCurrentPowerAndClip() {
405 DCHECK(will_monitor_audio_levels());
406 return power_monitor_
.ReadCurrentPowerAndClip();
409 void AudioOutputController::WedgeCheck() {
410 DCHECK(message_loop_
->BelongsToCurrentThread());
412 // If we should be playing and we haven't, that's a wedge.
413 if (state_
== kPlaying
) {
414 UMA_HISTOGRAM_BOOLEAN("Media.AudioOutputControllerPlaybackStartupSuccess",
415 base::AtomicRefCountIsOne(&on_more_io_data_called_
));