blob: b9ccfd594d36dad0d7b85fbe1f8dbd4f16249f09 [file] [log] [blame]
henrikab2619892015-05-18 16:49:16 +02001/*
2 * Copyright (c) 2015 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_player.h"
12
13#include <android/log.h>
14
15#include "webrtc/base/arraysize.h"
16#include "webrtc/base/checks.h"
Peter Kasting1380e262015-08-28 17:31:03 -070017#include "webrtc/base/format_macros.h"
henrikab2619892015-05-18 16:49:16 +020018#include "webrtc/modules/audio_device/android/audio_manager.h"
henrika86d907c2015-09-07 16:09:50 +020019#include "webrtc/modules/audio_device/fine_audio_buffer.h"
henrikab2619892015-05-18 16:49:16 +020020
21#define TAG "OpenSLESPlayer"
22#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
23#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
24#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
25#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
26#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
27
28#define RETURN_ON_ERROR(op, ...) \
29 do { \
30 SLresult err = (op); \
31 if (err != SL_RESULT_SUCCESS) { \
32 ALOGE("%s failed: %d", #op, err); \
33 return __VA_ARGS__; \
34 } \
35 } while (0)
36
37namespace webrtc {
38
39OpenSLESPlayer::OpenSLESPlayer(AudioManager* audio_manager)
40 : audio_parameters_(audio_manager->GetPlayoutAudioParameters()),
41 audio_device_buffer_(NULL),
42 initialized_(false),
43 playing_(false),
44 bytes_per_buffer_(0),
45 buffer_index_(0),
46 engine_(nullptr),
47 player_(nullptr),
48 simple_buffer_queue_(nullptr),
49 volume_(nullptr) {
50 ALOGD("ctor%s", GetThreadInfo().c_str());
51 // Use native audio output parameters provided by the audio manager and
52 // define the PCM format structure.
53 pcm_format_ = CreatePCMConfiguration(audio_parameters_.channels(),
54 audio_parameters_.sample_rate(),
55 audio_parameters_.bits_per_sample());
56 // Detach from this thread since we want to use the checker to verify calls
57 // from the internal audio thread.
58 thread_checker_opensles_.DetachFromThread();
59}
60
61OpenSLESPlayer::~OpenSLESPlayer() {
62 ALOGD("dtor%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -070063 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +020064 Terminate();
65 DestroyAudioPlayer();
66 DestroyMix();
67 DestroyEngine();
henrikg91d6ede2015-09-17 00:24:34 -070068 RTC_DCHECK(!engine_object_.Get());
69 RTC_DCHECK(!engine_);
70 RTC_DCHECK(!output_mix_.Get());
71 RTC_DCHECK(!player_);
72 RTC_DCHECK(!simple_buffer_queue_);
73 RTC_DCHECK(!volume_);
henrikab2619892015-05-18 16:49:16 +020074}
75
76int OpenSLESPlayer::Init() {
77 ALOGD("Init%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -070078 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +020079 return 0;
80}
81
82int OpenSLESPlayer::Terminate() {
83 ALOGD("Terminate%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -070084 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +020085 StopPlayout();
86 return 0;
87}
88
89int OpenSLESPlayer::InitPlayout() {
90 ALOGD("InitPlayout%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -070091 RTC_DCHECK(thread_checker_.CalledOnValidThread());
92 RTC_DCHECK(!initialized_);
93 RTC_DCHECK(!playing_);
henrikab2619892015-05-18 16:49:16 +020094 CreateEngine();
95 CreateMix();
96 initialized_ = true;
97 buffer_index_ = 0;
98 return 0;
99}
100
101int OpenSLESPlayer::StartPlayout() {
102 ALOGD("StartPlayout%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -0700103 RTC_DCHECK(thread_checker_.CalledOnValidThread());
104 RTC_DCHECK(initialized_);
105 RTC_DCHECK(!playing_);
henrikab2619892015-05-18 16:49:16 +0200106 // The number of lower latency audio players is limited, hence we create the
107 // audio player in Start() and destroy it in Stop().
108 CreateAudioPlayer();
109 // Fill up audio buffers to avoid initial glitch and to ensure that playback
110 // starts when mode is later changed to SL_PLAYSTATE_PLAYING.
111 // TODO(henrika): we can save some delay by only making one call to
112 // EnqueuePlayoutData. Most likely not worth the risk of adding a glitch.
113 for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) {
114 EnqueuePlayoutData();
115 }
116 // Start streaming data by setting the play state to SL_PLAYSTATE_PLAYING.
117 // For a player object, when the object is in the SL_PLAYSTATE_PLAYING
118 // state, adding buffers will implicitly start playback.
119 RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_PLAYING), -1);
120 playing_ = (GetPlayState() == SL_PLAYSTATE_PLAYING);
henrikg91d6ede2015-09-17 00:24:34 -0700121 RTC_DCHECK(playing_);
henrikab2619892015-05-18 16:49:16 +0200122 return 0;
123}
124
125int OpenSLESPlayer::StopPlayout() {
126 ALOGD("StopPlayout%s", GetThreadInfo().c_str());
henrikg91d6ede2015-09-17 00:24:34 -0700127 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200128 if (!initialized_ || !playing_) {
129 return 0;
130 }
131 // Stop playing by setting the play state to SL_PLAYSTATE_STOPPED.
132 RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_STOPPED), -1);
133 // Clear the buffer queue to flush out any remaining data.
134 RETURN_ON_ERROR((*simple_buffer_queue_)->Clear(simple_buffer_queue_), -1);
135#ifndef NDEBUG
136 // Verify that the buffer queue is in fact cleared as it should.
137 SLAndroidSimpleBufferQueueState buffer_queue_state;
138 (*simple_buffer_queue_)->GetState(simple_buffer_queue_, &buffer_queue_state);
henrikg91d6ede2015-09-17 00:24:34 -0700139 RTC_DCHECK_EQ(0u, buffer_queue_state.count);
140 RTC_DCHECK_EQ(0u, buffer_queue_state.index);
henrikab2619892015-05-18 16:49:16 +0200141#endif
142 // The number of lower latency audio players is limited, hence we create the
143 // audio player in Start() and destroy it in Stop().
144 DestroyAudioPlayer();
145 thread_checker_opensles_.DetachFromThread();
146 initialized_ = false;
147 playing_ = false;
148 return 0;
149}
150
151int OpenSLESPlayer::SpeakerVolumeIsAvailable(bool& available) {
152 available = false;
153 return 0;
154}
155
156int OpenSLESPlayer::MaxSpeakerVolume(uint32_t& maxVolume) const {
157 return -1;
158}
159
160int OpenSLESPlayer::MinSpeakerVolume(uint32_t& minVolume) const {
161 return -1;
162}
163
164int OpenSLESPlayer::SetSpeakerVolume(uint32_t volume) {
165 return -1;
166}
167
168int OpenSLESPlayer::SpeakerVolume(uint32_t& volume) const {
169 return -1;
170}
171
172void OpenSLESPlayer::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
173 ALOGD("AttachAudioBuffer");
henrikg91d6ede2015-09-17 00:24:34 -0700174 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200175 audio_device_buffer_ = audioBuffer;
176 const int sample_rate_hz = audio_parameters_.sample_rate();
177 ALOGD("SetPlayoutSampleRate(%d)", sample_rate_hz);
178 audio_device_buffer_->SetPlayoutSampleRate(sample_rate_hz);
179 const int channels = audio_parameters_.channels();
180 ALOGD("SetPlayoutChannels(%d)", channels);
181 audio_device_buffer_->SetPlayoutChannels(channels);
henrikg91d6ede2015-09-17 00:24:34 -0700182 RTC_CHECK(audio_device_buffer_);
henrikab2619892015-05-18 16:49:16 +0200183 AllocateDataBuffers();
184}
185
Peter Kasting1380e262015-08-28 17:31:03 -0700186SLDataFormat_PCM OpenSLESPlayer::CreatePCMConfiguration(
187 int channels,
188 int sample_rate,
189 size_t bits_per_sample) {
henrikab2619892015-05-18 16:49:16 +0200190 ALOGD("CreatePCMConfiguration");
henrikg91d6ede2015-09-17 00:24:34 -0700191 RTC_CHECK_EQ(bits_per_sample, SL_PCMSAMPLEFORMAT_FIXED_16);
henrikab2619892015-05-18 16:49:16 +0200192 SLDataFormat_PCM format;
193 format.formatType = SL_DATAFORMAT_PCM;
194 format.numChannels = static_cast<SLuint32>(channels);
195 // Note that, the unit of sample rate is actually in milliHertz and not Hertz.
196 switch (sample_rate) {
197 case 8000:
198 format.samplesPerSec = SL_SAMPLINGRATE_8;
199 break;
200 case 16000:
201 format.samplesPerSec = SL_SAMPLINGRATE_16;
202 break;
203 case 22050:
204 format.samplesPerSec = SL_SAMPLINGRATE_22_05;
205 break;
206 case 32000:
207 format.samplesPerSec = SL_SAMPLINGRATE_32;
208 break;
209 case 44100:
210 format.samplesPerSec = SL_SAMPLINGRATE_44_1;
211 break;
212 case 48000:
213 format.samplesPerSec = SL_SAMPLINGRATE_48;
214 break;
215 default:
henrikg91d6ede2015-09-17 00:24:34 -0700216 RTC_CHECK(false) << "Unsupported sample rate: " << sample_rate;
henrikab2619892015-05-18 16:49:16 +0200217 }
218 format.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
219 format.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
220 format.endianness = SL_BYTEORDER_LITTLEENDIAN;
221 if (format.numChannels == 1)
222 format.channelMask = SL_SPEAKER_FRONT_CENTER;
223 else if (format.numChannels == 2)
224 format.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
225 else
henrikg91d6ede2015-09-17 00:24:34 -0700226 RTC_CHECK(false) << "Unsupported number of channels: "
227 << format.numChannels;
henrikab2619892015-05-18 16:49:16 +0200228 return format;
229}
230
231void OpenSLESPlayer::AllocateDataBuffers() {
232 ALOGD("AllocateDataBuffers");
henrikg91d6ede2015-09-17 00:24:34 -0700233 RTC_DCHECK(thread_checker_.CalledOnValidThread());
234 RTC_DCHECK(!simple_buffer_queue_);
235 RTC_CHECK(audio_device_buffer_);
henrikab2619892015-05-18 16:49:16 +0200236 bytes_per_buffer_ = audio_parameters_.GetBytesPerBuffer();
Peter Kasting1380e262015-08-28 17:31:03 -0700237 ALOGD("native buffer size: %" PRIuS, bytes_per_buffer_);
henrikab2619892015-05-18 16:49:16 +0200238 // Create a modified audio buffer class which allows us to ask for any number
239 // of samples (and not only multiple of 10ms) to match the native OpenSL ES
240 // buffer size.
241 fine_buffer_.reset(new FineAudioBuffer(audio_device_buffer_,
242 bytes_per_buffer_,
243 audio_parameters_.sample_rate()));
244 // Each buffer must be of this size to avoid unnecessary memcpy while caching
245 // data between successive callbacks.
henrika86d907c2015-09-07 16:09:50 +0200246 const size_t required_buffer_size =
247 fine_buffer_->RequiredPlayoutBufferSizeBytes();
Peter Kasting1380e262015-08-28 17:31:03 -0700248 ALOGD("required buffer size: %" PRIuS, required_buffer_size);
henrikab2619892015-05-18 16:49:16 +0200249 for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) {
250 audio_buffers_[i].reset(new SLint8[required_buffer_size]);
251 }
252}
253
254bool OpenSLESPlayer::CreateEngine() {
255 ALOGD("CreateEngine");
henrikg91d6ede2015-09-17 00:24:34 -0700256 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200257 if (engine_object_.Get())
258 return true;
henrikg91d6ede2015-09-17 00:24:34 -0700259 RTC_DCHECK(!engine_);
henrikab2619892015-05-18 16:49:16 +0200260 const SLEngineOption option[] = {
261 {SL_ENGINEOPTION_THREADSAFE, static_cast<SLuint32>(SL_BOOLEAN_TRUE)}};
262 RETURN_ON_ERROR(
263 slCreateEngine(engine_object_.Receive(), 1, option, 0, NULL, NULL),
264 false);
265 RETURN_ON_ERROR(
266 engine_object_->Realize(engine_object_.Get(), SL_BOOLEAN_FALSE), false);
267 RETURN_ON_ERROR(engine_object_->GetInterface(engine_object_.Get(),
268 SL_IID_ENGINE, &engine_),
269 false);
270 return true;
271}
272
273void OpenSLESPlayer::DestroyEngine() {
274 ALOGD("DestroyEngine");
henrikg91d6ede2015-09-17 00:24:34 -0700275 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200276 if (!engine_object_.Get())
277 return;
278 engine_ = nullptr;
279 engine_object_.Reset();
280}
281
282bool OpenSLESPlayer::CreateMix() {
283 ALOGD("CreateMix");
henrikg91d6ede2015-09-17 00:24:34 -0700284 RTC_DCHECK(thread_checker_.CalledOnValidThread());
285 RTC_DCHECK(engine_);
henrikab2619892015-05-18 16:49:16 +0200286 if (output_mix_.Get())
287 return true;
288
289 // Create the ouput mix on the engine object. No interfaces will be used.
290 RETURN_ON_ERROR((*engine_)->CreateOutputMix(engine_, output_mix_.Receive(), 0,
291 NULL, NULL),
292 false);
293 RETURN_ON_ERROR(output_mix_->Realize(output_mix_.Get(), SL_BOOLEAN_FALSE),
294 false);
295 return true;
296}
297
298void OpenSLESPlayer::DestroyMix() {
299 ALOGD("DestroyMix");
henrikg91d6ede2015-09-17 00:24:34 -0700300 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200301 if (!output_mix_.Get())
302 return;
303 output_mix_.Reset();
304}
305
306bool OpenSLESPlayer::CreateAudioPlayer() {
307 ALOGD("CreateAudioPlayer");
henrikg91d6ede2015-09-17 00:24:34 -0700308 RTC_DCHECK(thread_checker_.CalledOnValidThread());
309 RTC_DCHECK(engine_object_.Get());
310 RTC_DCHECK(output_mix_.Get());
henrikab2619892015-05-18 16:49:16 +0200311 if (player_object_.Get())
312 return true;
henrikg91d6ede2015-09-17 00:24:34 -0700313 RTC_DCHECK(!player_);
314 RTC_DCHECK(!simple_buffer_queue_);
315 RTC_DCHECK(!volume_);
henrikab2619892015-05-18 16:49:16 +0200316
317 // source: Android Simple Buffer Queue Data Locator is source.
318 SLDataLocator_AndroidSimpleBufferQueue simple_buffer_queue = {
319 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
320 static_cast<SLuint32>(kNumOfOpenSLESBuffers)};
321 SLDataSource audio_source = {&simple_buffer_queue, &pcm_format_};
322
323 // sink: OutputMix-based data is sink.
324 SLDataLocator_OutputMix locator_output_mix = {SL_DATALOCATOR_OUTPUTMIX,
325 output_mix_.Get()};
326 SLDataSink audio_sink = {&locator_output_mix, NULL};
327
328 // Define interfaces that we indend to use and realize.
329 const SLInterfaceID interface_ids[] = {
330 SL_IID_ANDROIDCONFIGURATION, SL_IID_BUFFERQUEUE, SL_IID_VOLUME};
331 const SLboolean interface_required[] = {
332 SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
333
334 // Create the audio player on the engine interface.
335 RETURN_ON_ERROR(
336 (*engine_)->CreateAudioPlayer(
337 engine_, player_object_.Receive(), &audio_source, &audio_sink,
338 arraysize(interface_ids), interface_ids, interface_required),
339 false);
340
341 // Use the Android configuration interface to set platform-specific
342 // parameters. Should be done before player is realized.
343 SLAndroidConfigurationItf player_config;
344 RETURN_ON_ERROR(
345 player_object_->GetInterface(player_object_.Get(),
346 SL_IID_ANDROIDCONFIGURATION, &player_config),
347 false);
348 // Set audio player configuration to SL_ANDROID_STREAM_VOICE which
349 // corresponds to android.media.AudioManager.STREAM_VOICE_CALL.
henrika1ba936a2015-11-03 04:27:58 -0800350 SLint32 stream_type = SL_ANDROID_STREAM_VOICE;
henrikab2619892015-05-18 16:49:16 +0200351 RETURN_ON_ERROR(
352 (*player_config)
353 ->SetConfiguration(player_config, SL_ANDROID_KEY_STREAM_TYPE,
354 &stream_type, sizeof(SLint32)),
355 false);
356
357 // Realize the audio player object after configuration has been set.
358 RETURN_ON_ERROR(
359 player_object_->Realize(player_object_.Get(), SL_BOOLEAN_FALSE), false);
360
361 // Get the SLPlayItf interface on the audio player.
362 RETURN_ON_ERROR(
363 player_object_->GetInterface(player_object_.Get(), SL_IID_PLAY, &player_),
364 false);
365
366 // Get the SLAndroidSimpleBufferQueueItf interface on the audio player.
367 RETURN_ON_ERROR(
368 player_object_->GetInterface(player_object_.Get(), SL_IID_BUFFERQUEUE,
369 &simple_buffer_queue_),
370 false);
371
372 // Register callback method for the Android Simple Buffer Queue interface.
373 // This method will be called when the native audio layer needs audio data.
374 RETURN_ON_ERROR((*simple_buffer_queue_)
375 ->RegisterCallback(simple_buffer_queue_,
376 SimpleBufferQueueCallback, this),
377 false);
378
379 // Get the SLVolumeItf interface on the audio player.
380 RETURN_ON_ERROR(player_object_->GetInterface(player_object_.Get(),
381 SL_IID_VOLUME, &volume_),
382 false);
383
384 // TODO(henrika): might not be required to set volume to max here since it
385 // seems to be default on most devices. Might be required for unit tests.
386 // RETURN_ON_ERROR((*volume_)->SetVolumeLevel(volume_, 0), false);
387
388 return true;
389}
390
391void OpenSLESPlayer::DestroyAudioPlayer() {
392 ALOGD("DestroyAudioPlayer");
henrikg91d6ede2015-09-17 00:24:34 -0700393 RTC_DCHECK(thread_checker_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200394 if (!player_object_.Get())
395 return;
396 player_object_.Reset();
397 player_ = nullptr;
398 simple_buffer_queue_ = nullptr;
399 volume_ = nullptr;
400}
401
402// static
403void OpenSLESPlayer::SimpleBufferQueueCallback(
404 SLAndroidSimpleBufferQueueItf caller,
405 void* context) {
406 OpenSLESPlayer* stream = reinterpret_cast<OpenSLESPlayer*>(context);
407 stream->FillBufferQueue();
408}
409
410void OpenSLESPlayer::FillBufferQueue() {
henrikg91d6ede2015-09-17 00:24:34 -0700411 RTC_DCHECK(thread_checker_opensles_.CalledOnValidThread());
henrikab2619892015-05-18 16:49:16 +0200412 SLuint32 state = GetPlayState();
413 if (state != SL_PLAYSTATE_PLAYING) {
414 ALOGW("Buffer callback in non-playing state!");
415 return;
416 }
417 EnqueuePlayoutData();
418}
419
420void OpenSLESPlayer::EnqueuePlayoutData() {
421 // Read audio data from the WebRTC source using the FineAudioBuffer object
422 // to adjust for differences in buffer size between WebRTC (10ms) and native
423 // OpenSL ES.
424 SLint8* audio_ptr = audio_buffers_[buffer_index_].get();
henrika86d907c2015-09-07 16:09:50 +0200425 fine_buffer_->GetPlayoutData(audio_ptr);
henrikab2619892015-05-18 16:49:16 +0200426 // Enqueue the decoded audio buffer for playback.
427 SLresult err =
428 (*simple_buffer_queue_)
429 ->Enqueue(simple_buffer_queue_, audio_ptr, bytes_per_buffer_);
430 if (SL_RESULT_SUCCESS != err) {
431 ALOGE("Enqueue failed: %d", err);
432 }
433 buffer_index_ = (buffer_index_ + 1) % kNumOfOpenSLESBuffers;
434}
435
436SLuint32 OpenSLESPlayer::GetPlayState() const {
henrikg91d6ede2015-09-17 00:24:34 -0700437 RTC_DCHECK(player_);
henrikab2619892015-05-18 16:49:16 +0200438 SLuint32 state;
439 SLresult err = (*player_)->GetPlayState(player_, &state);
440 if (SL_RESULT_SUCCESS != err) {
441 ALOGE("GetPlayState failed: %d", err);
442 }
443 return state;
444}
445
446} // namespace webrtc