Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / media / audio / audio_output_device.cc
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.
4
5 #include "media/audio/audio_output_device.h"
6
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"
13
14 namespace media {
15
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
18 // OnStreamCreated().
19 class AudioOutputDevice::AudioThreadCallback
20     : public AudioDeviceThread::Callback {
21  public:
22   AudioThreadCallback(const AudioParameters& audio_parameters,
23                       base::SharedMemoryHandle memory,
24                       int memory_length,
25                       AudioRendererSink::RenderCallback* render_callback);
26   virtual ~AudioThreadCallback();
27
28   virtual void MapSharedMemory() OVERRIDE;
29
30   // Called whenever we receive notifications about pending data.
31   virtual void Process(int pending_data) OVERRIDE;
32
33  private:
34   AudioRendererSink::RenderCallback* render_callback_;
35   scoped_ptr<AudioBus> input_bus_;
36   scoped_ptr<AudioBus> output_bus_;
37   DISALLOW_COPY_AND_ASSIGN(AudioThreadCallback);
38 };
39
40 AudioOutputDevice::AudioOutputDevice(
41     scoped_ptr<AudioOutputIPC> ipc,
42     const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
43     : ScopedTaskRunnerObserver(io_task_runner),
44       callback_(NULL),
45       ipc_(ipc.Pass()),
46       state_(IDLE),
47       play_on_start_(true),
48       session_id_(-1),
49       stopping_hack_(false) {
50   CHECK(ipc_);
51
52   // The correctness of the code depends on the relative values assigned in the
53   // State enum.
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);
58 }
59
60 void AudioOutputDevice::InitializeUnifiedStream(const AudioParameters& params,
61                                                 RenderCallback* callback,
62                                                 int session_id) {
63   DCHECK(!callback_) << "Calling InitializeUnifiedStream() twice?";
64   DCHECK(params.IsValid());
65   audio_parameters_ = params;
66   callback_ = callback;
67   session_id_ = session_id;
68 }
69
70 void AudioOutputDevice::Initialize(const AudioParameters& params,
71                                    RenderCallback* callback) {
72   InitializeUnifiedStream(params, callback, 0);
73 }
74
75 AudioOutputDevice::~AudioOutputDevice() {
76   // The current design requires that the user calls Stop() before deleting
77   // this class.
78   DCHECK(audio_thread_.IsStopped());
79 }
80
81 void AudioOutputDevice::Start() {
82   DCHECK(callback_) << "Initialize hasn't been called";
83   task_runner()->PostTask(FROM_HERE,
84       base::Bind(&AudioOutputDevice::CreateStreamOnIOThread, this,
85                  audio_parameters_));
86 }
87
88 void AudioOutputDevice::Stop() {
89   {
90     base::AutoLock auto_lock(audio_thread_lock_);
91     audio_thread_.Stop(base::MessageLoop::current());
92     stopping_hack_ = true;
93   }
94
95   task_runner()->PostTask(FROM_HERE,
96       base::Bind(&AudioOutputDevice::ShutDownOnIOThread, this));
97 }
98
99 void AudioOutputDevice::Play() {
100   task_runner()->PostTask(FROM_HERE,
101       base::Bind(&AudioOutputDevice::PlayOnIOThread, this));
102 }
103
104 void AudioOutputDevice::Pause() {
105   task_runner()->PostTask(FROM_HERE,
106       base::Bind(&AudioOutputDevice::PauseOnIOThread, this));
107 }
108
109 bool AudioOutputDevice::SetVolume(double volume) {
110   if (volume < 0 || volume > 1.0)
111     return false;
112
113   if (!task_runner()->PostTask(FROM_HERE,
114           base::Bind(&AudioOutputDevice::SetVolumeOnIOThread, this, volume))) {
115     return false;
116   }
117
118   return true;
119 }
120
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_);
126   }
127 }
128
129 void AudioOutputDevice::PlayOnIOThread() {
130   DCHECK(task_runner()->BelongsToCurrentThread());
131   if (state_ == PAUSED) {
132     ipc_->PlayStream();
133     state_ = PLAYING;
134     play_on_start_ = false;
135   } else {
136     play_on_start_ = true;
137   }
138 }
139
140 void AudioOutputDevice::PauseOnIOThread() {
141   DCHECK(task_runner()->BelongsToCurrentThread());
142   if (state_ == PLAYING) {
143     ipc_->PauseStream();
144     state_ = PAUSED;
145   }
146   play_on_start_ = false;
147 }
148
149 void AudioOutputDevice::ShutDownOnIOThread() {
150   DCHECK(task_runner()->BelongsToCurrentThread());
151
152   // Close the stream, if we haven't already.
153   if (state_ >= CREATING_STREAM) {
154     ipc_->CloseStream();
155     state_ = IDLE;
156   }
157
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.
162   //
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;
171 }
172
173 void AudioOutputDevice::SetVolumeOnIOThread(double volume) {
174   DCHECK(task_runner()->BelongsToCurrentThread());
175   if (state_ >= CREATING_STREAM)
176     ipc_->SetVolume(volume);
177 }
178
179 void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) {
180   DCHECK(task_runner()->BelongsToCurrentThread());
181
182   // Do nothing if the stream has been closed.
183   if (state_ < CREATING_STREAM)
184     return;
185
186   // TODO(miu): Clean-up inconsistent and incomplete handling here.
187   // http://crbug.com/180640
188   switch (state) {
189     case AudioOutputIPCDelegate::kPlaying:
190     case AudioOutputIPCDelegate::kPaused:
191       break;
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();
202       break;
203     default:
204       NOTREACHED();
205       break;
206   }
207 }
208
209 void AudioOutputDevice::OnStreamCreated(
210     base::SharedMemoryHandle handle,
211     base::SyncSocket::Handle socket_handle,
212     int length) {
213   DCHECK(task_runner()->BelongsToCurrentThread());
214 #if defined(OS_WIN)
215   DCHECK(handle);
216   DCHECK(socket_handle);
217 #else
218   DCHECK_GE(handle.fd, 0);
219   DCHECK_GE(socket_handle, 0);
220 #endif
221   DCHECK_GT(length, 0);
222
223   if (state_ != CREATING_STREAM)
224     return;
225
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.
230   //
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
237   // details.
238   base::AutoLock auto_lock(audio_thread_lock_);
239   if (stopping_hack_)
240     return;
241
242   DCHECK(audio_thread_.IsStopped());
243   audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback(
244       audio_parameters_, handle, length, callback_));
245   audio_thread_.Start(
246       audio_callback_.get(), socket_handle, "AudioOutputDevice", true);
247   state_ = PAUSED;
248
249   // We handle the case where Play() and/or Pause() may have been called
250   // multiple times before OnStreamCreated() gets called.
251   if (play_on_start_)
252     PlayOnIOThread();
253 }
254
255 void AudioOutputDevice::OnIPCClosed() {
256   DCHECK(task_runner()->BelongsToCurrentThread());
257   state_ = IPC_CLOSED;
258   ipc_.reset();
259 }
260
261 void AudioOutputDevice::WillDestroyCurrentMessageLoop() {
262   LOG(ERROR) << "IO loop going away before the audio device has been stopped";
263   ShutDownOnIOThread();
264 }
265
266 // AudioOutputDevice::AudioThreadCallback
267
268 AudioOutputDevice::AudioThreadCallback::AudioThreadCallback(
269     const AudioParameters& audio_parameters,
270     base::SharedMemoryHandle memory,
271     int memory_length,
272     AudioRendererSink::RenderCallback* render_callback)
273     : AudioDeviceThread::Callback(audio_parameters, memory, memory_length, 1),
274       render_callback_(render_callback) {}
275
276 AudioOutputDevice::AudioThreadCallback::~AudioThreadCallback() {
277 }
278
279 void AudioOutputDevice::AudioThreadCallback::MapSharedMemory() {
280   CHECK_EQ(total_segments_, 1);
281   CHECK(shared_memory_.Map(memory_length_));
282
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);
288
289   int io_size = output_memory_size + input_memory_size;
290
291   DCHECK_EQ(memory_length_, io_size);
292
293   output_bus_ =
294       AudioBus::WrapMemory(audio_parameters_, shared_memory_.memory());
295
296   if (input_channels > 0) {
297     // The input data is after the output data.
298     char* input_data =
299         static_cast<char*>(shared_memory_.memory()) + output_memory_size;
300     input_bus_ = AudioBus::WrapMemory(input_channels, frames, input_data);
301   }
302 }
303
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)
308     return;
309
310   // Convert the number of pending bytes in the render buffer into milliseconds.
311   int audio_delay_milliseconds = pending_data / bytes_per_ms_;
312
313   TRACE_EVENT0("audio", "AudioOutputDevice::FireRenderCallback");
314
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);
322   } else {
323     render_callback_->Render(output_bus_.get(), audio_delay_milliseconds);
324   }
325 }
326
327 }  // namespace media.