蓝牙耳机拨打电话和VOIP通话两种方式对于上层来说创建SCO的过程是不同的。
1、蓝牙耳机拨打电话是因为注册了函数handlePreciseCallStateChange(),当有CALL STATE状态发生改变时,就会调用BluetoothHeadset.java的phoneStateChanged()函数,在Headset 状态机里面调用processCallState()函数,通过调用JNI函数phoneStateChangeNative(),发送CALL STATE状态到蓝牙底层,然后创建SCO。
2、VOIP通话是通过第三方调用AudioManager.java的API接口函数startBluetoothSco(),创建一个ScoClient,调用startScoUsingVirtualVoiceCall(),在Headset状态机里面调用initiateScoUsingVirtualVoiceCall()调用了processCallState()函数,通过调用JNI函数phoneStateChangeNative(),模拟了CALL STATE的状态改变,发送CALL STATE状态到蓝牙底层,然后创建SCO。
希望发送和接收音频的应用程序可以使用此方法,一般有app来调用,比如微信通话,王者荣耀等等。
/frameworks/base/media/java/android/media/AudioManager.java
public void startBluetoothSco(){
1990 final IAudioService service = getService();
1991 try {
1992 service.startBluetoothSco(mICallBack,
1993 getContext().getApplicationInfo().targetSdkVersion);
1994 } catch (RemoteException e) {
1995 throw e.rethrowFromSystemServer();
1996 }
1997 }
/frameworks/base/services/core/java/com/android/server/audio/AudioService.java
4267 public void startBluetoothSco(IBinder cb, int targetSdkVersion) {
4268 final int uid = Binder.getCallingUid();
4269 final int pid = Binder.getCallingPid();
4270 final int scoAudioMode =
4271 (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR2) ?
4272 BtHelper.SCO_MODE_VIRTUAL_CALL : BtHelper.SCO_MODE_UNDEFINED;
4273 final String eventSource = new StringBuilder("startBluetoothSco()")
4274 .append(") from u/pid:").append(uid).append("/")
4275 .append(pid).toString();
4276
4277 new MediaMetrics.Item(MediaMetrics.Name.AUDIO_BLUETOOTH)
4278 .setUid(uid)
4279 .setPid(pid)
4280 .set(MediaMetrics.Property.EVENT, "startBluetoothSco")
4281 .set(MediaMetrics.Property.SCO_AUDIO_MODE,
4282 BtHelper.scoAudioModeToString(scoAudioMode))
4283 .record();
4284 startBluetoothScoInt(cb, scoAudioMode, eventSource);
4285
4286 }
void startBluetoothScoInt(IBinder cb, int scoAudioMode, @NonNull String eventSource) {
4307 MediaMetrics.Item mmi = new MediaMetrics.Item(MediaMetrics.Name.AUDIO_BLUETOOTH)
4308 .set(MediaMetrics.Property.EVENT, "startBluetoothScoInt")
4309 .set(MediaMetrics.Property.SCO_AUDIO_MODE,
4310 BtHelper.scoAudioModeToString(scoAudioMode));
4311
4312 if (!checkAudioSettingsPermission("startBluetoothSco()") ||
4313 !mSystemReady) {
4314 mmi.set(MediaMetrics.Property.EARLY_RETURN, "permission or systemReady").record();
4315 return;
4316 }
4317 synchronized (mDeviceBroker.mSetModeLock) {
4318 mDeviceBroker.startBluetoothScoForClient_Sync(cb, scoAudioMode, eventSource);
4319 }
4320 mmi.record();
4321 }
/frameworks/base/services/core/java/com/android/server/audio/AudioDeviceBroker.java
void startBluetoothScoForClient_Sync(IBinder cb, int scoAudioMode,
512 @NonNull String eventSource) {
513 synchronized (mDeviceStateLock) {
514 // Cancel speakerphone ON request by this same client: speakerphone and BT SCO routes
515 // are mutually exclusive.
516 // See symmetrical operation for setSpeakerphoneOn(true).
517 setSpeakerphoneOffForPid(Binder.getCallingPid());
518 mBtHelper.startBluetoothScoForClient(cb, scoAudioMode, eventSource);
519 }
520 }
/frameworks/base/services/core/java/com/android/server/audio/BtHelper.java
synchronized void startBluetoothScoForClient(IBinder cb, int scoAudioMode,
408 @NonNull String eventSource) {
409 ScoClient client = getScoClient(cb, true);
410 // The calling identity must be cleared before calling ScoClient.incCount().
411 // inCount() calls requestScoState() which in turn can call BluetoothHeadset APIs
412 // and this must be done on behalf of system server to make sure permissions are granted.
413 // The caller identity must be cleared after getScoClient() because it is needed if a new
414 // client is created.
415 final long ident = Binder.clearCallingIdentity();
416 try {
417 AudioService.sDeviceLogger.log(new AudioEventLogger.StringEvent(eventSource));
418 client.requestScoState(BluetoothHeadset.STATE_AUDIO_CONNECTED, scoAudioMode);
419 } catch (NullPointerException e) {
420 Log.e(TAG, "Null ScoClient", e);
421 }
422 Binder.restoreCallingIdentity(ident);
423 }
private boolean requestScoState(int state, int scoAudioMode) {
if (mScoClients.size() != 1) {
790 Log.i(TAG, "requestScoState: state=" + state + ", scoAudioMode=" + scoAudioMode
791 + ", num SCO clients=" + mScoClients.size());
792 return true;
793 }
794 if (state == BluetoothHeadset.STATE_AUDIO_CONNECTED) {
795 // Make sure that the state transitions to CONNECTING even if we cannot initiate
796 // the connection.
797 broadcastScoConnectionState(AudioManager.SCO_AUDIO_STATE_CONNECTING);
这里会广播状态
...
switch (mScoAudioState) {
808 case SCO_STATE_INACTIVE:
809 mScoAudioMode = scoAudioMode;
if (connectBluetoothScoAudioHelper(mBluetoothHeadset,
843 mBluetoothHeadsetDevice, mScoAudioMode)) {
844 mScoAudioState = SCO_STATE_ACTIVE_INTERNAL;
接下来会调用connectBluetoothScoAudioHelper函数
2.1 先看广播发送
private void broadcastScoConnectionState(int state) {
606 mDeviceBroker.postBroadcastScoConnectionState(state);
607 }
// Message handling on behalf of helper classes
607 void postBroadcastScoConnectionState(int state) {
608 sendIMsgNoDelay(MSG_I_BROADCAST_BT_CONNECTION_STATE, SENDMSG_QUEUE, state);
609 }
610
private class BrokerHandler extends Handler {
883
884 @Override
885 public void handleMessage(Message msg) {
886 switch (msg.what) {
case MSG_I_BROADCAST_BT_CONNECTION_STATE:
900 synchronized (mDeviceStateLock) {
901 mBtHelper.onBroadcastScoConnectionState(msg.arg1);
902 }
进行状态广播
/frameworks/base/services/core/java/com/android/server/audio/BtHelper.java
synchronized void onBroadcastScoConnectionState(int state) {
489 if (state == mScoConnectionState) {
490 return;
491 }
492 Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
493 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, state);
494 newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_PREVIOUS_STATE,
495 mScoConnectionState);
496 sendStickyBroadcastToAll(newIntent);
497 mScoConnectionState = state;
498 }
最终这个广播发出去就被一个app接收去显示蓝牙俩呢及状态了。
2.2. 再看connectBluetoothScoAudioHelper/frameworks/base/services/core/java/com/android/server/audio/BtHelper.java
private static boolean connectBluetoothScoAudioHelper(BluetoothHeadset bluetoothHeadset,
954 BluetoothDevice device, int scoAudioMode) {
955 switch (scoAudioMode) {
956 case SCO_MODE_RAW:
957 return bluetoothHeadset.connectAudio();
958 case SCO_MODE_VIRTUAL_CALL:
959 return bluetoothHeadset.startScoUsingVirtualVoiceCall();//执行这个
960 case SCO_MODE_VR:
961 return bluetoothHeadset.startVoiceRecognition(device);
962 default:
963 return false;
964 }
965 }
/frameworks/base/core/java/android/bluetooth/BluetoothHeadset.java
向当前活动设备发起 SCO 通道连接作为虚拟语音呼叫活动免提设备将收到来电和已连接呼叫的通知。
public boolean startScoUsingVirtualVoiceCall() {
980 if (DBG) log("startScoUsingVirtualVoiceCall()");
981 final IBluetoothHeadset service = mService;
982 if (service != null && isEnabled()) {
983 try {
984 return service.startScoUsingVirtualVoiceCall();
985 } catch (RemoteException e) {
986 Log.e(TAG, e.toString());
987 }
988 } else {
989 Log.w(TAG, "Proxy not attached to service");
990 if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable()));
991 }
992 return false;
993 }
/packages/apps/Bluetooth/src/com/android/bluetooth/hfp/HeadsetService.java
public boolean startScoUsingVirtualVoiceCall() {
615 HeadsetService service = getService();
616 if (service == null) {
617 return false;
618 }
619 return service.startScoUsingVirtualVoiceCall();
620 }
private boolean startScoUsingVirtualVoiceCall() {
1287 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission");
1288 Log.i(TAG, "startScoUsingVirtualVoiceCall: " + Utils.getUidPidString());
1289 synchronized (mStateMachines) {
1290 // TODO(b/79660380): Workaround in case voice recognition was not terminated properly
1291 if (mVoiceRecognitionStarted) {
1292 boolean status = stopVoiceRecognition(mActiveDevice);
1293 Log.w(TAG, "startScoUsingVirtualVoiceCall: voice recognition is still active, "
1294 + "just called stopVoiceRecognition, returned " + status + " on "
1295 + mActiveDevice + ", please try again");
1296 mVoiceRecognitionStarted = false;
1297 return false;
1298 }
1299 if (!isAudioModeIdle()) {
1300 Log.w(TAG, "startScoUsingVirtualVoiceCall: audio mode not idle, active device is "
1301 + mActiveDevice);
1302 return false;
1303 }
1304 // Audio should not be on when no audio mode is active
1305 if (isAudioOn()) {
1306 // Disconnect audio so that API user can try later
1307 boolean status = disconnectAudio();
1308 Log.w(TAG, "startScoUsingVirtualVoiceCall: audio is still active, please wait for "
1309 + "audio to be disconnected, disconnectAudio() returned " + status
1310 + ", active device is " + mActiveDevice);
1311 return false;
1312 }
1313 if (mActiveDevice == null) {
1314 Log.w(TAG, "startScoUsingVirtualVoiceCall: no active device");
1315 return false;
1316 }
1317 mVirtualCallStarted = true;
1318 // Send virtual phone state changed to initialize SCO
1319 phoneStateChanged(0, 0, HeadsetHalConstants.CALL_STATE_DIALING, "", 0, "", true);
1320 phoneStateChanged(0, 0, HeadsetHalConstants.CALL_STATE_ALERTING, "", 0, "", true);
1321 phoneStateChanged(1, 0, HeadsetHalConstants.CALL_STATE_IDLE, "", 0, "", true);
1322 return true;
1323 }
1324 }
Send virtual phone state changed to initialize SCO,此时发送电话状态改变:phoneStateChanged()函数
public void phoneStateChanged(int numActive, int numHeld, int callState, String number,
633 int type, String name) {
634 HeadsetService service = getService();
635 if (service == null) {
636 return;
637 }
638 service.phoneStateChanged(numActive, numHeld, callState, number, type, name, false);
639 }
private void phoneStateChanged(int numActive, int numHeld, int callState, String number,
1537 int type, String name, boolean isVirtualCall) {
1538 enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, "Need MODIFY_PHONE_STATE permission");
1539 synchronized (mStateMachines) {
1540 // Should stop all other audio mode in this case
1541 if ((numActive + numHeld) > 0 || callState != HeadsetHalConstants.CALL_STATE_IDLE) {
1542 if (!isVirtualCall && mVirtualCallStarted) {
1543 // stop virtual voice call if there is an incoming Telecom call update
1544 stopScoUsingVirtualVoiceCall();
。。。。。。。
// Suspend A2DP when call about is about to become active
1576 if (callState != HeadsetHalConstants.CALL_STATE_DISCONNECTED
1577 && !mSystemInterface.isCallIdle() && isCallIdleBefore) {
1578 mSystemInterface.getAudioManager().setParameters("A2dpSuspended=true");这里需要注意,在蓝牙进入audio on 之前就已经先把a2dpsuspended设置成了true
1579 }
doForEachConnectedStateMachine(
1582 stateMachine -> stateMachine.sendMessage(HeadsetStateMachine.CALL_STATE_CHANGED,
1583 new HeadsetCallState(numActive, numHeld, callState, number, type, name)));
这里需要注意,在蓝牙进入audio on 之前就已经先把a2dpsuspended设置成了true。
现在开始进行audio的连接:
Base class for Connected, AudioConnecting, AudioOn, AudioDisconnecting states 799 */ 800 private abstract class ConnectedBase extends HeadsetStateBase { 801 @Override 802 int getConnectionStateInt() { 803 return BluetoothProfile.STATE_CONNECTED; 804 }
case CALL_STATE_CHANGED: {
850 HeadsetCallState callState = (HeadsetCallState) message.obj;
851 if (!mNativeInterface.phoneStateChange(mDevice, callState)) {
852 stateLogW("processCallState: failed to update call state " + callState);
853 break;
854 }
855 break;
856 }
从这里就调用到了协议栈的phoneStateChange()函数,进行协议的流程:phonestatechange->BTA_AgResult->bta_ag_api_result。
具体的协议栈流程查看文首链接。



