OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. |
| 3 * |
| 4 * Use of this source code is governed by a BSD-style license |
| 5 * that can be found in the LICENSE file in the root of the source |
| 6 * tree. An additional intellectual property rights grant can be found |
| 7 * in the file PATENTS. All contributing project authors may |
| 8 * be found in the AUTHORS file in the root of the source tree. |
| 9 */ |
| 10 |
| 11 #include "webrtc/modules/audio_device/android/opensles_recorder.h" |
| 12 |
| 13 #include <android/log.h> |
| 14 |
| 15 #include "webrtc/base/arraysize.h" |
| 16 #include "webrtc/base/checks.h" |
| 17 #include "webrtc/base/format_macros.h" |
| 18 #include "webrtc/base/timeutils.h" |
| 19 #include "webrtc/modules/audio_device/android/audio_common.h" |
| 20 #include "webrtc/modules/audio_device/android/audio_manager.h" |
| 21 #include "webrtc/modules/audio_device/fine_audio_buffer.h" |
| 22 |
| 23 #define TAG "OpenSLESRecorder" |
| 24 #define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) |
| 25 #define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) |
| 26 #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) |
| 27 #define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__) |
| 28 #define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) |
| 29 |
| 30 #define LOG_ON_ERROR(op) \ |
| 31 [](SLresult err) { \ |
| 32 if (err != SL_RESULT_SUCCESS) { \ |
| 33 ALOGE("%s:%d %s failed: %s", __FILE__, __LINE__, #op, \ |
| 34 GetSLErrorString(err)); \ |
| 35 return true; \ |
| 36 } \ |
| 37 return false; \ |
| 38 }(op) |
| 39 |
| 40 namespace webrtc { |
| 41 |
| 42 OpenSLESRecorder::OpenSLESRecorder(AudioManager* audio_manager) |
| 43 : audio_manager_(audio_manager), |
| 44 audio_parameters_(audio_manager->GetRecordAudioParameters()), |
| 45 audio_device_buffer_(nullptr), |
| 46 initialized_(false), |
| 47 recording_(false), |
| 48 engine_(nullptr), |
| 49 recorder_(nullptr), |
| 50 simple_buffer_queue_(nullptr), |
| 51 buffer_index_(0), |
| 52 last_rec_time_(0) { |
| 53 ALOGD("ctor%s", GetThreadInfo().c_str()); |
| 54 // Detach from this thread since we want to use the checker to verify calls |
| 55 // from the internal audio thread. |
| 56 thread_checker_opensles_.DetachFromThread(); |
| 57 // Use native audio output parameters provided by the audio manager and |
| 58 // define the PCM format structure. |
| 59 pcm_format_ = CreatePCMConfiguration(audio_parameters_.channels(), |
| 60 audio_parameters_.sample_rate(), |
| 61 audio_parameters_.bits_per_sample()); |
| 62 } |
| 63 |
| 64 OpenSLESRecorder::~OpenSLESRecorder() { |
| 65 ALOGD("dtor%s", GetThreadInfo().c_str()); |
| 66 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 67 Terminate(); |
| 68 DestroyAudioRecorder(); |
| 69 engine_ = nullptr; |
| 70 RTC_DCHECK(!engine_); |
| 71 RTC_DCHECK(!recorder_); |
| 72 RTC_DCHECK(!simple_buffer_queue_); |
| 73 } |
| 74 |
| 75 int OpenSLESRecorder::Init() { |
| 76 ALOGD("Init%s", GetThreadInfo().c_str()); |
| 77 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 78 return 0; |
| 79 } |
| 80 |
| 81 int OpenSLESRecorder::Terminate() { |
| 82 ALOGD("Terminate%s", GetThreadInfo().c_str()); |
| 83 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 84 StopRecording(); |
| 85 return 0; |
| 86 } |
| 87 |
| 88 int OpenSLESRecorder::InitRecording() { |
| 89 ALOGD("InitRecording%s", GetThreadInfo().c_str()); |
| 90 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 91 RTC_DCHECK(!initialized_); |
| 92 RTC_DCHECK(!recording_); |
| 93 if (!ObtainEngineInterface()) { |
| 94 ALOGE("Failed to obtain SL Engine interface"); |
| 95 return -1; |
| 96 } |
| 97 CreateAudioRecorder(); |
| 98 initialized_ = true; |
| 99 buffer_index_ = 0; |
| 100 return 0; |
| 101 } |
| 102 |
| 103 int OpenSLESRecorder::StartRecording() { |
| 104 ALOGD("StartRecording%s", GetThreadInfo().c_str()); |
| 105 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 106 RTC_DCHECK(initialized_); |
| 107 RTC_DCHECK(!recording_); |
| 108 if (fine_audio_buffer_) { |
| 109 fine_audio_buffer_->ResetRecord(); |
| 110 } |
| 111 // Add buffers to the queue before changing state to SL_RECORDSTATE_RECORDING |
| 112 // to ensure that recording starts as soon as the state is modified. On some |
| 113 // devices, SLAndroidSimpleBufferQueue::Clear() used in Stop() does not flush |
| 114 // the buffers as intended and we therefore check the number of buffers |
| 115 // already queued first. Enqueue() can return SL_RESULT_BUFFER_INSUFFICIENT |
| 116 // otherwise. |
| 117 int num_buffers_in_queue = GetBufferCount(); |
| 118 for (int i = 0; i < kNumOfOpenSLESBuffers - num_buffers_in_queue; ++i) { |
| 119 if (!EnqueueAudioBuffer()) { |
| 120 recording_ = false; |
| 121 return -1; |
| 122 } |
| 123 } |
| 124 num_buffers_in_queue = GetBufferCount(); |
| 125 RTC_DCHECK_EQ(num_buffers_in_queue, kNumOfOpenSLESBuffers); |
| 126 LogBufferState(); |
| 127 // Start audio recording by changing the state to SL_RECORDSTATE_RECORDING. |
| 128 // Given that buffers are already enqueued, recording should start at once. |
| 129 // The macro returns -1 if recording fails to start. |
| 130 last_rec_time_ = rtc::Time(); |
| 131 if (LOG_ON_ERROR( |
| 132 (*recorder_)->SetRecordState(recorder_, SL_RECORDSTATE_RECORDING))) { |
| 133 return -1; |
| 134 } |
| 135 recording_ = (GetRecordState() == SL_RECORDSTATE_RECORDING); |
| 136 RTC_DCHECK(recording_); |
| 137 return 0; |
| 138 } |
| 139 |
| 140 int OpenSLESRecorder::StopRecording() { |
| 141 ALOGD("StopRecording%s", GetThreadInfo().c_str()); |
| 142 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 143 if (!initialized_ || !recording_) { |
| 144 return 0; |
| 145 } |
| 146 // Stop recording by setting the record state to SL_RECORDSTATE_STOPPED. |
| 147 if (LOG_ON_ERROR( |
| 148 (*recorder_)->SetRecordState(recorder_, SL_RECORDSTATE_STOPPED))) { |
| 149 return -1; |
| 150 } |
| 151 // Clear the buffer queue to get rid of old data when resuming recording. |
| 152 if (LOG_ON_ERROR((*simple_buffer_queue_)->Clear(simple_buffer_queue_))) { |
| 153 return -1; |
| 154 } |
| 155 thread_checker_opensles_.DetachFromThread(); |
| 156 initialized_ = false; |
| 157 recording_ = false; |
| 158 return 0; |
| 159 } |
| 160 |
| 161 void OpenSLESRecorder::AttachAudioBuffer(AudioDeviceBuffer* audio_buffer) { |
| 162 ALOGD("AttachAudioBuffer"); |
| 163 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 164 RTC_CHECK(audio_buffer); |
| 165 audio_device_buffer_ = audio_buffer; |
| 166 // Ensure that the audio device buffer is informed about the native sample |
| 167 // rate used on the recording side. |
| 168 const int sample_rate_hz = audio_parameters_.sample_rate(); |
| 169 ALOGD("SetRecordingSampleRate(%d)", sample_rate_hz); |
| 170 audio_device_buffer_->SetRecordingSampleRate(sample_rate_hz); |
| 171 // Ensure that the audio device buffer is informed about the number of |
| 172 // channels preferred by the OS on the recording side. |
| 173 const size_t channels = audio_parameters_.channels(); |
| 174 ALOGD("SetRecordingChannels(%" PRIuS ")", channels); |
| 175 audio_device_buffer_->SetRecordingChannels(channels); |
| 176 // Allocated memory for internal data buffers given existing audio parameters. |
| 177 AllocateDataBuffers(); |
| 178 } |
| 179 |
| 180 int OpenSLESRecorder::EnableBuiltInAEC(bool enable) { |
| 181 ALOGD("EnableBuiltInAEC(%d)", enable); |
| 182 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 183 ALOGE("Not implemented"); |
| 184 return 0; |
| 185 } |
| 186 |
| 187 int OpenSLESRecorder::EnableBuiltInAGC(bool enable) { |
| 188 ALOGD("EnableBuiltInAGC(%d)", enable); |
| 189 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 190 ALOGE("Not implemented"); |
| 191 return 0; |
| 192 } |
| 193 |
| 194 int OpenSLESRecorder::EnableBuiltInNS(bool enable) { |
| 195 ALOGD("EnableBuiltInNS(%d)", enable); |
| 196 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 197 ALOGE("Not implemented"); |
| 198 return 0; |
| 199 } |
| 200 |
| 201 bool OpenSLESRecorder::ObtainEngineInterface() { |
| 202 ALOGD("ObtainEngineInterface"); |
| 203 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 204 if (engine_) |
| 205 return true; |
| 206 // Get access to (or create if not already existing) the global OpenSL Engine |
| 207 // object. |
| 208 SLObjectItf engine_object = audio_manager_->GetOpenSLEngine(); |
| 209 if (engine_object == nullptr) { |
| 210 ALOGE("Failed to access the global OpenSL engine"); |
| 211 return false; |
| 212 } |
| 213 // Get the SL Engine Interface which is implicit. |
| 214 if (LOG_ON_ERROR( |
| 215 (*engine_object) |
| 216 ->GetInterface(engine_object, SL_IID_ENGINE, &engine_))) { |
| 217 return false; |
| 218 } |
| 219 return true; |
| 220 } |
| 221 |
| 222 bool OpenSLESRecorder::CreateAudioRecorder() { |
| 223 ALOGD("CreateAudioRecorder"); |
| 224 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 225 if (recorder_object_.Get()) |
| 226 return true; |
| 227 RTC_DCHECK(!recorder_); |
| 228 RTC_DCHECK(!simple_buffer_queue_); |
| 229 |
| 230 // Audio source configuration. |
| 231 SLDataLocator_IODevice mic_locator = {SL_DATALOCATOR_IODEVICE, |
| 232 SL_IODEVICE_AUDIOINPUT, |
| 233 SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; |
| 234 SLDataSource audio_source = {&mic_locator, NULL}; |
| 235 |
| 236 // Audio sink configuration. |
| 237 SLDataLocator_AndroidSimpleBufferQueue buffer_queue = { |
| 238 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, |
| 239 static_cast<SLuint32>(kNumOfOpenSLESBuffers)}; |
| 240 SLDataSink audio_sink = {&buffer_queue, &pcm_format_}; |
| 241 |
| 242 // Create the audio recorder object (requires the RECORD_AUDIO permission). |
| 243 // Do not realize the recorder yet. Set the configuration first. |
| 244 const SLInterfaceID interface_id[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, |
| 245 SL_IID_ANDROIDCONFIGURATION}; |
| 246 const SLboolean interface_required[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; |
| 247 if (LOG_ON_ERROR((*engine_)->CreateAudioRecorder( |
| 248 engine_, recorder_object_.Receive(), &audio_source, &audio_sink, |
| 249 arraysize(interface_id), interface_id, interface_required))) { |
| 250 return false; |
| 251 } |
| 252 |
| 253 // Configure the audio recorder (before it is realized). |
| 254 SLAndroidConfigurationItf recorder_config; |
| 255 if (LOG_ON_ERROR((recorder_object_->GetInterface(recorder_object_.Get(), |
| 256 SL_IID_ANDROIDCONFIGURATION, |
| 257 &recorder_config)))) { |
| 258 return false; |
| 259 } |
| 260 |
| 261 // Uses the default microphone tuned for audio communication. |
| 262 // Note that, SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION leads to a fast |
| 263 // track but also excludes usage of required effects like AEC, AGC and NS. |
| 264 // SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION |
| 265 SLint32 stream_type = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION; |
| 266 if (LOG_ON_ERROR(((*recorder_config) |
| 267 ->SetConfiguration(recorder_config, |
| 268 SL_ANDROID_KEY_RECORDING_PRESET, |
| 269 &stream_type, sizeof(SLint32))))) { |
| 270 return false; |
| 271 } |
| 272 |
| 273 // The audio recorder can now be realized (in synchronous mode). |
| 274 if (LOG_ON_ERROR((recorder_object_->Realize(recorder_object_.Get(), |
| 275 SL_BOOLEAN_FALSE)))) { |
| 276 return false; |
| 277 } |
| 278 |
| 279 // Get the implicit recorder interface (SL_IID_RECORD). |
| 280 if (LOG_ON_ERROR((recorder_object_->GetInterface( |
| 281 recorder_object_.Get(), SL_IID_RECORD, &recorder_)))) { |
| 282 return false; |
| 283 } |
| 284 |
| 285 // Get the simple buffer queue interface (SL_IID_ANDROIDSIMPLEBUFFERQUEUE). |
| 286 // It was explicitly requested. |
| 287 if (LOG_ON_ERROR((recorder_object_->GetInterface( |
| 288 recorder_object_.Get(), SL_IID_ANDROIDSIMPLEBUFFERQUEUE, |
| 289 &simple_buffer_queue_)))) { |
| 290 return false; |
| 291 } |
| 292 |
| 293 // Register the input callback for the simple buffer queue. |
| 294 // This callback will be called when receiving new data from the device. |
| 295 if (LOG_ON_ERROR(((*simple_buffer_queue_) |
| 296 ->RegisterCallback(simple_buffer_queue_, |
| 297 SimpleBufferQueueCallback, this)))) { |
| 298 return false; |
| 299 } |
| 300 return true; |
| 301 } |
| 302 |
| 303 void OpenSLESRecorder::DestroyAudioRecorder() { |
| 304 ALOGD("DestroyAudioRecorder"); |
| 305 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 306 if (!recorder_object_.Get()) |
| 307 return; |
| 308 (*simple_buffer_queue_) |
| 309 ->RegisterCallback(simple_buffer_queue_, nullptr, nullptr); |
| 310 recorder_object_.Reset(); |
| 311 recorder_ = nullptr; |
| 312 simple_buffer_queue_ = nullptr; |
| 313 } |
| 314 |
| 315 void OpenSLESRecorder::SimpleBufferQueueCallback( |
| 316 SLAndroidSimpleBufferQueueItf buffer_queue, |
| 317 void* context) { |
| 318 OpenSLESRecorder* stream = static_cast<OpenSLESRecorder*>(context); |
| 319 stream->ReadBufferQueue(); |
| 320 } |
| 321 |
| 322 void OpenSLESRecorder::AllocateDataBuffers() { |
| 323 ALOGD("AllocateDataBuffers"); |
| 324 RTC_DCHECK(thread_checker_.CalledOnValidThread()); |
| 325 RTC_DCHECK(!simple_buffer_queue_); |
| 326 RTC_CHECK(audio_device_buffer_); |
| 327 // Create a modified audio buffer class which allows us to deliver any number |
| 328 // of samples (and not only multiple of 10ms) to match the native audio unit |
| 329 // buffer size. |
| 330 ALOGD("frames per native buffer: %" PRIuS, |
| 331 audio_parameters_.frames_per_buffer()); |
| 332 ALOGD("frames per 10ms buffer: %" PRIuS, |
| 333 audio_parameters_.frames_per_10ms_buffer()); |
| 334 ALOGD("bytes per native buffer: %" PRIuS, |
| 335 audio_parameters_.GetBytesPerBuffer()); |
| 336 ALOGD("native sample rate: %d", audio_parameters_.sample_rate()); |
| 337 RTC_DCHECK(audio_device_buffer_); |
| 338 fine_audio_buffer_.reset(new FineAudioBuffer( |
| 339 audio_device_buffer_, audio_parameters_.GetBytesPerBuffer(), |
| 340 audio_parameters_.sample_rate())); |
| 341 // Allocate queue of audio buffers that stores recorded audio samples. |
| 342 const int data_size_bytes = audio_parameters_.GetBytesPerBuffer(); |
| 343 audio_buffers_.reset(new std::unique_ptr<SLint8[]>[kNumOfOpenSLESBuffers]); |
| 344 for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) { |
| 345 audio_buffers_[i].reset(new SLint8[data_size_bytes]); |
| 346 } |
| 347 } |
| 348 |
| 349 void OpenSLESRecorder::ReadBufferQueue() { |
| 350 RTC_DCHECK(thread_checker_opensles_.CalledOnValidThread()); |
| 351 SLuint32 state = GetRecordState(); |
| 352 if (state != SL_RECORDSTATE_RECORDING) { |
| 353 ALOGW("Buffer callback in non-recording state!"); |
| 354 return; |
| 355 } |
| 356 // Check delta time between two successive callbacks and provide a warning |
| 357 // if it becomes very large. |
| 358 // TODO(henrika): using 150ms as upper limit but this value is rather random. |
| 359 const uint32_t current_time = rtc::Time(); |
| 360 const uint32_t diff = current_time - last_rec_time_; |
| 361 if (diff > 150) { |
| 362 ALOGW("Bad OpenSL ES record timing, dT=%u [ms]", diff); |
| 363 } |
| 364 last_rec_time_ = current_time; |
| 365 // Send recorded audio data to the WebRTC sink. |
| 366 // TODO(henrika): fix delay estimates. It is OK to use fixed values for now |
| 367 // since there is no support to turn off built-in EC in combination with |
| 368 // OpenSL ES anyhow. Hence, as is, the WebRTC based AEC (which would use |
| 369 // these estimates) will never be active. |
| 370 const size_t size_in_bytes = |
| 371 static_cast<size_t>(audio_parameters_.GetBytesPerBuffer()); |
| 372 const int8_t* data = |
| 373 static_cast<const int8_t*>(audio_buffers_[buffer_index_].get()); |
| 374 fine_audio_buffer_->DeliverRecordedData(data, size_in_bytes, 25, 25); |
| 375 // Enqueue the utilized audio buffer and use if for recording again. |
| 376 EnqueueAudioBuffer(); |
| 377 } |
| 378 |
| 379 bool OpenSLESRecorder::EnqueueAudioBuffer() { |
| 380 SLresult err = |
| 381 (*simple_buffer_queue_) |
| 382 ->Enqueue(simple_buffer_queue_, audio_buffers_[buffer_index_].get(), |
| 383 audio_parameters_.GetBytesPerBuffer()); |
| 384 if (SL_RESULT_SUCCESS != err) { |
| 385 ALOGE("Enqueue failed: %s", GetSLErrorString(err)); |
| 386 return false; |
| 387 } |
| 388 buffer_index_ = (buffer_index_ + 1) % kNumOfOpenSLESBuffers; |
| 389 return true; |
| 390 } |
| 391 |
| 392 SLuint32 OpenSLESRecorder::GetRecordState() const { |
| 393 RTC_DCHECK(recorder_); |
| 394 SLuint32 state; |
| 395 SLresult err = (*recorder_)->GetRecordState(recorder_, &state); |
| 396 if (SL_RESULT_SUCCESS != err) { |
| 397 ALOGE("GetRecordState failed: %s", GetSLErrorString(err)); |
| 398 } |
| 399 return state; |
| 400 } |
| 401 |
| 402 SLAndroidSimpleBufferQueueState OpenSLESRecorder::GetBufferQueueState() const { |
| 403 RTC_DCHECK(simple_buffer_queue_); |
| 404 // state.count: Number of buffers currently in the queue. |
| 405 // state.index: Index of the currently filling buffer. This is a linear index |
| 406 // that keeps a cumulative count of the number of buffers recorded. |
| 407 SLAndroidSimpleBufferQueueState state; |
| 408 SLresult err = |
| 409 (*simple_buffer_queue_)->GetState(simple_buffer_queue_, &state); |
| 410 if (SL_RESULT_SUCCESS != err) { |
| 411 ALOGE("GetState failed: %s", GetSLErrorString(err)); |
| 412 } |
| 413 return state; |
| 414 } |
| 415 |
| 416 void OpenSLESRecorder::LogBufferState() const { |
| 417 SLAndroidSimpleBufferQueueState state = GetBufferQueueState(); |
| 418 ALOGD("state.count:%d state.index:%d", state.count, state.index); |
| 419 } |
| 420 |
| 421 SLuint32 OpenSLESRecorder::GetBufferCount() { |
| 422 SLAndroidSimpleBufferQueueState state = GetBufferQueueState(); |
| 423 return state.count; |
| 424 } |
| 425 |
| 426 } // namespace webrtc |
OLD | NEW |