summaryrefslogtreecommitdiff
path: root/chromium/media/audio/android/opensles_input.cc
blob: 15c3eac3726389bb7f8d0a7f37ee4b8d35a82f91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/android/opensles_input.h"

#include "base/logging.h"
#include "media/audio/android/audio_manager_android.h"

#define LOG_ON_FAILURE_AND_RETURN(op, ...) \
  do { \
    SLresult err = (op);            \
    if (err != SL_RESULT_SUCCESS) { \
      DLOG(ERROR) << #op << " failed: " << err; \
      return __VA_ARGS__; \
    } \
  } while (0)

namespace media {

OpenSLESInputStream::OpenSLESInputStream(AudioManagerAndroid* audio_manager,
                                         const AudioParameters& params)
    : audio_manager_(audio_manager),
      callback_(NULL),
      recorder_(NULL),
      simple_buffer_queue_(NULL),
      active_queue_(0),
      buffer_size_bytes_(0),
      started_(false) {
  format_.formatType = SL_DATAFORMAT_PCM;
  format_.numChannels = static_cast<SLuint32>(params.channels());
  // Provides sampling rate in milliHertz to OpenSLES.
  format_.samplesPerSec = static_cast<SLuint32>(params.sample_rate() * 1000);
  format_.bitsPerSample = params.bits_per_sample();
  format_.containerSize = params.bits_per_sample();
  format_.endianness = SL_BYTEORDER_LITTLEENDIAN;
  if (format_.numChannels == 1)
    format_.channelMask = SL_SPEAKER_FRONT_CENTER;
  else if (format_.numChannels == 2)
    format_.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  else
    NOTREACHED() << "Unsupported number of channels: " << format_.numChannels;

  buffer_size_bytes_ = params.GetBytesPerBuffer();

  memset(&audio_data_, 0, sizeof(audio_data_));
}

OpenSLESInputStream::~OpenSLESInputStream() {
  DCHECK(!recorder_object_.Get());
  DCHECK(!engine_object_.Get());
  DCHECK(!recorder_);
  DCHECK(!simple_buffer_queue_);
  DCHECK(!audio_data_[0]);
}

bool OpenSLESInputStream::Open() {
  if (engine_object_.Get())
    return false;

  if (!CreateRecorder())
    return false;

  SetupAudioBuffer();

  return true;
}

void OpenSLESInputStream::Start(AudioInputCallback* callback) {
  DCHECK(callback);
  DCHECK(recorder_);
  DCHECK(simple_buffer_queue_);
  if (started_)
    return;

  // Enable the flags before streaming.
  callback_ = callback;
  active_queue_ = 0;
  started_ = true;

  SLresult err = SL_RESULT_UNKNOWN_ERROR;
  // Enqueues |kNumOfQueuesInBuffer| zero buffers to get the ball rolling.
  for (int i = 0; i < kNumOfQueuesInBuffer; ++i) {
    err = (*simple_buffer_queue_)->Enqueue(
        simple_buffer_queue_,
        audio_data_[i],
        buffer_size_bytes_);
    if (SL_RESULT_SUCCESS != err) {
      HandleError(err);
      return;
    }
  }

  // Start the recording by setting the state to |SL_RECORDSTATE_RECORDING|.
  err = (*recorder_)->SetRecordState(recorder_, SL_RECORDSTATE_RECORDING);
  if (SL_RESULT_SUCCESS != err)
    HandleError(err);
}

void OpenSLESInputStream::Stop() {
  if (!started_)
    return;

  // Stop recording by setting the record state to |SL_RECORDSTATE_STOPPED|.
  LOG_ON_FAILURE_AND_RETURN(
      (*recorder_)->SetRecordState(recorder_,
                                   SL_RECORDSTATE_STOPPED));

  // Clear the buffer queue to get rid of old data when resuming recording.
  LOG_ON_FAILURE_AND_RETURN(
      (*simple_buffer_queue_)->Clear(simple_buffer_queue_));

  started_ = false;
}

void OpenSLESInputStream::Close() {
  // Stop the stream if it is still recording.
  Stop();

  // Explicitly free the player objects and invalidate their associated
  // interfaces. They have to be done in the correct order.
  recorder_object_.Reset();
  engine_object_.Reset();
  simple_buffer_queue_ = NULL;
  recorder_ = NULL;

  ReleaseAudioBuffer();

  audio_manager_->ReleaseInputStream(this);
}

double OpenSLESInputStream::GetMaxVolume() {
  NOTIMPLEMENTED();
  return 0.0;
}

void OpenSLESInputStream::SetVolume(double volume) {
  NOTIMPLEMENTED();
}

double OpenSLESInputStream::GetVolume() {
  NOTIMPLEMENTED();
  return 0.0;
}

void OpenSLESInputStream::SetAutomaticGainControl(bool enabled) {
  NOTIMPLEMENTED();
}

bool OpenSLESInputStream::GetAutomaticGainControl() {
  NOTIMPLEMENTED();
  return false;
}

bool OpenSLESInputStream::CreateRecorder() {
  // Initializes the engine object with specific option. After working with the
  // object, we need to free the object and its resources.
  SLEngineOption option[] = {
    { SL_ENGINEOPTION_THREADSAFE, static_cast<SLuint32>(SL_BOOLEAN_TRUE) }
  };
  LOG_ON_FAILURE_AND_RETURN(slCreateEngine(engine_object_.Receive(),
                                           1,
                                           option,
                                           0,
                                           NULL,
                                           NULL),
                            false);

  // Realize the SL engine object in synchronous mode.
  LOG_ON_FAILURE_AND_RETURN(engine_object_->Realize(engine_object_.Get(),
                                                    SL_BOOLEAN_FALSE),
                            false);

  // Get the SL engine interface which is implicit.
  SLEngineItf engine;
  LOG_ON_FAILURE_AND_RETURN(engine_object_->GetInterface(engine_object_.Get(),
                                                         SL_IID_ENGINE,
                                                         &engine),
                            false);

  // Audio source configuration.
  SLDataLocator_IODevice mic_locator = {
    SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT,
    SL_DEFAULTDEVICEID_AUDIOINPUT, NULL
  };
  SLDataSource audio_source = { &mic_locator, NULL };

  // Audio sink configuration.
  SLDataLocator_AndroidSimpleBufferQueue buffer_queue = {
    SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,  // Locator type.
    static_cast<SLuint32>(kNumOfQueuesInBuffer)  // Number of buffers.
  };
  SLDataSink audio_sink = { &buffer_queue, &format_ };

  // Create an audio recorder.
  const SLInterfaceID interface_id[] = {
    SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
    SL_IID_ANDROIDCONFIGURATION
  };
  const SLboolean interface_required[] = {
    SL_BOOLEAN_TRUE,
    SL_BOOLEAN_TRUE
  };
  // Create AudioRecorder and specify SL_IID_ANDROIDCONFIGURATION.
  LOG_ON_FAILURE_AND_RETURN(
      (*engine)->CreateAudioRecorder(engine,
                                     recorder_object_.Receive(),
                                     &audio_source,
                                     &audio_sink,
                                     arraysize(interface_id),
                                     interface_id,
                                     interface_required),
      false);

  SLAndroidConfigurationItf recorder_config;
  LOG_ON_FAILURE_AND_RETURN(
      recorder_object_->GetInterface(recorder_object_.Get(),
                                     SL_IID_ANDROIDCONFIGURATION,
                                     &recorder_config),
      false);

  SLint32 stream_type = SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION;
  LOG_ON_FAILURE_AND_RETURN(
      (*recorder_config)->SetConfiguration(recorder_config,
                                           SL_ANDROID_KEY_RECORDING_PRESET,
                                           &stream_type, sizeof(SLint32)),
      false);

  // Realize the recorder object in synchronous mode.
  LOG_ON_FAILURE_AND_RETURN(
      recorder_object_->Realize(recorder_object_.Get(),
                                SL_BOOLEAN_FALSE),
      false);

  // Get an implicit recorder interface.
  LOG_ON_FAILURE_AND_RETURN(
      recorder_object_->GetInterface(recorder_object_.Get(),
                                     SL_IID_RECORD,
                                     &recorder_),
      false);

  // Get the simple buffer queue interface.
  LOG_ON_FAILURE_AND_RETURN(
      recorder_object_->GetInterface(recorder_object_.Get(),
                                     SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
                                     &simple_buffer_queue_),
      false);

  // Register the input callback for the simple buffer queue.
  // This callback will be called when receiving new data from the device.
  LOG_ON_FAILURE_AND_RETURN(
      (*simple_buffer_queue_)->RegisterCallback(simple_buffer_queue_,
                                                SimpleBufferQueueCallback,
                                                this),
      false);

  return true;
}

void OpenSLESInputStream::SimpleBufferQueueCallback(
    SLAndroidSimpleBufferQueueItf buffer_queue, void* instance) {
  OpenSLESInputStream* stream =
      reinterpret_cast<OpenSLESInputStream*>(instance);
  stream->ReadBufferQueue();
}

void OpenSLESInputStream::ReadBufferQueue() {
  if (!started_)
    return;

  // TODO(xians): Get an accurate delay estimation.
  callback_->OnData(this,
                    audio_data_[active_queue_],
                    buffer_size_bytes_,
                    buffer_size_bytes_,
                    0.0);

  // Done with this buffer. Send it to device for recording.
  SLresult err = (*simple_buffer_queue_)->Enqueue(
      simple_buffer_queue_,
      audio_data_[active_queue_],
      buffer_size_bytes_);
  if (SL_RESULT_SUCCESS != err)
    HandleError(err);

  active_queue_ = (active_queue_ + 1) % kNumOfQueuesInBuffer;
}

void OpenSLESInputStream::SetupAudioBuffer() {
  DCHECK(!audio_data_[0]);
  for (int i = 0; i < kNumOfQueuesInBuffer; ++i) {
    audio_data_[i] = new uint8[buffer_size_bytes_];
  }
}

void OpenSLESInputStream::ReleaseAudioBuffer() {
  if (audio_data_[0]) {
    for (int i = 0; i < kNumOfQueuesInBuffer; ++i) {
      delete [] audio_data_[i];
      audio_data_[i] = NULL;
    }
  }
}

void OpenSLESInputStream::HandleError(SLresult error) {
  DLOG(FATAL) << "OpenSLES Input error " << error;
  if (callback_)
    callback_->OnError(this);
}

}  // namespace media