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"
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"
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
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
{
28 AudioThreadCallback(const AudioParameters
& audio_parameters
,
29 base::SharedMemoryHandle memory
,
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
;
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
),
56 agc_is_enabled_(false),
57 stopping_hack_(false) {
60 // The correctness of the code depends on the relative values assigned in the
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
,
70 DCHECK(params
.IsValid());
72 DCHECK_EQ(0, session_id_
);
73 audio_parameters_
= params
;
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() {
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";
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
,
115 void AudioInputDevice::OnStreamCreated(
116 base::SharedMemoryHandle handle
,
117 base::SyncSocket::Handle socket_handle
,
119 int total_segments
) {
120 DCHECK(task_runner()->BelongsToCurrentThread());
121 DCHECK(base::SharedMemory::IsHandleValid(handle
));
123 DCHECK(socket_handle
);
125 DCHECK_GE(socket_handle
, 0);
127 DCHECK_GT(length
, 0);
129 if (state_
!= CREATING_STREAM
)
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).
139 DCHECK(audio_thread_
.IsStopped());
140 audio_callback_
.reset(new AudioInputDevice::AudioThreadCallback(
141 audio_parameters_
, handle
, length
, total_segments
, callback_
));
143 audio_callback_
.get(), socket_handle
, "AudioInputDevice", false);
146 ipc_
->RecordStream();
149 void AudioInputDevice::OnVolume(double volume
) {
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
)
161 // TODO(miu): Clean-up inconsistent and incomplete handling here.
162 // http://crbug.com/180640
164 case AudioInputIPCDelegate::kStopped
:
165 ShutDownOnIOThread();
167 case AudioInputIPCDelegate::kRecording
:
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();
187 void AudioInputDevice::OnIPCClosed() {
188 DCHECK(task_runner()->BelongsToCurrentThread());
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.
206 if (session_id_
<= 0) {
207 DLOG(WARNING
) << "Invalid session id for the input stream " << session_id_
;
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
) {
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.";
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
,
271 CaptureCallback
* capture_callback
)
272 : AudioDeviceThread::Callback(audio_parameters
, memory
, memory_length
,
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;