crazy linker: convert relocation unpacking to Android style.
[chromium-blink-merge.git] / media / audio / audio_input_device.cc
blob0b41b347faf83f81acac035ebef75a1984a85241
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_input_device.h"
7 #include "base/bind.h"
8 #include "base/memory/scoped_vector.h"
9 #include "base/threading/thread_restrictions.h"
10 #include "base/time/time.h"
11 #include "media/audio/audio_manager_base.h"
12 #include "media/base/audio_bus.h"
14 namespace media {
16 // The number of shared memory buffer segments indicated to browser process
17 // in order to avoid data overwriting. This number can be any positive number,
18 // dependent how fast the renderer process can pick up captured data from
19 // shared memory.
20 static const int kRequestedSharedMemoryCount = 10;
22 // Takes care of invoking the capture callback on the audio thread.
23 // An instance of this class is created for each capture stream in
24 // OnLowLatencyCreated().
25 class AudioInputDevice::AudioThreadCallback
26 : public AudioDeviceThread::Callback {
27 public:
28 AudioThreadCallback(const AudioParameters& audio_parameters,
29 base::SharedMemoryHandle memory,
30 int memory_length,
31 int total_segments,
32 CaptureCallback* capture_callback);
33 ~AudioThreadCallback() override;
35 void MapSharedMemory() override;
37 // Called whenever we receive notifications about pending data.
38 void Process(uint32 pending_data) override;
40 private:
41 int current_segment_id_;
42 ScopedVector<media::AudioBus> audio_buses_;
43 CaptureCallback* capture_callback_;
45 DISALLOW_COPY_AND_ASSIGN(AudioThreadCallback);
48 AudioInputDevice::AudioInputDevice(
49 scoped_ptr<AudioInputIPC> ipc,
50 const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner)
51 : ScopedTaskRunnerObserver(io_task_runner),
52 callback_(NULL),
53 ipc_(ipc.Pass()),
54 state_(IDLE),
55 session_id_(0),
56 agc_is_enabled_(false),
57 stopping_hack_(false) {
58 CHECK(ipc_);
60 // The correctness of the code depends on the relative values assigned in the
61 // State enum.
62 static_assert(IPC_CLOSED < IDLE, "invalid enum value assignment 0");
63 static_assert(IDLE < CREATING_STREAM, "invalid enum value assignment 1");
64 static_assert(CREATING_STREAM < RECORDING, "invalid enum value assignment 2");
67 void AudioInputDevice::Initialize(const AudioParameters& params,
68 CaptureCallback* callback,
69 int session_id) {
70 DCHECK(params.IsValid());
71 DCHECK(!callback_);
72 DCHECK_EQ(0, session_id_);
73 audio_parameters_ = params;
74 callback_ = callback;
75 session_id_ = session_id;
78 void AudioInputDevice::Start() {
79 DCHECK(callback_) << "Initialize hasn't been called";
80 DVLOG(1) << "Start()";
81 task_runner()->PostTask(FROM_HERE,
82 base::Bind(&AudioInputDevice::StartUpOnIOThread, this));
85 void AudioInputDevice::Stop() {
86 DVLOG(1) << "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(&AudioInputDevice::ShutDownOnIOThread, this));
98 void AudioInputDevice::SetVolume(double volume) {
99 if (volume < 0 || volume > 1.0) {
100 DLOG(ERROR) << "Invalid volume value specified";
101 return;
104 task_runner()->PostTask(FROM_HERE,
105 base::Bind(&AudioInputDevice::SetVolumeOnIOThread, this, volume));
108 void AudioInputDevice::SetAutomaticGainControl(bool enabled) {
109 DVLOG(1) << "SetAutomaticGainControl(enabled=" << enabled << ")";
110 task_runner()->PostTask(FROM_HERE,
111 base::Bind(&AudioInputDevice::SetAutomaticGainControlOnIOThread,
112 this, enabled));
115 void AudioInputDevice::OnStreamCreated(
116 base::SharedMemoryHandle handle,
117 base::SyncSocket::Handle socket_handle,
118 int length,
119 int total_segments) {
120 DCHECK(task_runner()->BelongsToCurrentThread());
121 DCHECK(base::SharedMemory::IsHandleValid(handle));
122 #if defined(OS_WIN)
123 DCHECK(socket_handle);
124 #else
125 DCHECK_GE(socket_handle, 0);
126 #endif
127 DCHECK_GT(length, 0);
129 if (state_ != CREATING_STREAM)
130 return;
132 base::AutoLock auto_lock(audio_thread_lock_);
133 // TODO(miu): See TODO in OnStreamCreated method for AudioOutputDevice.
134 // Interface changes need to be made; likely, after AudioInputDevice is merged
135 // into AudioOutputDevice (http://crbug.com/179597).
136 if (stopping_hack_)
137 return;
139 DCHECK(audio_thread_.IsStopped());
140 audio_callback_.reset(new AudioInputDevice::AudioThreadCallback(
141 audio_parameters_, handle, length, total_segments, callback_));
142 audio_thread_.Start(
143 audio_callback_.get(), socket_handle, "AudioInputDevice", false);
145 state_ = RECORDING;
146 ipc_->RecordStream();
149 void AudioInputDevice::OnVolume(double volume) {
150 NOTIMPLEMENTED();
153 void AudioInputDevice::OnStateChanged(
154 AudioInputIPCDelegate::State state) {
155 DCHECK(task_runner()->BelongsToCurrentThread());
157 // Do nothing if the stream has been closed.
158 if (state_ < CREATING_STREAM)
159 return;
161 // TODO(miu): Clean-up inconsistent and incomplete handling here.
162 // http://crbug.com/180640
163 switch (state) {
164 case AudioInputIPCDelegate::kStopped:
165 ShutDownOnIOThread();
166 break;
167 case AudioInputIPCDelegate::kRecording:
168 NOTIMPLEMENTED();
169 break;
170 case AudioInputIPCDelegate::kError:
171 DLOG(WARNING) << "AudioInputDevice::OnStateChanged(kError)";
172 // Don't dereference the callback object if the audio thread
173 // is stopped or stopping. That could mean that the callback
174 // object has been deleted.
175 // TODO(tommi): Add an explicit contract for clearing the callback
176 // object. Possibly require calling Initialize again or provide
177 // a callback object via Start() and clear it in Stop().
178 if (!audio_thread_.IsStopped())
179 callback_->OnCaptureError();
180 break;
181 default:
182 NOTREACHED();
183 break;
187 void AudioInputDevice::OnIPCClosed() {
188 DCHECK(task_runner()->BelongsToCurrentThread());
189 state_ = IPC_CLOSED;
190 ipc_.reset();
193 AudioInputDevice::~AudioInputDevice() {
194 // TODO(henrika): The current design requires that the user calls
195 // Stop before deleting this class.
196 DCHECK(audio_thread_.IsStopped());
199 void AudioInputDevice::StartUpOnIOThread() {
200 DCHECK(task_runner()->BelongsToCurrentThread());
202 // Make sure we don't call Start() more than once.
203 if (state_ != IDLE)
204 return;
206 if (session_id_ <= 0) {
207 DLOG(WARNING) << "Invalid session id for the input stream " << session_id_;
208 return;
211 state_ = CREATING_STREAM;
212 ipc_->CreateStream(this, session_id_, audio_parameters_,
213 agc_is_enabled_, kRequestedSharedMemoryCount);
216 void AudioInputDevice::ShutDownOnIOThread() {
217 DCHECK(task_runner()->BelongsToCurrentThread());
219 // Close the stream, if we haven't already.
220 if (state_ >= CREATING_STREAM) {
221 ipc_->CloseStream();
222 state_ = IDLE;
223 agc_is_enabled_ = false;
226 // We can run into an issue where ShutDownOnIOThread is called right after
227 // OnStreamCreated is called in cases where Start/Stop are called before we
228 // get the OnStreamCreated callback. To handle that corner case, we call
229 // Stop(). In most cases, the thread will already be stopped.
231 // Another situation is when the IO thread goes away before Stop() is called
232 // in which case, we cannot use the message loop to close the thread handle
233 // and can't not rely on the main thread existing either.
234 base::AutoLock auto_lock_(audio_thread_lock_);
235 base::ThreadRestrictions::ScopedAllowIO allow_io;
236 audio_thread_.Stop(NULL);
237 audio_callback_.reset();
238 stopping_hack_ = false;
241 void AudioInputDevice::SetVolumeOnIOThread(double volume) {
242 DCHECK(task_runner()->BelongsToCurrentThread());
243 if (state_ >= CREATING_STREAM)
244 ipc_->SetVolume(volume);
247 void AudioInputDevice::SetAutomaticGainControlOnIOThread(bool enabled) {
248 DCHECK(task_runner()->BelongsToCurrentThread());
250 if (state_ >= CREATING_STREAM) {
251 DLOG(WARNING) << "The AGC state can not be modified after starting.";
252 return;
255 // We simply store the new AGC setting here. This value will be used when
256 // a new stream is initialized and by GetAutomaticGainControl().
257 agc_is_enabled_ = enabled;
260 void AudioInputDevice::WillDestroyCurrentMessageLoop() {
261 LOG(ERROR) << "IO loop going away before the input device has been stopped";
262 ShutDownOnIOThread();
265 // AudioInputDevice::AudioThreadCallback
266 AudioInputDevice::AudioThreadCallback::AudioThreadCallback(
267 const AudioParameters& audio_parameters,
268 base::SharedMemoryHandle memory,
269 int memory_length,
270 int total_segments,
271 CaptureCallback* capture_callback)
272 : AudioDeviceThread::Callback(audio_parameters, memory, memory_length,
273 total_segments),
274 current_segment_id_(0),
275 capture_callback_(capture_callback) {
278 AudioInputDevice::AudioThreadCallback::~AudioThreadCallback() {
281 void AudioInputDevice::AudioThreadCallback::MapSharedMemory() {
282 shared_memory_.Map(memory_length_);
284 // Create vector of audio buses by wrapping existing blocks of memory.
285 uint8* ptr = static_cast<uint8*>(shared_memory_.memory());
286 for (int i = 0; i < total_segments_; ++i) {
287 media::AudioInputBuffer* buffer =
288 reinterpret_cast<media::AudioInputBuffer*>(ptr);
289 scoped_ptr<media::AudioBus> audio_bus =
290 media::AudioBus::WrapMemory(audio_parameters_, buffer->audio);
291 audio_buses_.push_back(audio_bus.Pass());
292 ptr += segment_length_;
296 void AudioInputDevice::AudioThreadCallback::Process(uint32 pending_data) {
297 // The shared memory represents parameters, size of the data buffer and the
298 // actual data buffer containing audio data. Map the memory into this
299 // structure and parse out parameters and the data area.
300 uint8* ptr = static_cast<uint8*>(shared_memory_.memory());
301 ptr += current_segment_id_ * segment_length_;
302 AudioInputBuffer* buffer = reinterpret_cast<AudioInputBuffer*>(ptr);
303 // Usually this will be equal but in the case of low sample rate (e.g. 8kHz,
304 // the buffer may be bigger (on mac at least)).
305 DCHECK_GE(buffer->params.size,
306 segment_length_ - sizeof(AudioInputBufferParameters));
307 double volume = buffer->params.volume;
308 bool key_pressed = buffer->params.key_pressed;
310 // Use pre-allocated audio bus wrapping existing block of shared memory.
311 media::AudioBus* audio_bus = audio_buses_[current_segment_id_];
313 // Deliver captured data to the client in floating point format
314 // and update the audio-delay measurement.
315 int audio_delay_milliseconds = pending_data / bytes_per_ms_;
316 capture_callback_->Capture(
317 audio_bus, audio_delay_milliseconds, volume, key_pressed);
319 if (++current_segment_id_ >= total_segments_)
320 current_segment_id_ = 0;
323 } // namespace media