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/debug/trace_event.h"
9 #include "base/threading/thread_restrictions.h"
10 #include "base/time/time.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 virtual ~AudioThreadCallback();
28 virtual void MapSharedMemory() OVERRIDE;
30 // Called whenever we receive notifications about pending data.
31 virtual void Process(int pending_data) OVERRIDE;
34 AudioRendererSink::RenderCallback* render_callback_;
35 scoped_ptr<AudioBus> input_bus_;
36 scoped_ptr<AudioBus> output_bus_;
37 DISALLOW_COPY_AND_ASSIGN(AudioThreadCallback);
40 AudioOutputDevice::AudioOutputDevice(
41 scoped_ptr<AudioOutputIPC> ipc,
42 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
43 : ScopedTaskRunnerObserver(io_task_runner),
49 stopping_hack_(false) {
52 // The correctness of the code depends on the relative values assigned in the
54 COMPILE_ASSERT(IPC_CLOSED < IDLE, invalid_enum_value_assignment_0);
55 COMPILE_ASSERT(IDLE < CREATING_STREAM, invalid_enum_value_assignment_1);
56 COMPILE_ASSERT(CREATING_STREAM < PAUSED, invalid_enum_value_assignment_2);
57 COMPILE_ASSERT(PAUSED < PLAYING, invalid_enum_value_assignment_3);
60 void AudioOutputDevice::InitializeUnifiedStream(const AudioParameters& params,
61 RenderCallback* callback,
63 DCHECK(!callback_) << "Calling InitializeUnifiedStream() twice?";
64 DCHECK(params.IsValid());
65 audio_parameters_ = params;
67 session_id_ = session_id;
70 void AudioOutputDevice::Initialize(const AudioParameters& params,
71 RenderCallback* callback) {
72 InitializeUnifiedStream(params, callback, 0);
75 AudioOutputDevice::~AudioOutputDevice() {
76 // The current design requires that the user calls Stop() before deleting
78 DCHECK(audio_thread_.IsStopped());
81 void AudioOutputDevice::Start() {
82 DCHECK(callback_) << "Initialize hasn't been called";
83 task_runner()->PostTask(FROM_HERE,
84 base::Bind(&AudioOutputDevice::CreateStreamOnIOThread, this,
88 void AudioOutputDevice::Stop() {
90 base::AutoLock auto_lock(audio_thread_lock_);
91 audio_thread_.Stop(base::MessageLoop::current());
92 stopping_hack_ = true;
95 task_runner()->PostTask(FROM_HERE,
96 base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this));
99 void AudioOutputDevice::Play() {
100 task_runner()->PostTask(FROM_HERE,
101 base::Bind(&AudioOutputDevice::PlayOnIOThread, this));
104 void AudioOutputDevice::Pause() {
105 task_runner()->PostTask(FROM_HERE,
106 base::Bind(&AudioOutputDevice::PauseOnIOThread, this));
109 bool AudioOutputDevice::SetVolume(double volume) {
110 if (volume < 0 || volume > 1.0)
113 if (!task_runner()->PostTask(FROM_HERE,
114 base::Bind(&AudioOutputDevice::SetVolumeOnIOThread, this, volume))) {
121 void AudioOutputDevice::CreateStreamOnIOThread(const AudioParameters& params) {
122 DCHECK(task_runner()->BelongsToCurrentThread());
123 if (state_ == IDLE) {
124 state_ = CREATING_STREAM;
125 ipc_->CreateStream(this, params, session_id_);
129 void AudioOutputDevice::PlayOnIOThread() {
130 DCHECK(task_runner()->BelongsToCurrentThread());
131 if (state_ == PAUSED) {
134 play_on_start_ = false;
136 play_on_start_ = true;
140 void AudioOutputDevice::PauseOnIOThread() {
141 DCHECK(task_runner()->BelongsToCurrentThread());
142 if (state_ == PLAYING) {
146 play_on_start_ = false;
149 void AudioOutputDevice::ShutDownOnIOThread() {
150 DCHECK(task_runner()->BelongsToCurrentThread());
152 // Close the stream, if we haven't already.
153 if (state_ >= CREATING_STREAM) {
158 // We can run into an issue where ShutDownOnIOThread is called right after
159 // OnStreamCreated is called in cases where Start/Stop are called before we
160 // get the OnStreamCreated callback. To handle that corner case, we call
161 // Stop(). In most cases, the thread will already be stopped.
163 // Another situation is when the IO thread goes away before Stop() is called
164 // in which case, we cannot use the message loop to close the thread handle
165 // and can't rely on the main thread existing either.
166 base::AutoLock auto_lock_(audio_thread_lock_);
167 base::ThreadRestrictions::ScopedAllowIO allow_io;
168 audio_thread_.Stop(NULL);
169 audio_callback_.reset();
170 stopping_hack_ = false;
173 void AudioOutputDevice::SetVolumeOnIOThread(double volume) {
174 DCHECK(task_runner()->BelongsToCurrentThread());
175 if (state_ >= CREATING_STREAM)
176 ipc_->SetVolume(volume);
179 void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) {
180 DCHECK(task_runner()->BelongsToCurrentThread());
182 // Do nothing if the stream has been closed.
183 if (state_ < CREATING_STREAM)
186 // TODO(miu): Clean-up inconsistent and incomplete handling here.
187 // http://crbug.com/180640
189 case AudioOutputIPCDelegate::kPlaying:
190 case AudioOutputIPCDelegate::kPaused:
192 case AudioOutputIPCDelegate::kError:
193 DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)";
194 // Don't dereference the callback object if the audio thread
195 // is stopped or stopping. That could mean that the callback
196 // object has been deleted.
197 // TODO(tommi): Add an explicit contract for clearing the callback
198 // object. Possibly require calling Initialize again or provide
199 // a callback object via Start() and clear it in Stop().
200 if (!audio_thread_.IsStopped())
201 callback_->OnRenderError();
209 void AudioOutputDevice::OnStreamCreated(
210 base::SharedMemoryHandle handle,
211 base::SyncSocket::Handle socket_handle,
213 DCHECK(task_runner()->BelongsToCurrentThread());
216 DCHECK(socket_handle);
218 DCHECK_GE(handle.fd, 0);
219 DCHECK_GE(socket_handle, 0);
221 DCHECK_GT(length, 0);
223 if (state_ != CREATING_STREAM)
226 // We can receive OnStreamCreated() on the IO thread after the client has
227 // called Stop() but before ShutDownOnIOThread() is processed. In such a
228 // situation |callback_| might point to freed memory. Instead of starting
229 // |audio_thread_| do nothing and wait for ShutDownOnIOThread() to get called.
231 // TODO(scherkus): The real fix is to have sane ownership semantics. The fact
232 // that |callback_| (which should own and outlive this object!) can point to
233 // freed memory is a mess. AudioRendererSink should be non-refcounted so that
234 // owners (WebRtcAudioDeviceImpl, AudioRendererImpl, etc...) can Stop() and
235 // delete as they see fit. AudioOutputDevice should internally use WeakPtr
236 // to handle teardown and thread hopping. See http://crbug.com/151051 for
238 base::AutoLock auto_lock(audio_thread_lock_);
242 DCHECK(audio_thread_.IsStopped());
243 audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback(
244 audio_parameters_, handle, length, callback_));
246 audio_callback_.get(), socket_handle, "AudioOutputDevice", true);
249 // We handle the case where Play() and/or Pause() may have been called
250 // multiple times before OnStreamCreated() gets called.
255 void AudioOutputDevice::OnIPCClosed() {
256 DCHECK(task_runner()->BelongsToCurrentThread());
261 void AudioOutputDevice::WillDestroyCurrentMessageLoop() {
262 LOG(ERROR) << "IO loop going away before the audio device has been stopped";
263 ShutDownOnIOThread();
266 // AudioOutputDevice::AudioThreadCallback
268 AudioOutputDevice::AudioThreadCallback::AudioThreadCallback(
269 const AudioParameters& audio_parameters,
270 base::SharedMemoryHandle memory,
272 AudioRendererSink::RenderCallback* render_callback)
273 : AudioDeviceThread::Callback(audio_parameters, memory, memory_length, 1),
274 render_callback_(render_callback) {}
276 AudioOutputDevice::AudioThreadCallback::~AudioThreadCallback() {
279 void AudioOutputDevice::AudioThreadCallback::MapSharedMemory() {
280 CHECK_EQ(total_segments_, 1);
281 CHECK(shared_memory_.Map(memory_length_));
283 // Calculate output and input memory size.
284 int output_memory_size = AudioBus::CalculateMemorySize(audio_parameters_);
285 int input_channels = audio_parameters_.input_channels();
286 int frames = audio_parameters_.frames_per_buffer();
287 int input_memory_size = AudioBus::CalculateMemorySize(input_channels, frames);
289 int io_size = output_memory_size + input_memory_size;
291 DCHECK_EQ(memory_length_, io_size);
294 AudioBus::WrapMemory(audio_parameters_, shared_memory_.memory());
296 if (input_channels > 0) {
297 // The input data is after the output data.
299 static_cast<char*>(shared_memory_.memory()) + output_memory_size;
300 input_bus_ = AudioBus::WrapMemory(input_channels, frames, input_data);
304 // Called whenever we receive notifications about pending data.
305 void AudioOutputDevice::AudioThreadCallback::Process(int pending_data) {
306 // Negative |pending_data| indicates the browser side stream has stopped.
307 if (pending_data < 0)
310 // Convert the number of pending bytes in the render buffer into milliseconds.
311 int audio_delay_milliseconds = pending_data / bytes_per_ms_;
313 TRACE_EVENT0("audio", "AudioOutputDevice::FireRenderCallback");
315 // Update the audio-delay measurement then ask client to render audio. Since
316 // |output_bus_| is wrapping the shared memory the Render() call is writing
317 // directly into the shared memory.
318 int input_channels = audio_parameters_.input_channels();
319 if (input_bus_ && input_channels > 0) {
320 render_callback_->RenderIO(
321 input_bus_.get(), output_bus_.get(), audio_delay_milliseconds);
323 render_callback_->Render(output_bus_.get(), audio_delay_milliseconds);
327 } // namespace media.