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/basictypes.h"
8 #include "base/threading/thread_restrictions.h"
9 #include "base/time/time.h"
10 #include "base/trace_event/trace_event.h"
11 #include "media/audio/audio_output_controller.h"
12 #include "media/base/limits.h"
16 // Takes care of invoking the render callback on the audio thread.
17 // An instance of this class is created for each capture stream in
19 class AudioOutputDevice::AudioThreadCallback
20 : public AudioDeviceThread::Callback
{
22 AudioThreadCallback(const AudioParameters
& audio_parameters
,
23 base::SharedMemoryHandle memory
,
25 AudioRendererSink::RenderCallback
* render_callback
);
26 ~AudioThreadCallback() override
;
28 void MapSharedMemory() override
;
30 // Called whenever we receive notifications about pending data.
31 void Process(uint32 pending_data
) override
;
34 AudioRendererSink::RenderCallback
* render_callback_
;
35 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
) {
133 play_on_start_
= false;
135 play_on_start_
= true;
139 void AudioOutputDevice::PauseOnIOThread() {
140 DCHECK(task_runner()->BelongsToCurrentThread());
141 if (state_
== PLAYING
) {
145 play_on_start_
= false;
148 void AudioOutputDevice::ShutDownOnIOThread() {
149 DCHECK(task_runner()->BelongsToCurrentThread());
151 // Close the stream, if we haven't already.
152 if (state_
>= CREATING_STREAM
) {
157 // We can run into an issue where ShutDownOnIOThread is called right after
158 // OnStreamCreated is called in cases where Start/Stop are called before we
159 // get the OnStreamCreated callback. To handle that corner case, we call
160 // Stop(). In most cases, the thread will already be stopped.
162 // Another situation is when the IO thread goes away before Stop() is called
163 // in which case, we cannot use the message loop to close the thread handle
164 // and can't rely on the main thread existing either.
165 base::AutoLock
auto_lock_(audio_thread_lock_
);
166 base::ThreadRestrictions::ScopedAllowIO allow_io
;
167 audio_thread_
.Stop(NULL
);
168 audio_callback_
.reset();
169 stopping_hack_
= false;
172 void AudioOutputDevice::SetVolumeOnIOThread(double volume
) {
173 DCHECK(task_runner()->BelongsToCurrentThread());
174 if (state_
>= CREATING_STREAM
)
175 ipc_
->SetVolume(volume
);
178 void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state
) {
179 DCHECK(task_runner()->BelongsToCurrentThread());
181 // Do nothing if the stream has been closed.
182 if (state_
< CREATING_STREAM
)
185 // TODO(miu): Clean-up inconsistent and incomplete handling here.
186 // http://crbug.com/180640
188 case AudioOutputIPCDelegate::kPlaying
:
189 case AudioOutputIPCDelegate::kPaused
:
191 case AudioOutputIPCDelegate::kError
:
192 DLOG(WARNING
) << "AudioOutputDevice::OnStateChanged(kError)";
193 // Don't dereference the callback object if the audio thread
194 // is stopped or stopping. That could mean that the callback
195 // object has been deleted.
196 // TODO(tommi): Add an explicit contract for clearing the callback
197 // object. Possibly require calling Initialize again or provide
198 // a callback object via Start() and clear it in Stop().
199 if (!audio_thread_
.IsStopped())
200 callback_
->OnRenderError();
208 void AudioOutputDevice::OnStreamCreated(
209 base::SharedMemoryHandle handle
,
210 base::SyncSocket::Handle socket_handle
,
212 DCHECK(task_runner()->BelongsToCurrentThread());
215 DCHECK(socket_handle
);
217 DCHECK_GE(handle
.fd
, 0);
218 DCHECK_GE(socket_handle
, 0);
220 DCHECK_GT(length
, 0);
222 if (state_
!= CREATING_STREAM
)
225 // We can receive OnStreamCreated() on the IO thread after the client has
226 // called Stop() but before ShutDownOnIOThread() is processed. In such a
227 // situation |callback_| might point to freed memory. Instead of starting
228 // |audio_thread_| do nothing and wait for ShutDownOnIOThread() to get called.
230 // TODO(scherkus): The real fix is to have sane ownership semantics. The fact
231 // that |callback_| (which should own and outlive this object!) can point to
232 // freed memory is a mess. AudioRendererSink should be non-refcounted so that
233 // owners (WebRtcAudioDeviceImpl, AudioRendererImpl, etc...) can Stop() and
234 // delete as they see fit. AudioOutputDevice should internally use WeakPtr
235 // to handle teardown and thread hopping. See http://crbug.com/151051 for
237 base::AutoLock
auto_lock(audio_thread_lock_
);
241 DCHECK(audio_thread_
.IsStopped());
242 audio_callback_
.reset(new AudioOutputDevice::AudioThreadCallback(
243 audio_parameters_
, handle
, length
, callback_
));
245 audio_callback_
.get(), socket_handle
, "AudioOutputDevice", true);
248 // We handle the case where Play() and/or Pause() may have been called
249 // multiple times before OnStreamCreated() gets called.
254 void AudioOutputDevice::OnIPCClosed() {
255 DCHECK(task_runner()->BelongsToCurrentThread());
260 void AudioOutputDevice::WillDestroyCurrentMessageLoop() {
261 LOG(ERROR
) << "IO loop going away before the audio device has been stopped";
262 ShutDownOnIOThread();
265 // AudioOutputDevice::AudioThreadCallback
267 AudioOutputDevice::AudioThreadCallback::AudioThreadCallback(
268 const AudioParameters
& audio_parameters
,
269 base::SharedMemoryHandle memory
,
271 AudioRendererSink::RenderCallback
* render_callback
)
272 : AudioDeviceThread::Callback(audio_parameters
, memory
, memory_length
, 1),
273 render_callback_(render_callback
) {}
275 AudioOutputDevice::AudioThreadCallback::~AudioThreadCallback() {
278 void AudioOutputDevice::AudioThreadCallback::MapSharedMemory() {
279 CHECK_EQ(total_segments_
, 1);
280 CHECK(shared_memory_
.Map(memory_length_
));
281 DCHECK_EQ(memory_length_
, AudioBus::CalculateMemorySize(audio_parameters_
));
284 AudioBus::WrapMemory(audio_parameters_
, shared_memory_
.memory());
287 // Called whenever we receive notifications about pending data.
288 void AudioOutputDevice::AudioThreadCallback::Process(uint32 pending_data
) {
289 // Convert the number of pending bytes in the render buffer into milliseconds.
290 int audio_delay_milliseconds
= pending_data
/ bytes_per_ms_
;
292 TRACE_EVENT0("audio", "AudioOutputDevice::FireRenderCallback");
294 // Update the audio-delay measurement then ask client to render audio. Since
295 // |output_bus_| is wrapping the shared memory the Render() call is writing
296 // directly into the shared memory.
297 render_callback_
->Render(output_bus_
.get(), audio_delay_milliseconds
);
300 } // namespace media.