ndk-samples icon indicating copy to clipboard operation
ndk-samples copied to clipboard

audio-echo sample doesn't work on Pixel 2 when recording audio over Bluetooth

Open sixbangs opened this issue 8 years ago • 20 comments

Tested on a Pixel 2 running 8.1.0 (patch Feb 5 2018).

Android Studio 3.0 BuildToolsVersion 26.0.3 com.android.tools.build:gradle:3.0.1 services.gradle.org/distributions/gradle-4.1-all.zip

This appears to reproduce with all Bluetooth headsets. I modified the sample to use startBluetoothSco() before recording: https://github.com/life-beam/android-ndk/tree/audio-echo-sco

For background, this is an issue we're observing with our app that uses Nuance VoCon (an NDK library that uses OpenSL) for voice recognition. It works well on all other phones, just not the Pixel 2. Now that it reproduces here, it appears that the problem may occur at a lower level than VoCon.

sixbangs avatar Feb 23 '18 22:02 sixbangs

the sample was not tested on Bluetooth, could well be a bug in the sample. Before dive deep into it, add @donturner, @philburk if there are any gotchas for Bluetooth.

Since this is new app, might directly use Oboe interface., potentially to make a bigger story out of your development.

ggfan avatar Feb 23 '18 22:02 ggfan

Hmm... I don't think Oboe is a possibility for us since we depend on OpenSL transitively through VoCon. Looks cool though; we had just checked out AAudio yesterday.

Note that we're already in production; audio recording was working pretty well until the Pixel 2 was released. There was a more general bug affecting audio recording via Bluetooth, but a fix is available in 8.1. Now recording audio over Bluetooth via the Java APIs works great, but it appears that something is still missing with OpenSL (and maybe AAudio).

sixbangs avatar Feb 25 '18 01:02 sixbangs

I added to @6bangs code BluetoothScoConnector constructer the following line audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); and now the audio-echo sample works with bluetooth on pixel 2. @ggfan, @donturner, @philburk why does pixel 2 need a call to audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); while other phones don't ? This is not only a Pixel 2 issue, I have seen several android phones that behaves this way.

atsafrir avatar Feb 26 '18 04:02 atsafrir

@atsafrir @6bangs thanks for the update and efforts! will follow-up: I do not have answer myself.

Yeah, the line audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); is significant: I could see the symptoms on both Pixel 2 ( Android P ) and Pixel XL ( android O MR1 ). Will pass on the info to experts and hope could assist them to dig the things out. Will update once get something solid. Thanks

ggfan avatar Feb 26 '18 17:02 ggfan

surprising to find that:

  • when it is in COMMUNICATION mode, Audio playback is FAST_PATH
  • when it is NOT in COMMUNICATION mode, Audio playback is denied of FAST_PATH request

if it is not in fast path, there is no way to run this sample: the callback is so irregular that it totally breaks streams. still need to debug why it is not granted the FAST_PATH in the failure case? The asked audio buffer size 3840 (framecount) is much smaller than supported buffer size of 11544. 11544 would be minimum latency time ( my guess ), application creates buffer of 96 frames, 11544/96 = 120.25 buffers, audio echo only creates 16, it is not going to play audio like streams.

Still need more debug, @6bangs how do you come up with the workaround? just a question.

ggfan avatar Mar 02 '18 05:03 ggfan

Created bug b2/74176028

ggfan avatar Mar 05 '18 17:03 ggfan

Thanks for the additional details; are there any docs for acquiring the FAST_PATH other than the SO question? I'll dig in more later this week, but looking forward to any updates coming from your end.

@atsafrir found the workaround in this thread: https://groups.google.com/forum/#!topic/android-ndk/0zxkPODXQ14

sixbangs avatar Mar 05 '18 21:03 sixbangs

https://developer.android.com/ndk/guides/audio/audio-latency.html would be another one, that SO question would still be true (I believe).

ggfan avatar Mar 05 '18 23:03 ggfan

Some info: when application starts up, Bluetooth audio is at default mode:

  • AUDIO_MODE_NORMAL (3)
  • OutputDevice is AUDIO_DEVICE_OUT_BLUETOOTH_A2DP ==> this does not support audio fast path. If no audio fast path, pro audio( low latency audio) will not be enabled ( could not support it ). So you will see HUGE audio buffer: "Client defaulted notificationFrames to 5772 for frameCount 11544".

Once set mode to COMMUNICATION, "MEDIA is forced to use the communication routing which has higher priority [and goes to earpiece by default]". Fast mode is supported <== audio Fast mode is enabled, hence we saw smaller audio buffers and other tuned up features for audio: D AudioTrack: Client defaulted notificationFrames to 96 for frameCount 384

It means that we ( applications ) will get notified after every 96 frames are consumed from playback in fast mode; while the "NORMAL" mode only notifies us for every 5772 frames ( this is too much: leave the math to you).

There is a way to detect whether we are in fast mode:

  1. Request for SL_IID_ANDROIDCONFIGURATION when CreateAudioPlayer()
  2. Request for SL_ANDROID_PERFORMANCE_LATENCY:
    SLAndroidConfigurationItf androidCfgItf;
    result = (*playerObjectItf_)->GetInterface(playerObjectItf_, SL_IID_ANDROIDCONFIGURATION, &androidCfgItf);
    SLASSERT(result);

    SLuint32 performanceMode = SL_ANDROID_PERFORMANCE_LATENCY;
    SLuint32 len = sizeof(performanceMode);
    result = (*androidCfgItf)->SetConfiguration(androidCfgItf,
                                                SL_ANDROID_KEY_PERFORMANCE_MODE,
                                                &performanceMode,
                                                len);
    SLASSERT(result);
  1. Check for sure PERFORMANCE_LATENCY mode is granted:
    // realize the player
    result = (*playerObjectItf_)->Realize(playerObjectItf_, SL_BOOLEAN_FALSE);
    SLASSERT(result);
    performanceMode  = SL_ANDROID_PERFORMANCE_NONE;
    result = (*androidCfgItf)->GetConfiguration(androidCfgItf,
                                                SL_ANDROID_KEY_PERFORMANCE_MODE,
                                                &len, &performanceMode);
    //  SLASSERT(result);  // do not check for this return value: it is wrong, more info below.

    if (performanceMode != SL_ANDROID_PERFORMANCE_LATENCY) {
        LOGE("====Low latency mode is not supported, could not move forward");
        .... // bail out from here
    }

Currently there is a small bug in the framework configuration code in that it missed a "break;" statement hence SLAndroidConfigurationItf::GetConfiguration() will always return UNSUPPORTED even it actually has the right values returned. So just ignore the return value from this function: it will be fixed in the future source code release.

Sorry for the delay, hope this helps you in your future project. Basically the answer is: yeah, application must sets mode into COMMUNICATION before creating audio playback streams to get low latency playback audio.

ggfan avatar Apr 03 '18 00:04 ggfan

Hi guys, I have the same issues with Bluetooth on Pixel 2 but with Java Api, same code work on Samsung, One plus, lg, nexus devices. however on Pixel 2 it gives corrupted stream.

Here is the the receiver's code:

bluetoothScoStateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        int newState = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
                AudioManager.SCO_AUDIO_STATE_ERROR);

        int prevState = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
                AudioManager.SCO_AUDIO_STATE_ERROR);

        if (prevState == AudioManager.SCO_AUDIO_STATE_CONNECTING) {
            if (newState == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
                Logger.i("Record Service => Bluetooth Sco connected, recording via headset");
                AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                audioManager.setBluetoothScoOn(true);
                createAudioRecorder(true);
                startRecording();
            }
        }
    }
}

Here the register code:

registerReceiver(bluetoothScoStateReceiver,
                    new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));

 audioManager.startBluetoothSco();

And I follow android docs to create a audio recorder:

int encoding = AudioFormat.ENCODING_PCM_16BIT;
if (isSourceHeadset) {
    source = MediaRecorder.AudioSource.VOICE_COMMUNICATION;
    audioFormat = AudioFormat.CHANNEL_IN_MONO;
    sampleRate = 16000;
 }

int bufferSize = AudioRecord.getMinBufferSize(sampleRate, format, encoding);
audioRecord = new AudioRecord(source, sampleRate, audioFormat, encoding, bufferSize);

Resulting voice stream is corrupted however the same code works on other devices. Is there something that I miss, or it's a bug in Pixel 2? I checked with several headsets. Also I noticed that they work perfectly on incoming/outgoing calls. Setting mode into COMMUNICATION results empty buffers from recorder.

Vardan95 avatar Apr 13 '18 20:04 Vardan95

@Vardan95 not quite sure if these are related issues; as far as I was aware, audio recording over Bluetooth was supposed to work fine on the Pixel 2 using the Java APIs.

@ggfan thanks for the write-up! This will definitely help when I can find the time to debug further. COMMUNICATION mode seems to be working in most cases, but it's not recommended by the Android docs:

The audio mode encompasses audio routing AND the behavior of the telephony layer. Therefore this method should only be used by applications that replace the platform-wide management of audio settings or the main telephony application.

As far as I know, there isn't another way to update the audio mode without affecting telephony. Our customers are happy, so we're happy - but this is a heavy-handed workaround :smile:

sixbangs avatar May 04 '18 12:05 sixbangs

Oh, I missed some of my emails. @Vardan95, java side I am a strange, created a bug 79253330 for it, we could track it there.

@6bang, looks like I need to follow-up more on that, could be a slow efforts... but will try. I did see other people are using it(set the communication mode). yeah, need to confirm doc and reality matches, or this is an exception...

ggfan avatar May 04 '18 18:05 ggfan

@Vardan95 some info ( I am relaying the authoritative info without confirm/study ):

    App should not use setBluetoothScoOn() this is reserved for the framework
    Apps should use startBluetoothSco() and when SCO_AUDIO_STATE_CONNECTED is signaled, the system is ready to send audio to BT SCO.

probably my bug is not visible to you: 7925330, may you confirm?

ggfan avatar May 04 '18 18:05 ggfan

@Vardan95 Did you solve this issue for pixel 2? I've encountered the same issue....

xiafan-su avatar Jun 30 '18 13:06 xiafan-su

@ggfan Hi ggfan, any update on bug 7925330? I can't find it, could you please share a hyper link to it?

xiafan-su avatar Jun 30 '18 13:06 xiafan-su

yeah the bug is 79253330, it is internal bug

ggfan avatar Jul 01 '18 18:07 ggfan

Hi guys, sorry for late response. @ggfan Unfortuantely I can't find it. @Demonsu Nope, we didn't find any workaround for pixel 2.

Vardan95 avatar Jul 08 '18 13:07 Vardan95

@Demonsu: could you file a bug from external database? I will link internal bug ( you could also do that )to it after you done, then you could have access and track it there. Not sure I could add value on Java side of framework. Thanks

ggfan avatar Jul 21 '18 00:07 ggfan

I would like to close this one as java side of the things is still in my dreams. If I do get some info from the internal bug, I will update here for sure. Feel free to reopen it

ggfan avatar Jul 28 '18 00:07 ggfan

@6bangs Hello I tried the audio-echo app in the audio-echo-sco branch linked your original post and I am trying to understand how it works. In the original audio-echo NDK program, there is a function that generates the echo and audio delay effect on the output sound, and there is an array called liveAudio inside this function (not actually an array but a pointer to int16_t* type) which contains the latest frame of incoming audio. I can multiply the contents of this array by a number to cause an increase of output volume. Where is the corresponding array in case of audio-echo-sco?

The liveAudio pointer is actually obtained by typecasting the void *data parameter of the EngineService callback function, and the type casting is done inside a switch case under case ENGINE_SERVICE_MSG_RECORDED_AUDIO_AVAILABLE: (value =3). This part is completely removed in audio-echo-sco and in fact the EngineService() function [audio_main.cpp] does not seem ot get called at all.

Where can I see the audio data (audio-echo-sco's' equivalent of liveAudio) in this program?

mahaju avatar Feb 19 '20 08:02 mahaju