1 /*
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 "sdk/android/src/jni/audio_device/opensles_player.h"
12
13 #include <android/log.h>
14
15 #include <memory>
16
17 #include "api/array_view.h"
18 #include "modules/audio_device/fine_audio_buffer.h"
19 #include "rtc_base/arraysize.h"
20 #include "rtc_base/checks.h"
21 #include "rtc_base/platform_thread.h"
22 #include "rtc_base/time_utils.h"
23 #include "sdk/android/src/jni/audio_device/audio_common.h"
24
25 #define TAG "OpenSLESPlayer"
26 #define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
27 #define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
28 #define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
29 #define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
30 #define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
31
32 #define RETURN_ON_ERROR(op, ...) \
33 do { \
34 SLresult err = (op); \
35 if (err != SL_RESULT_SUCCESS) { \
36 ALOGE("%s failed: %s", #op, GetSLErrorString(err)); \
37 return __VA_ARGS__; \
38 } \
39 } while (0)
40
41 namespace webrtc {
42
43 namespace jni {
44
OpenSLESPlayer(const AudioParameters & audio_parameters,rtc::scoped_refptr<OpenSLEngineManager> engine_manager)45 OpenSLESPlayer::OpenSLESPlayer(
46 const AudioParameters& audio_parameters,
47 rtc::scoped_refptr<OpenSLEngineManager> engine_manager)
48 : audio_parameters_(audio_parameters),
49 audio_device_buffer_(nullptr),
50 initialized_(false),
51 playing_(false),
52 buffer_index_(0),
53 engine_manager_(std::move(engine_manager)),
54 engine_(nullptr),
55 player_(nullptr),
56 simple_buffer_queue_(nullptr),
57 volume_(nullptr),
58 last_play_time_(0) {
59 ALOGD("ctor[tid=%d]", rtc::CurrentThreadId());
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 // Detach from this thread since we want to use the checker to verify calls
66 // from the internal audio thread.
67 thread_checker_opensles_.Detach();
68 }
69
~OpenSLESPlayer()70 OpenSLESPlayer::~OpenSLESPlayer() {
71 ALOGD("dtor[tid=%d]", rtc::CurrentThreadId());
72 RTC_DCHECK(thread_checker_.IsCurrent());
73 Terminate();
74 DestroyAudioPlayer();
75 DestroyMix();
76 engine_ = nullptr;
77 RTC_DCHECK(!engine_);
78 RTC_DCHECK(!output_mix_.Get());
79 RTC_DCHECK(!player_);
80 RTC_DCHECK(!simple_buffer_queue_);
81 RTC_DCHECK(!volume_);
82 }
83
Init()84 int OpenSLESPlayer::Init() {
85 ALOGD("Init[tid=%d]", rtc::CurrentThreadId());
86 RTC_DCHECK(thread_checker_.IsCurrent());
87 if (audio_parameters_.channels() == 2) {
88 ALOGW("Stereo mode is enabled");
89 }
90 return 0;
91 }
92
Terminate()93 int OpenSLESPlayer::Terminate() {
94 ALOGD("Terminate[tid=%d]", rtc::CurrentThreadId());
95 RTC_DCHECK(thread_checker_.IsCurrent());
96 StopPlayout();
97 return 0;
98 }
99
InitPlayout()100 int OpenSLESPlayer::InitPlayout() {
101 ALOGD("InitPlayout[tid=%d]", rtc::CurrentThreadId());
102 RTC_DCHECK(thread_checker_.IsCurrent());
103 RTC_DCHECK(!initialized_);
104 RTC_DCHECK(!playing_);
105 if (!ObtainEngineInterface()) {
106 ALOGE("Failed to obtain SL Engine interface");
107 return -1;
108 }
109 CreateMix();
110 initialized_ = true;
111 buffer_index_ = 0;
112 return 0;
113 }
114
PlayoutIsInitialized() const115 bool OpenSLESPlayer::PlayoutIsInitialized() const {
116 return initialized_;
117 }
118
StartPlayout()119 int OpenSLESPlayer::StartPlayout() {
120 ALOGD("StartPlayout[tid=%d]", rtc::CurrentThreadId());
121 RTC_DCHECK(thread_checker_.IsCurrent());
122 RTC_DCHECK(initialized_);
123 RTC_DCHECK(!playing_);
124 if (fine_audio_buffer_) {
125 fine_audio_buffer_->ResetPlayout();
126 }
127 // The number of lower latency audio players is limited, hence we create the
128 // audio player in Start() and destroy it in Stop().
129 CreateAudioPlayer();
130 // Fill up audio buffers to avoid initial glitch and to ensure that playback
131 // starts when mode is later changed to SL_PLAYSTATE_PLAYING.
132 // TODO(henrika): we can save some delay by only making one call to
133 // EnqueuePlayoutData. Most likely not worth the risk of adding a glitch.
134 last_play_time_ = rtc::Time();
135 for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) {
136 EnqueuePlayoutData(true);
137 }
138 // Start streaming data by setting the play state to SL_PLAYSTATE_PLAYING.
139 // For a player object, when the object is in the SL_PLAYSTATE_PLAYING
140 // state, adding buffers will implicitly start playback.
141 RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_PLAYING), -1);
142 playing_ = (GetPlayState() == SL_PLAYSTATE_PLAYING);
143 RTC_DCHECK(playing_);
144 return 0;
145 }
146
StopPlayout()147 int OpenSLESPlayer::StopPlayout() {
148 ALOGD("StopPlayout[tid=%d]", rtc::CurrentThreadId());
149 RTC_DCHECK(thread_checker_.IsCurrent());
150 if (!initialized_ || !playing_) {
151 return 0;
152 }
153 // Stop playing by setting the play state to SL_PLAYSTATE_STOPPED.
154 RETURN_ON_ERROR((*player_)->SetPlayState(player_, SL_PLAYSTATE_STOPPED), -1);
155 // Clear the buffer queue to flush out any remaining data.
156 RETURN_ON_ERROR((*simple_buffer_queue_)->Clear(simple_buffer_queue_), -1);
157 #if RTC_DCHECK_IS_ON
158 // Verify that the buffer queue is in fact cleared as it should.
159 SLAndroidSimpleBufferQueueState buffer_queue_state;
160 (*simple_buffer_queue_)->GetState(simple_buffer_queue_, &buffer_queue_state);
161 RTC_DCHECK_EQ(0, buffer_queue_state.count);
162 RTC_DCHECK_EQ(0, buffer_queue_state.index);
163 #endif
164 // The number of lower latency audio players is limited, hence we create the
165 // audio player in Start() and destroy it in Stop().
166 DestroyAudioPlayer();
167 thread_checker_opensles_.Detach();
168 initialized_ = false;
169 playing_ = false;
170 return 0;
171 }
172
Playing() const173 bool OpenSLESPlayer::Playing() const {
174 return playing_;
175 }
176
SpeakerVolumeIsAvailable()177 bool OpenSLESPlayer::SpeakerVolumeIsAvailable() {
178 return false;
179 }
180
SetSpeakerVolume(uint32_t volume)181 int OpenSLESPlayer::SetSpeakerVolume(uint32_t volume) {
182 return -1;
183 }
184
SpeakerVolume() const185 absl::optional<uint32_t> OpenSLESPlayer::SpeakerVolume() const {
186 return absl::nullopt;
187 }
188
MaxSpeakerVolume() const189 absl::optional<uint32_t> OpenSLESPlayer::MaxSpeakerVolume() const {
190 return absl::nullopt;
191 }
192
MinSpeakerVolume() const193 absl::optional<uint32_t> OpenSLESPlayer::MinSpeakerVolume() const {
194 return absl::nullopt;
195 }
196
AttachAudioBuffer(AudioDeviceBuffer * audioBuffer)197 void OpenSLESPlayer::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
198 ALOGD("AttachAudioBuffer");
199 RTC_DCHECK(thread_checker_.IsCurrent());
200 audio_device_buffer_ = audioBuffer;
201 const int sample_rate_hz = audio_parameters_.sample_rate();
202 ALOGD("SetPlayoutSampleRate(%d)", sample_rate_hz);
203 audio_device_buffer_->SetPlayoutSampleRate(sample_rate_hz);
204 const size_t channels = audio_parameters_.channels();
205 ALOGD("SetPlayoutChannels(%zu)", channels);
206 audio_device_buffer_->SetPlayoutChannels(channels);
207 RTC_CHECK(audio_device_buffer_);
208 AllocateDataBuffers();
209 }
210
AllocateDataBuffers()211 void OpenSLESPlayer::AllocateDataBuffers() {
212 ALOGD("AllocateDataBuffers");
213 RTC_DCHECK(thread_checker_.IsCurrent());
214 RTC_DCHECK(!simple_buffer_queue_);
215 RTC_CHECK(audio_device_buffer_);
216 // Create a modified audio buffer class which allows us to ask for any number
217 // of samples (and not only multiple of 10ms) to match the native OpenSL ES
218 // buffer size. The native buffer size corresponds to the
219 // PROPERTY_OUTPUT_FRAMES_PER_BUFFER property which is the number of audio
220 // frames that the HAL (Hardware Abstraction Layer) buffer can hold. It is
221 // recommended to construct audio buffers so that they contain an exact
222 // multiple of this number. If so, callbacks will occur at regular intervals,
223 // which reduces jitter.
224 const size_t buffer_size_in_samples =
225 audio_parameters_.frames_per_buffer() * audio_parameters_.channels();
226 ALOGD("native buffer size: %zu", buffer_size_in_samples);
227 ALOGD("native buffer size in ms: %.2f",
228 audio_parameters_.GetBufferSizeInMilliseconds());
229 fine_audio_buffer_ = std::make_unique<FineAudioBuffer>(audio_device_buffer_);
230 // Allocated memory for audio buffers.
231 for (int i = 0; i < kNumOfOpenSLESBuffers; ++i) {
232 audio_buffers_[i].reset(new SLint16[buffer_size_in_samples]);
233 }
234 }
235
ObtainEngineInterface()236 bool OpenSLESPlayer::ObtainEngineInterface() {
237 ALOGD("ObtainEngineInterface");
238 RTC_DCHECK(thread_checker_.IsCurrent());
239 if (engine_)
240 return true;
241 // Get access to (or create if not already existing) the global OpenSL Engine
242 // object.
243 SLObjectItf engine_object = engine_manager_->GetOpenSLEngine();
244 if (engine_object == nullptr) {
245 ALOGE("Failed to access the global OpenSL engine");
246 return false;
247 }
248 // Get the SL Engine Interface which is implicit.
249 RETURN_ON_ERROR(
250 (*engine_object)->GetInterface(engine_object, SL_IID_ENGINE, &engine_),
251 false);
252 return true;
253 }
254
CreateMix()255 bool OpenSLESPlayer::CreateMix() {
256 ALOGD("CreateMix");
257 RTC_DCHECK(thread_checker_.IsCurrent());
258 RTC_DCHECK(engine_);
259 if (output_mix_.Get())
260 return true;
261
262 // Create the ouput mix on the engine object. No interfaces will be used.
263 RETURN_ON_ERROR((*engine_)->CreateOutputMix(engine_, output_mix_.Receive(), 0,
264 nullptr, nullptr),
265 false);
266 RETURN_ON_ERROR(output_mix_->Realize(output_mix_.Get(), SL_BOOLEAN_FALSE),
267 false);
268 return true;
269 }
270
DestroyMix()271 void OpenSLESPlayer::DestroyMix() {
272 ALOGD("DestroyMix");
273 RTC_DCHECK(thread_checker_.IsCurrent());
274 if (!output_mix_.Get())
275 return;
276 output_mix_.Reset();
277 }
278
CreateAudioPlayer()279 bool OpenSLESPlayer::CreateAudioPlayer() {
280 ALOGD("CreateAudioPlayer");
281 RTC_DCHECK(thread_checker_.IsCurrent());
282 RTC_DCHECK(output_mix_.Get());
283 if (player_object_.Get())
284 return true;
285 RTC_DCHECK(!player_);
286 RTC_DCHECK(!simple_buffer_queue_);
287 RTC_DCHECK(!volume_);
288
289 // source: Android Simple Buffer Queue Data Locator is source.
290 SLDataLocator_AndroidSimpleBufferQueue simple_buffer_queue = {
291 SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
292 static_cast<SLuint32>(kNumOfOpenSLESBuffers)};
293 SLDataSource audio_source = {&simple_buffer_queue, &pcm_format_};
294
295 // sink: OutputMix-based data is sink.
296 SLDataLocator_OutputMix locator_output_mix = {SL_DATALOCATOR_OUTPUTMIX,
297 output_mix_.Get()};
298 SLDataSink audio_sink = {&locator_output_mix, nullptr};
299
300 // Define interfaces that we indend to use and realize.
301 const SLInterfaceID interface_ids[] = {SL_IID_ANDROIDCONFIGURATION,
302 SL_IID_BUFFERQUEUE, SL_IID_VOLUME};
303 const SLboolean interface_required[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE,
304 SL_BOOLEAN_TRUE};
305
306 // Create the audio player on the engine interface.
307 RETURN_ON_ERROR(
308 (*engine_)->CreateAudioPlayer(
309 engine_, player_object_.Receive(), &audio_source, &audio_sink,
310 arraysize(interface_ids), interface_ids, interface_required),
311 false);
312
313 // Use the Android configuration interface to set platform-specific
314 // parameters. Should be done before player is realized.
315 SLAndroidConfigurationItf player_config;
316 RETURN_ON_ERROR(
317 player_object_->GetInterface(player_object_.Get(),
318 SL_IID_ANDROIDCONFIGURATION, &player_config),
319 false);
320 // Set audio player configuration to SL_ANDROID_STREAM_VOICE which
321 // corresponds to android.media.AudioManager.STREAM_VOICE_CALL.
322 SLint32 stream_type = SL_ANDROID_STREAM_VOICE;
323 RETURN_ON_ERROR(
324 (*player_config)
325 ->SetConfiguration(player_config, SL_ANDROID_KEY_STREAM_TYPE,
326 &stream_type, sizeof(SLint32)),
327 false);
328
329 // Realize the audio player object after configuration has been set.
330 RETURN_ON_ERROR(
331 player_object_->Realize(player_object_.Get(), SL_BOOLEAN_FALSE), false);
332
333 // Get the SLPlayItf interface on the audio player.
334 RETURN_ON_ERROR(
335 player_object_->GetInterface(player_object_.Get(), SL_IID_PLAY, &player_),
336 false);
337
338 // Get the SLAndroidSimpleBufferQueueItf interface on the audio player.
339 RETURN_ON_ERROR(
340 player_object_->GetInterface(player_object_.Get(), SL_IID_BUFFERQUEUE,
341 &simple_buffer_queue_),
342 false);
343
344 // Register callback method for the Android Simple Buffer Queue interface.
345 // This method will be called when the native audio layer needs audio data.
346 RETURN_ON_ERROR((*simple_buffer_queue_)
347 ->RegisterCallback(simple_buffer_queue_,
348 SimpleBufferQueueCallback, this),
349 false);
350
351 // Get the SLVolumeItf interface on the audio player.
352 RETURN_ON_ERROR(player_object_->GetInterface(player_object_.Get(),
353 SL_IID_VOLUME, &volume_),
354 false);
355
356 // TODO(henrika): might not be required to set volume to max here since it
357 // seems to be default on most devices. Might be required for unit tests.
358 // RETURN_ON_ERROR((*volume_)->SetVolumeLevel(volume_, 0), false);
359
360 return true;
361 }
362
DestroyAudioPlayer()363 void OpenSLESPlayer::DestroyAudioPlayer() {
364 ALOGD("DestroyAudioPlayer");
365 RTC_DCHECK(thread_checker_.IsCurrent());
366 if (!player_object_.Get())
367 return;
368 (*simple_buffer_queue_)
369 ->RegisterCallback(simple_buffer_queue_, nullptr, nullptr);
370 player_object_.Reset();
371 player_ = nullptr;
372 simple_buffer_queue_ = nullptr;
373 volume_ = nullptr;
374 }
375
376 // static
SimpleBufferQueueCallback(SLAndroidSimpleBufferQueueItf caller,void * context)377 void OpenSLESPlayer::SimpleBufferQueueCallback(
378 SLAndroidSimpleBufferQueueItf caller,
379 void* context) {
380 OpenSLESPlayer* stream = reinterpret_cast<OpenSLESPlayer*>(context);
381 stream->FillBufferQueue();
382 }
383
FillBufferQueue()384 void OpenSLESPlayer::FillBufferQueue() {
385 RTC_DCHECK(thread_checker_opensles_.IsCurrent());
386 SLuint32 state = GetPlayState();
387 if (state != SL_PLAYSTATE_PLAYING) {
388 ALOGW("Buffer callback in non-playing state!");
389 return;
390 }
391 EnqueuePlayoutData(false);
392 }
393
EnqueuePlayoutData(bool silence)394 void OpenSLESPlayer::EnqueuePlayoutData(bool silence) {
395 // Check delta time between two successive callbacks and provide a warning
396 // if it becomes very large.
397 // TODO(henrika): using 150ms as upper limit but this value is rather random.
398 const uint32_t current_time = rtc::Time();
399 const uint32_t diff = current_time - last_play_time_;
400 if (diff > 150) {
401 ALOGW("Bad OpenSL ES playout timing, dT=%u [ms]", diff);
402 }
403 last_play_time_ = current_time;
404 SLint8* audio_ptr8 =
405 reinterpret_cast<SLint8*>(audio_buffers_[buffer_index_].get());
406 if (silence) {
407 RTC_DCHECK(thread_checker_.IsCurrent());
408 // Avoid acquiring real audio data from WebRTC and fill the buffer with
409 // zeros instead. Used to prime the buffer with silence and to avoid asking
410 // for audio data from two different threads.
411 memset(audio_ptr8, 0, audio_parameters_.GetBytesPerBuffer());
412 } else {
413 RTC_DCHECK(thread_checker_opensles_.IsCurrent());
414 // Read audio data from the WebRTC source using the FineAudioBuffer object
415 // to adjust for differences in buffer size between WebRTC (10ms) and native
416 // OpenSL ES. Use hardcoded delay estimate since OpenSL ES does not support
417 // delay estimation.
418 fine_audio_buffer_->GetPlayoutData(
419 rtc::ArrayView<int16_t>(audio_buffers_[buffer_index_].get(),
420 audio_parameters_.frames_per_buffer() *
421 audio_parameters_.channels()),
422 25);
423 }
424 // Enqueue the decoded audio buffer for playback.
425 SLresult err = (*simple_buffer_queue_)
426 ->Enqueue(simple_buffer_queue_, audio_ptr8,
427 audio_parameters_.GetBytesPerBuffer());
428 if (SL_RESULT_SUCCESS != err) {
429 ALOGE("Enqueue failed: %d", err);
430 }
431 buffer_index_ = (buffer_index_ + 1) % kNumOfOpenSLESBuffers;
432 }
433
GetPlayState() const434 SLuint32 OpenSLESPlayer::GetPlayState() const {
435 RTC_DCHECK(player_);
436 SLuint32 state;
437 SLresult err = (*player_)->GetPlayState(player_, &state);
438 if (SL_RESULT_SUCCESS != err) {
439 ALOGE("GetPlayState failed: %d", err);
440 }
441 return state;
442 }
443
444 } // namespace jni
445
446 } // namespace webrtc
447