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/android/opensles_input.h"
7 #include "base/debug/trace_event.h"
8 #include "base/logging.h"
9 #include "media/audio/android/audio_manager_android.h"
11 #define LOG_ON_FAILURE_AND_RETURN(op, ...) \
13 SLresult err = (op); \
14 if (err != SL_RESULT_SUCCESS) { \
15 DLOG(ERROR) << #op << " failed: " << err; \
22 OpenSLESInputStream::OpenSLESInputStream(AudioManagerAndroid
* audio_manager
,
23 const AudioParameters
& params
)
24 : audio_manager_(audio_manager
),
27 simple_buffer_queue_(NULL
),
28 active_buffer_index_(0),
29 buffer_size_bytes_(0),
31 DVLOG(2) << __PRETTY_FUNCTION__
;
32 format_
.formatType
= SL_DATAFORMAT_PCM
;
33 format_
.numChannels
= static_cast<SLuint32
>(params
.channels());
34 // Provides sampling rate in milliHertz to OpenSLES.
35 format_
.samplesPerSec
= static_cast<SLuint32
>(params
.sample_rate() * 1000);
36 format_
.bitsPerSample
= params
.bits_per_sample();
37 format_
.containerSize
= params
.bits_per_sample();
38 format_
.endianness
= SL_BYTEORDER_LITTLEENDIAN
;
39 if (format_
.numChannels
== 1)
40 format_
.channelMask
= SL_SPEAKER_FRONT_CENTER
;
41 else if (format_
.numChannels
== 2)
42 format_
.channelMask
= SL_SPEAKER_FRONT_LEFT
| SL_SPEAKER_FRONT_RIGHT
;
44 NOTREACHED() << "Unsupported number of channels: " << format_
.numChannels
;
46 buffer_size_bytes_
= params
.GetBytesPerBuffer();
48 memset(&audio_data_
, 0, sizeof(audio_data_
));
51 OpenSLESInputStream::~OpenSLESInputStream() {
52 DVLOG(2) << __PRETTY_FUNCTION__
;
53 DCHECK(thread_checker_
.CalledOnValidThread());
54 DCHECK(!recorder_object_
.Get());
55 DCHECK(!engine_object_
.Get());
57 DCHECK(!simple_buffer_queue_
);
58 DCHECK(!audio_data_
[0]);
61 bool OpenSLESInputStream::Open() {
62 DVLOG(2) << __PRETTY_FUNCTION__
;
63 DCHECK(thread_checker_
.CalledOnValidThread());
64 if (engine_object_
.Get())
67 if (!CreateRecorder())
75 void OpenSLESInputStream::Start(AudioInputCallback
* callback
) {
76 DVLOG(2) << __PRETTY_FUNCTION__
;
77 DCHECK(thread_checker_
.CalledOnValidThread());
80 DCHECK(simple_buffer_queue_
);
84 base::AutoLock
lock(lock_
);
85 DCHECK(callback_
== NULL
|| callback_
== callback
);
87 active_buffer_index_
= 0;
89 // Enqueues kMaxNumOfBuffersInQueue zero buffers to get the ball rolling.
90 // TODO(henrika): add support for Start/Stop/Start sequences when we are
91 // able to clear the buffer queue. There is currently a bug in the OpenSLES
92 // implementation which forces us to always call Stop() and Close() before
93 // calling Start() again.
94 SLresult err
= SL_RESULT_UNKNOWN_ERROR
;
95 for (int i
= 0; i
< kMaxNumOfBuffersInQueue
; ++i
) {
96 err
= (*simple_buffer_queue_
)->Enqueue(
97 simple_buffer_queue_
, audio_data_
[i
], buffer_size_bytes_
);
98 if (SL_RESULT_SUCCESS
!= err
) {
105 // Start the recording by setting the state to SL_RECORDSTATE_RECORDING.
106 // When the object is in the SL_RECORDSTATE_RECORDING state, adding buffers
107 // will implicitly start the filling process.
108 err
= (*recorder_
)->SetRecordState(recorder_
, SL_RECORDSTATE_RECORDING
);
109 if (SL_RESULT_SUCCESS
!= err
) {
118 void OpenSLESInputStream::Stop() {
119 DVLOG(2) << __PRETTY_FUNCTION__
;
120 DCHECK(thread_checker_
.CalledOnValidThread());
124 base::AutoLock
lock(lock_
);
126 // Stop recording by setting the record state to SL_RECORDSTATE_STOPPED.
127 LOG_ON_FAILURE_AND_RETURN(
128 (*recorder_
)->SetRecordState(recorder_
, SL_RECORDSTATE_STOPPED
));
130 // Clear the buffer queue to get rid of old data when resuming recording.
131 LOG_ON_FAILURE_AND_RETURN(
132 (*simple_buffer_queue_
)->Clear(simple_buffer_queue_
));
138 void OpenSLESInputStream::Close() {
139 DVLOG(2) << __PRETTY_FUNCTION__
;
140 DCHECK(thread_checker_
.CalledOnValidThread());
142 // Stop the stream if it is still recording.
145 // TODO(henrika): Do we need to hold the lock here?
146 base::AutoLock
lock(lock_
);
148 // Destroy the buffer queue recorder object and invalidate all associated
150 recorder_object_
.Reset();
151 simple_buffer_queue_
= NULL
;
154 // Destroy the engine object. We don't store any associated interface for
156 engine_object_
.Reset();
157 ReleaseAudioBuffer();
160 audio_manager_
->ReleaseInputStream(this);
163 double OpenSLESInputStream::GetMaxVolume() {
168 void OpenSLESInputStream::SetVolume(double volume
) {
172 double OpenSLESInputStream::GetVolume() {
177 void OpenSLESInputStream::SetAutomaticGainControl(bool enabled
) {
181 bool OpenSLESInputStream::GetAutomaticGainControl() {
186 bool OpenSLESInputStream::CreateRecorder() {
187 DCHECK(thread_checker_
.CalledOnValidThread());
188 DCHECK(!engine_object_
.Get());
189 DCHECK(!recorder_object_
.Get());
191 DCHECK(!simple_buffer_queue_
);
193 // Initializes the engine object with specific option. After working with the
194 // object, we need to free the object and its resources.
195 SLEngineOption option
[] = {
196 {SL_ENGINEOPTION_THREADSAFE
, static_cast<SLuint32
>(SL_BOOLEAN_TRUE
)}};
197 LOG_ON_FAILURE_AND_RETURN(
198 slCreateEngine(engine_object_
.Receive(), 1, option
, 0, NULL
, NULL
),
201 // Realize the SL engine object in synchronous mode.
202 LOG_ON_FAILURE_AND_RETURN(
203 engine_object_
->Realize(engine_object_
.Get(), SL_BOOLEAN_FALSE
), false);
205 // Get the SL engine interface which is implicit.
207 LOG_ON_FAILURE_AND_RETURN(engine_object_
->GetInterface(
208 engine_object_
.Get(), SL_IID_ENGINE
, &engine
),
211 // Audio source configuration.
212 SLDataLocator_IODevice mic_locator
= {
213 SL_DATALOCATOR_IODEVICE
, SL_IODEVICE_AUDIOINPUT
,
214 SL_DEFAULTDEVICEID_AUDIOINPUT
, NULL
};
215 SLDataSource audio_source
= {&mic_locator
, NULL
};
217 // Audio sink configuration.
218 SLDataLocator_AndroidSimpleBufferQueue buffer_queue
= {
219 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE
,
220 static_cast<SLuint32
>(kMaxNumOfBuffersInQueue
)};
221 SLDataSink audio_sink
= {&buffer_queue
, &format_
};
223 // Create an audio recorder.
224 const SLInterfaceID interface_id
[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE
,
225 SL_IID_ANDROIDCONFIGURATION
};
226 const SLboolean interface_required
[] = {SL_BOOLEAN_TRUE
, SL_BOOLEAN_TRUE
};
228 // Create AudioRecorder and specify SL_IID_ANDROIDCONFIGURATION.
229 LOG_ON_FAILURE_AND_RETURN(
230 (*engine
)->CreateAudioRecorder(engine
,
231 recorder_object_
.Receive(),
234 arraysize(interface_id
),
239 SLAndroidConfigurationItf recorder_config
;
240 LOG_ON_FAILURE_AND_RETURN(
241 recorder_object_
->GetInterface(recorder_object_
.Get(),
242 SL_IID_ANDROIDCONFIGURATION
,
246 // Uses the main microphone tuned for audio communications.
247 SLint32 stream_type
= SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION
;
248 LOG_ON_FAILURE_AND_RETURN(
249 (*recorder_config
)->SetConfiguration(recorder_config
,
250 SL_ANDROID_KEY_RECORDING_PRESET
,
255 // Realize the recorder object in synchronous mode.
256 LOG_ON_FAILURE_AND_RETURN(
257 recorder_object_
->Realize(recorder_object_
.Get(), SL_BOOLEAN_FALSE
),
260 // Get an implicit recorder interface.
261 LOG_ON_FAILURE_AND_RETURN(
262 recorder_object_
->GetInterface(
263 recorder_object_
.Get(), SL_IID_RECORD
, &recorder_
),
266 // Get the simple buffer queue interface.
267 LOG_ON_FAILURE_AND_RETURN(
268 recorder_object_
->GetInterface(recorder_object_
.Get(),
269 SL_IID_ANDROIDSIMPLEBUFFERQUEUE
,
270 &simple_buffer_queue_
),
273 // Register the input callback for the simple buffer queue.
274 // This callback will be called when receiving new data from the device.
275 LOG_ON_FAILURE_AND_RETURN(
276 (*simple_buffer_queue_
)->RegisterCallback(
277 simple_buffer_queue_
, SimpleBufferQueueCallback
, this),
283 void OpenSLESInputStream::SimpleBufferQueueCallback(
284 SLAndroidSimpleBufferQueueItf buffer_queue
,
286 OpenSLESInputStream
* stream
=
287 reinterpret_cast<OpenSLESInputStream
*>(instance
);
288 stream
->ReadBufferQueue();
291 void OpenSLESInputStream::ReadBufferQueue() {
292 base::AutoLock
lock(lock_
);
296 TRACE_EVENT0("audio", "OpenSLESOutputStream::ReadBufferQueue");
298 // TODO(henrika): Investigate if it is possible to get an accurate
300 callback_
->OnData(this,
301 audio_data_
[active_buffer_index_
],
306 // Done with this buffer. Send it to device for recording.
308 (*simple_buffer_queue_
)->Enqueue(simple_buffer_queue_
,
309 audio_data_
[active_buffer_index_
],
311 if (SL_RESULT_SUCCESS
!= err
)
314 active_buffer_index_
= (active_buffer_index_
+ 1) % kMaxNumOfBuffersInQueue
;
317 void OpenSLESInputStream::SetupAudioBuffer() {
318 DCHECK(thread_checker_
.CalledOnValidThread());
319 DCHECK(!audio_data_
[0]);
320 for (int i
= 0; i
< kMaxNumOfBuffersInQueue
; ++i
) {
321 audio_data_
[i
] = new uint8
[buffer_size_bytes_
];
325 void OpenSLESInputStream::ReleaseAudioBuffer() {
326 DCHECK(thread_checker_
.CalledOnValidThread());
327 if (audio_data_
[0]) {
328 for (int i
= 0; i
< kMaxNumOfBuffersInQueue
; ++i
) {
329 delete[] audio_data_
[i
];
330 audio_data_
[i
] = NULL
;
335 void OpenSLESInputStream::HandleError(SLresult error
) {
336 DLOG(ERROR
) << "OpenSLES Input error " << error
;
338 callback_
->OnError(this);