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