Make 'Google Smart Lock' a hyperlink in the password infobar on Mac.
[chromium-blink-merge.git] / media / audio / audio_output_device.cc
blobd55d10077ed47870fb34521fce57bc24ae4d71c8
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"
13 namespace media {
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
17 // OnStreamCreated().
18 class AudioOutputDevice::AudioThreadCallback
19 : public AudioDeviceThread::Callback {
20 public:
21 AudioThreadCallback(const AudioParameters& audio_parameters,
22 base::SharedMemoryHandle memory,
23 int memory_length,
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;
32 private:
33 AudioRendererSink::RenderCallback* render_callback_;
34 scoped_ptr<AudioBus> output_bus_;
35 uint64 callback_num_;
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),
43 callback_(NULL),
44 ipc_(ipc.Pass()),
45 state_(IDLE),
46 play_on_start_(true),
47 session_id_(-1),
48 stopping_hack_(false) {
49 CHECK(ipc_);
51 // The correctness of the code depends on the relative values assigned in the
52 // State enum.
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,
61 int session_id) {
62 DCHECK(!callback_) << "Calling InitializeWithSessionId() twice?";
63 DCHECK(params.IsValid());
64 audio_parameters_ = params;
65 callback_ = callback;
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
76 // this class.
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,
84 audio_parameters_));
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)
110 return false;
112 if (!task_runner()->PostTask(FROM_HERE,
113 base::Bind(&AudioOutputDevice::SetVolumeOnIOThread, this, volume))) {
114 return false;
117 return true;
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());
133 ipc_->PlayStream();
134 state_ = PLAYING;
135 play_on_start_ = false;
136 } else {
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());
146 ipc_->PauseStream();
147 state_ = PAUSED;
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) {
157 ipc_->CloseStream();
158 state_ = IDLE;
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)
187 return;
189 // TODO(miu): Clean-up inconsistent and incomplete handling here.
190 // http://crbug.com/180640
191 switch (state) {
192 case AUDIO_OUTPUT_IPC_DELEGATE_STATE_PLAYING:
193 case AUDIO_OUTPUT_IPC_DELEGATE_STATE_PAUSED:
194 break;
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();
205 break;
206 default:
207 NOTREACHED();
208 break;
212 void AudioOutputDevice::OnStreamCreated(
213 base::SharedMemoryHandle handle,
214 base::SyncSocket::Handle socket_handle,
215 int length) {
216 DCHECK(task_runner()->BelongsToCurrentThread());
217 DCHECK(base::SharedMemory::IsHandleValid(handle));
218 #if defined(OS_WIN)
219 DCHECK(socket_handle);
220 #else
221 DCHECK_GE(socket_handle, 0);
222 #endif
223 DCHECK_GT(length, 0);
225 if (state_ != CREATING_STREAM)
226 return;
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
239 // details.
240 base::AutoLock auto_lock(audio_thread_lock_);
241 if (stopping_hack_)
242 return;
244 DCHECK(audio_thread_.IsStopped());
245 audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback(
246 audio_parameters_, handle, length, callback_));
247 audio_thread_.Start(
248 audio_callback_.get(), socket_handle, "AudioOutputDevice", true);
249 state_ = PAUSED;
251 // We handle the case where Play() and/or Pause() may have been called
252 // multiple times before OnStreamCreated() gets called.
253 if (play_on_start_)
254 PlayOnIOThread();
257 void AudioOutputDevice::OnIPCClosed() {
258 DCHECK(task_runner()->BelongsToCurrentThread());
259 state_ = IPC_CLOSED;
260 ipc_.reset();
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,
273 int memory_length,
274 AudioRendererSink::RenderCallback* render_callback)
275 : AudioDeviceThread::Callback(audio_parameters, memory, memory_length, 1),
276 render_callback_(render_callback),
277 callback_num_(0) {}
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_));
287 output_bus_ =
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_;
296 callback_num_++;
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.