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_device.h"
7 #include "base/threading/thread_restrictions.h"
8 #include "base/time/time.h"
9 #include "base/trace_event/trace_event.h"
10 #include "media/audio/audio_output_controller.h"
11 #include "media/base/limits.h"
15 // Takes care of invoking the render callback on the audio thread.
16 // An instance of this class is created for each capture stream in
18 class AudioOutputDevice::AudioThreadCallback
19 : public AudioDeviceThread::Callback
{
21 AudioThreadCallback(const AudioParameters
& audio_parameters
,
22 base::SharedMemoryHandle memory
,
24 AudioRendererSink::RenderCallback
* render_callback
);
25 ~AudioThreadCallback() override
;
27 void MapSharedMemory() override
;
29 // Called whenever we receive notifications about pending data.
30 void Process(uint32 pending_data
) override
;
33 AudioRendererSink::RenderCallback
* render_callback_
;
34 scoped_ptr
<AudioBus
> output_bus_
;
36 DISALLOW_COPY_AND_ASSIGN(AudioThreadCallback
);
39 AudioOutputDevice::AudioOutputDevice(
40 scoped_ptr
<AudioOutputIPC
> ipc
,
41 const scoped_refptr
<base::SingleThreadTaskRunner
>& io_task_runner
)
42 : ScopedTaskRunnerObserver(io_task_runner
),
48 stopping_hack_(false) {
51 // The correctness of the code depends on the relative values assigned in the
53 static_assert(IPC_CLOSED
< IDLE
, "invalid enum value assignment 0");
54 static_assert(IDLE
< CREATING_STREAM
, "invalid enum value assignment 1");
55 static_assert(CREATING_STREAM
< PAUSED
, "invalid enum value assignment 2");
56 static_assert(PAUSED
< PLAYING
, "invalid enum value assignment 3");
59 void AudioOutputDevice::InitializeWithSessionId(const AudioParameters
& params
,
60 RenderCallback
* callback
,
62 DCHECK(!callback_
) << "Calling InitializeWithSessionId() twice?";
63 DCHECK(params
.IsValid());
64 audio_parameters_
= params
;
66 session_id_
= session_id
;
69 void AudioOutputDevice::Initialize(const AudioParameters
& params
,
70 RenderCallback
* callback
) {
71 InitializeWithSessionId(params
, callback
, 0);
74 AudioOutputDevice::~AudioOutputDevice() {
75 // The current design requires that the user calls Stop() before deleting
77 DCHECK(audio_thread_
.IsStopped());
80 void AudioOutputDevice::Start() {
81 DCHECK(callback_
) << "Initialize hasn't been called";
82 task_runner()->PostTask(FROM_HERE
,
83 base::Bind(&AudioOutputDevice::CreateStreamOnIOThread
, this,
87 void AudioOutputDevice::Stop() {
89 base::AutoLock
auto_lock(audio_thread_lock_
);
90 audio_thread_
.Stop(base::MessageLoop::current());
91 stopping_hack_
= true;
94 task_runner()->PostTask(FROM_HERE
,
95 base::Bind(&AudioOutputDevice::ShutDownOnIOThread
, this));
98 void AudioOutputDevice::Play() {
99 task_runner()->PostTask(FROM_HERE
,
100 base::Bind(&AudioOutputDevice::PlayOnIOThread
, this));
103 void AudioOutputDevice::Pause() {
104 task_runner()->PostTask(FROM_HERE
,
105 base::Bind(&AudioOutputDevice::PauseOnIOThread
, this));
108 bool AudioOutputDevice::SetVolume(double volume
) {
109 if (volume
< 0 || volume
> 1.0)
112 if (!task_runner()->PostTask(FROM_HERE
,
113 base::Bind(&AudioOutputDevice::SetVolumeOnIOThread
, this, volume
))) {
120 void AudioOutputDevice::CreateStreamOnIOThread(const AudioParameters
& params
) {
121 DCHECK(task_runner()->BelongsToCurrentThread());
122 if (state_
== IDLE
) {
123 state_
= CREATING_STREAM
;
124 ipc_
->CreateStream(this, params
, session_id_
);
128 void AudioOutputDevice::PlayOnIOThread() {
129 DCHECK(task_runner()->BelongsToCurrentThread());
130 if (state_
== PAUSED
) {
131 TRACE_EVENT_ASYNC_BEGIN0(
132 "audio", "StartingPlayback", audio_callback_
.get());
135 play_on_start_
= false;
137 play_on_start_
= true;
141 void AudioOutputDevice::PauseOnIOThread() {
142 DCHECK(task_runner()->BelongsToCurrentThread());
143 if (state_
== PLAYING
) {
144 TRACE_EVENT_ASYNC_END0(
145 "audio", "StartingPlayback", audio_callback_
.get());
149 play_on_start_
= false;
152 void AudioOutputDevice::ShutDownOnIOThread() {
153 DCHECK(task_runner()->BelongsToCurrentThread());
155 // Close the stream, if we haven't already.
156 if (state_
>= CREATING_STREAM
) {
161 // We can run into an issue where ShutDownOnIOThread is called right after
162 // OnStreamCreated is called in cases where Start/Stop are called before we
163 // get the OnStreamCreated callback. To handle that corner case, we call
164 // Stop(). In most cases, the thread will already be stopped.
166 // Another situation is when the IO thread goes away before Stop() is called
167 // in which case, we cannot use the message loop to close the thread handle
168 // and can't rely on the main thread existing either.
169 base::AutoLock
auto_lock_(audio_thread_lock_
);
170 base::ThreadRestrictions::ScopedAllowIO allow_io
;
171 audio_thread_
.Stop(NULL
);
172 audio_callback_
.reset();
173 stopping_hack_
= false;
176 void AudioOutputDevice::SetVolumeOnIOThread(double volume
) {
177 DCHECK(task_runner()->BelongsToCurrentThread());
178 if (state_
>= CREATING_STREAM
)
179 ipc_
->SetVolume(volume
);
182 void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegateState state
) {
183 DCHECK(task_runner()->BelongsToCurrentThread());
185 // Do nothing if the stream has been closed.
186 if (state_
< CREATING_STREAM
)
189 // TODO(miu): Clean-up inconsistent and incomplete handling here.
190 // http://crbug.com/180640
192 case AUDIO_OUTPUT_IPC_DELEGATE_STATE_PLAYING
:
193 case AUDIO_OUTPUT_IPC_DELEGATE_STATE_PAUSED
:
195 case AUDIO_OUTPUT_IPC_DELEGATE_STATE_ERROR
:
196 DLOG(WARNING
) << "AudioOutputDevice::OnStateChanged(ERROR)";
197 // Don't dereference the callback object if the audio thread
198 // is stopped or stopping. That could mean that the callback
199 // object has been deleted.
200 // TODO(tommi): Add an explicit contract for clearing the callback
201 // object. Possibly require calling Initialize again or provide
202 // a callback object via Start() and clear it in Stop().
203 if (!audio_thread_
.IsStopped())
204 callback_
->OnRenderError();
212 void AudioOutputDevice::OnStreamCreated(
213 base::SharedMemoryHandle handle
,
214 base::SyncSocket::Handle socket_handle
,
216 DCHECK(task_runner()->BelongsToCurrentThread());
217 DCHECK(base::SharedMemory::IsHandleValid(handle
));
219 DCHECK(socket_handle
);
221 DCHECK_GE(socket_handle
, 0);
223 DCHECK_GT(length
, 0);
225 if (state_
!= CREATING_STREAM
)
228 // We can receive OnStreamCreated() on the IO thread after the client has
229 // called Stop() but before ShutDownOnIOThread() is processed. In such a
230 // situation |callback_| might point to freed memory. Instead of starting
231 // |audio_thread_| do nothing and wait for ShutDownOnIOThread() to get called.
233 // TODO(scherkus): The real fix is to have sane ownership semantics. The fact
234 // that |callback_| (which should own and outlive this object!) can point to
235 // freed memory is a mess. AudioRendererSink should be non-refcounted so that
236 // owners (WebRtcAudioDeviceImpl, AudioRendererImpl, etc...) can Stop() and
237 // delete as they see fit. AudioOutputDevice should internally use WeakPtr
238 // to handle teardown and thread hopping. See http://crbug.com/151051 for
240 base::AutoLock
auto_lock(audio_thread_lock_
);
244 DCHECK(audio_thread_
.IsStopped());
245 audio_callback_
.reset(new AudioOutputDevice::AudioThreadCallback(
246 audio_parameters_
, handle
, length
, callback_
));
248 audio_callback_
.get(), socket_handle
, "AudioOutputDevice", true);
251 // We handle the case where Play() and/or Pause() may have been called
252 // multiple times before OnStreamCreated() gets called.
257 void AudioOutputDevice::OnIPCClosed() {
258 DCHECK(task_runner()->BelongsToCurrentThread());
263 void AudioOutputDevice::WillDestroyCurrentMessageLoop() {
264 LOG(ERROR
) << "IO loop going away before the audio device has been stopped";
265 ShutDownOnIOThread();
268 // AudioOutputDevice::AudioThreadCallback
270 AudioOutputDevice::AudioThreadCallback::AudioThreadCallback(
271 const AudioParameters
& audio_parameters
,
272 base::SharedMemoryHandle memory
,
274 AudioRendererSink::RenderCallback
* render_callback
)
275 : AudioDeviceThread::Callback(audio_parameters
, memory
, memory_length
, 1),
276 render_callback_(render_callback
),
279 AudioOutputDevice::AudioThreadCallback::~AudioThreadCallback() {
282 void AudioOutputDevice::AudioThreadCallback::MapSharedMemory() {
283 CHECK_EQ(total_segments_
, 1);
284 CHECK(shared_memory_
.Map(memory_length_
));
285 DCHECK_EQ(memory_length_
, AudioBus::CalculateMemorySize(audio_parameters_
));
288 AudioBus::WrapMemory(audio_parameters_
, shared_memory_
.memory());
291 // Called whenever we receive notifications about pending data.
292 void AudioOutputDevice::AudioThreadCallback::Process(uint32 pending_data
) {
293 // Convert the number of pending bytes in the render buffer into milliseconds.
294 int audio_delay_milliseconds
= pending_data
/ bytes_per_ms_
;
297 TRACE_EVENT1("audio", "AudioOutputDevice::FireRenderCallback",
298 "callback_num", callback_num_
);
300 // When playback starts, we get an immediate callback to Process to make sure
301 // that we have some data, we'll get another one after the device is awake and
302 // ingesting data, which is what we want to track with this trace.
303 if (callback_num_
== 2) {
304 TRACE_EVENT_ASYNC_END0("audio", "StartingPlayback", this);
307 // Update the audio-delay measurement then ask client to render audio. Since
308 // |output_bus_| is wrapping the shared memory the Render() call is writing
309 // directly into the shared memory.
310 render_callback_
->Render(output_bus_
.get(), audio_delay_milliseconds
);
313 } // namespace media.