1 蓝牙的两种类型

部署最为普遍的两种规格为蓝牙基础率/增强数据率 (BR/EDR)(采用版本为 2.0/2.1)和低耗能 (LE) 蓝牙(采用版本为 4.0/4.1/4.2)。

存在哪些差异?

蓝牙 BR/EDR—可建立相对较短距离的持续无线连接,因此非常适用于流式音频等应用

蓝牙 LE—可建立短时间的长距离无线电连接,非常适用于无需持续连接但依赖电池具有较长寿命的的物联网 (IoT) 应用

双模—双模芯片可支持需要连接 BR/EDR 设备(例如音频耳机)以及 LE 设备(例如穿戴设备或零售信标)的单一设备(例如智能手机或平板电脑)

2 核心系统结构

该系统包含射频收发器、基带和协议栈,支持设备连接和交换各类数据。

蓝牙设备交换根据蓝牙规格协议信号。核心系统协议包括射频 (RF) 协议、链路控制 (LC) 协议、链路管理器 (LM) 协议以及逻辑链路控制和适配协议 (L2CAP),蓝牙规格详细定义了这些协议。

最低的三个系统层—射频、链路控制和链路管理器协议—通常被归属于称为蓝牙控制器的子系统。这是一种采用可选标准接口—主机控制器接口 (HCI)—的通用部署,支持与蓝牙系统的其他设备(即蓝牙主机)进行双向通信。

主控制器可能是以下配置之一,具体取决于用例:

BR/EDR 控制器,包括射频、基带、链路管理器和可选 HCI

LE 控制器,包括 LE PHY、链路层和可选 HCI

BR/EDR 组合控制器和 LE 控制器,组合控制器共享一个蓝牙设备地址

蓝牙规格通过定义等效层之间交换的协议信息来实现系统之间的互操作性。它还通过定义蓝牙控制器和蓝牙主机之间的公用接口来实现独立蓝牙子系统之间的互操作性。

物理 (PHY) 层

通过蓝牙通信信道控制 2.4Ghz 射频的传输/接收。BR/EDR 提供的信道较多但带宽较窄,而 LE 使用的信道较少但带宽较宽。

链路层

定义数据包结构/信道、发现/连接程序以及发送/接收数据。

直接测试模式

允许测试人员向 PHY 层发出指令以传输或接收给定数据包序列,通过 HCI 或 2 线 UART 接口提交命令。

主机控制器接口 (HCI)

蓝牙控制器子系统(底部三层)和蓝牙主机之间的可选标准接口。

逻辑链路控制和适配协议 (L2CAP) 层

基于数据包的协议,可将数据包传输至 HCI 或直接传输到无主机系统中的链路管理器。支持更高级别的协议多路复用、数据包分割和重组,以及将服务质量信息传输到更高层。

属性协议 (ATT)

在建立连接之后定义数据交换客户端/服务器协议。使用通用属性配置文件 (GATT) 将属性分类为有意义的服务。ATT 主要用于 LE 部署,偶尔也会用于 BR/EDR 部署。

安全管理器

定义管理蓝牙设备之间配对完整性、身份验证以及加密的协议和操作,提供安全功能工具箱,其他组件可利用该工具箱支持不同应用所需的各种安全级别。

通用属性配置文件 (GATT)

使用属性协议,GATT 对封装设备组件性能的服务进行分组,并描述基于 GATT 功能的用例、角色和一般性能。其服务框架定义服务规程和格式及其特性,其中包括发现、读取、写入、通知以及指示特性以及配置特性广播。GATT 仅用于蓝牙 LE 部署。

通用访问配置文件(GAP)

可与蓝牙 LE 部署中的 GATT 配合使用,以定义与发现蓝牙设备和共享信息相关的规程和角色,以及连接蓝牙设备的链路管理内容。

3 Android抓取hci蓝牙log

本文是基于AOSP,android 6.0抓取蓝牙log方式描述。

在安卓手机设置-开发者选项-启用蓝牙HCI信息收集日志。个人理解我们抓取的日志实际上就是host和controller通过HCI收发数据截获的数据帧。

3.1 操作描述

1.捷波朗蓝牙耳机进入可被发现状态;

2.打开手机上的蓝牙开关;

3.扫描到蓝牙设备,直到扫描结束;

4.手机上点击捷波朗进行配对;

5.稍等片刻手机和捷波朗耳机配对并连接成功;

6.打开手机音乐播放器放音乐,耳机中听到音乐声,停留一小段时间;

7.手机中关闭蓝牙;

8.蓝牙耳机断开连接,并关闭耳机。

重启手机PC上可以在内置存储中找到btsnoop_hci.log文件,或者用其他第三方360助手等导出到PC,这就是蓝牙日志,PC上使用WireShark进行日志分析。

3.2 分析蓝牙log

对照上面的操作描述。

1.打开手机上的蓝牙开关,host向controller发送Reset指令,标志着即将启动手机上的蓝牙模块。

2.手机上的蓝牙开启成功以后,自动进入搜索模式,直到搜索结束,这个时候controller向host上报搜索结果,其中就有捷波朗蓝牙耳机,如下:

android 实现蓝牙录音 安卓 蓝牙耳机录音_链路

可以发现捷波朗耳机为可穿戴耳机设备(Wearable Headset Device),耳机名称缩写名称为Jabra EXTREME2,以及信号强度RSSI值等。

3.点击手机上的配对和耳机进行配对。

对照log可以知道:

首先会请求被连接设备的详细名称;

android 实现蓝牙录音 安卓 蓝牙耳机录音_蓝牙_02

然后创建连接、获取时钟偏移等,具体如下;

android 实现蓝牙录音 安卓 蓝牙耳机录音_录音_03

接下来才是真正的匹配,进行身份认证;

android 实现蓝牙录音 安卓 蓝牙耳机录音_蓝牙_04

4.手机和蓝牙耳机连接成功,配置完成后可正常传输数据。这里的主从角色和我们想当然的理解有差异,蓝牙耳机是主设备,手机是从设备。

android 实现蓝牙录音 安卓 蓝牙耳机录音_android_05

5.手机上播放音乐,蓝牙耳机接收,并未看到熟悉的A2DP协议,实际上SBC就是A2DP中关于音频的编码格式。

SBC即Sub-band coding,子带编码,是A2DP(Advanced Audio Distribution Profile,蓝牙音频传输协议)协议强制规定的编码格式。

android 实现蓝牙录音 安卓 蓝牙耳机录音_录音_06

这个耳机比较老了,编码用的是SBC格式,新耳机目前会采用ACC、APTX和LDAC等格式编码,进一步提升音频品质。

6.关闭手机蓝牙,也会看到Reset命令。

以上就是对照log粗略分析蓝牙耳机从配对到连接,再到通过蓝牙接收手机音频的过程。

4. 手机通话过程中蓝牙耳机连接分析

4.1 预备知识

在主单元和从单元之间,可以确定不同的类型的蓝牙物理链路:ACL(Asynchronous Connectionless),和另一种链路是SCO(Synchronous Connection Oriented)。SCO主要用于同步话音传送,ACL主要用于分组数据传送。A2DP(Advanced Audio Distribution Profile 高级音频传输模型)是跑在ACL链路上的高品质音频协议。

SCO连接对称连接,利用保留时隙传送数据包。它主要用于:主单元和从单元之间实现点到点链接。连接建立后,主设备和从设备可以不被选中就发送SCO数据包。

(1) SCO数据包既可以传送话音,也可以传送数据,但在传送数据时,只用于重发被损坏的那部分的数据。

(2) SCO主要用来传输对时间要求很高的数据通信。

(3) SCO 链接由主单元发送SCO 建立消息,经链接管理(LM)协议来确立。

ACL链路就是定向发送数据包,它既支持对称连接,也支持不对称连接(既可以一对一,也可以一对多)。主要用于:主单元与网中的所有从单元之间实现一点多址的连接方式。

主设备负责控制链路带宽,并决定微微网中的每个从设备可以占用多少带宽和连接的对称性。从设备只有被选中时才能传送数据。ACL链路也支持接收主设备发给微微网中所有从设备的广播消息。

4.2 蓝牙耳机通话分析

(1) 模式设置

为指定连接句柄写链路策略设置。链路策略设置允许主机控制器指定用于连接句柄的LM连接模式

host->controlller

  
Bluetooth
3.  
    [Source: host]
4.  
    [Destination: controller]
5.  
Bluetooth HCI H4
6.  
Sent (0x00)]
7.  
Command (0x01)
8.  
Bluetooth HCI Command - Write Link Policy Settings
9.  
Settings (0x080d)
10.  
    Parameter Total Length: 4
11.  
    Connection Handle: 0x0003
12.  
true (1)  //允许角色切换
13.  
.1. = Enable Hold Mode: true (1)    //改变LM状态和本地及远程设备为主模式
14.  
.1.. = Enable Sniff Mode: true (1)   //改变LM状态和本地及远程设备为呼吸模式
15.  
0... = Enable Park Mode: false (0)   //改变LM状态和本地及远程设备为休眠模式
16.  
Response in frame: 322]
17.  
Command-Response Delta: 1.3ms]

controlller->host

  
Bluetooth
3.  
    [Source: controller]
4.  
    [Destination: host]
5.  
Bluetooth HCI H4
6.  
0x01)]
7.  
Type: HCI Event (0x04)
8.  
Bluetooth HCI Event - Command Complete
9.  
0x0e)//命令执行状态-完成
10.  
6
11.  
of Allowed Command Packets: 1
12.  
Write Link Policy Settings (0x080d)
13.  
0000 10.. .... .... = Opcode Group Field: Link Policy Commands (0x02)
14.  
00 0000 1101 = Opcode Command Field: Write Link Policy Settings (0x00d)
15.  
0x00)
16.  
0x0003 //建立连接句柄
17.  
in frame: 321]
18.  
1.3ms]
(2) 语音设置
host->controlller
1.  
Frame 1471: 6 bytes on wire (48 bits), 6 bytes captured (48 bits)
2.  
Bluetooth
3.  
    [Source: host]
4.  
    [Destination: controller]
5.  
Bluetooth HCI H4
6.  
0x00)]
7.  
0x01)
8.  
Bluetooth HCI Command - Write Voice Setting
9.  
0x0c26)
10.  
2
11.  
0000 00.. .... .... = Unused bits: 0x00
12.  
.00 .... .... = Input Coding: Linear (0)
13.  
01.. .... = Input Data Format: 2's complement (1)
14.  
.1. .... = Input Sample Size: 16 bit (only for Linear PCM) (1)
15.  
.0 00.. = Linear PCM Bit Position: 0
16.  
.11 = Air Coding Format: Transparent (3)
17.  
Response in frame: 1472]
18.  
Response Delta: 0.36ms]

controlller->host


Bluetooth
3.  
    [Source: controller]
4.  
    [Destination: host]
5.  
Bluetooth HCI H4
6.  
0x01)]
7.  
Event (0x04)
8.  
Bluetooth HCI Event - Command Complete
9.  
Event Code: Command Complete (0x0e)
10.  
4
11.  
of Allowed Command Packets: 1
12.  
0x0c26)
13.  
0000 11.. .... .... = Opcode Group Field: Host Controller & Baseband Commands (0x03)
14.  
.00 0010 0110 = Opcode Command Field: Write Voice Setting (0x026)
15.  
0x00)
16.  
in frame: 1471]
17.  
0.36ms]

(3) 建立SCO连接

host->controlller

 
Bluetooth
3.  
    [Source: host]
4.  
    [Destination: controller]
5.  
Bluetooth HCI H4
6.  
    [Direction: Sent (0x00)]
7.  
    HCI Packet Type: HCI Command (0x01)
8.  
Bluetooth HCI Command - Setup Synchronous Connection
9.  
    Command Opcode: Setup Synchronous Connection (0x0428)
10.  
    Parameter Total Length: 17
11.  
    Connection Handle: 0x0003
12.  
    Tx Bandwidth (bytes/s): 8000
13.  
    Rx Bandwidth (bytes/s): 8000
14.  
    Max. Latency (ms): 13
15.  
    //语音设置参数,可以理解为SCO通道的属性
16.  
    0000 00.. .... .... = Unused bits: 0x00
17.  
    .... ..00 .... .... = Input Coding: Linear (0)
18.  
    .... .... 01.. .... = Input Data Format: 2's complement (1)
19.  
    .... .... ..1. .... = Input Sample Size: 16 bit (only for Linear PCM) (1)
20.  
    .... .... ...0 00.. = Linear PCM Bit Position: 0
21.  
    .... .... .... ..11 = Air Coding Format: Transparent (3)
22.  
optimize for link quality (2)
23.  
Type: 0x0388, 3-EV5, 2-EV5, 3-EV3, EV3
24.  
0000 00.. .... .... = Reserved: 0x00
25.  
.1. .... .... = 3-EV5: True
26.  
.1 .... .... = 2-EV5: True
27.  
1... .... = 3-EV3: True
28.  
.0.. .... = 2-EV3: False
29.  
.0. .... = EV5: False
30.  
.0 .... = EV4: False
31.  
1... = EV3: True
32.  
.0.. = HV3: False
33.  
.0. = HV2: False
34.  
.0 = HV1: False
35.  
in frame: 1474]
36.  
1.161ms]
37.  
in frame: 1476]
38.  
201.225ms]

controlller->host


Bluetooth
3.  
    [Source: controller]
4.  
    [Destination: host]
5.  
Bluetooth HCI H4
6.  
0x01)]
7.  
Event (0x04)
8.  
Bluetooth HCI Event - Command Status
9.  
Event Code: Command Status (0x0f)
10.  
4
11.  
0x00)
12.  
of Allowed Command Packets: 1
13.  
0x0428)
14.  
0000 01.. .... .... = Opcode Group Field: Link Control Commands (0x01)
15.  
.00 0010 1000 = Opcode Command Field: Setup Synchronous Connection (0x028)
16.  
in frame: 1473]
17.  
in frame: 1476]
18.  
1.161ms]
19.  
200.064ms]
20.  
Frame 1476: 20 bytes on wire (160 bits), 20 bytes captured (160 bits)
21.  
Bluetooth
22.  
    [Source: controller]
23.  
    [Destination: host]
24.  
Bluetooth HCI H4
25.  
0x01)]
26.  
Type: HCI Event (0x04)
27.  
Bluetooth HCI Event - Synchronous Connection Complete
28.  
0x2c)
29.  
17
30.  
0x00)//成功
31.  
0x0004 //建立连接句柄
32.  
4e:ce (50:c9:71:83:4e:ce)
33.  
Type: eSCO connection (0x02)
34.  
12 slots (7.5 msec)
35.  
4 slots (2.5 msec)
36.  
60
37.  
60
38.  
3)
39.  
in frame: 1473]
40.  
in frame: 1474]
41.  
200.064ms]
42.  
201.225ms]

(4) 打电话,低功耗监听模式(Sniff Subrating)、呼吸模式(Sniff Mode)设置

android 实现蓝牙录音 安卓 蓝牙耳机录音_android_07

(5) 结束电话断开SCO连接

host->controller


Bluetooth
3.  
    [Source: host]
4.  
    [Destination: controller]
5.  
Bluetooth HCI H4
6.  
0x00)]
7.  
Type: HCI Command (0x01)
8.  
Bluetooth HCI Command - Disconnect
9.  
0x0406)
10.  
3
11.  
0x0004 //注意连接句柄和建立sco通道时候一致
12.  
0x13)
13.  
in frame: 1491]
14.  
4.262ms]
15.  
in frame: 1492]
16.  
97.828ms]
controlller->host
1.  
Frame 1491: 7 bytes on wire (56 bits), 7 bytes captured (56 bits)
2.  
Bluetooth
3.  
    [Source: controller]
4.  
    [Destination: host]
5.  
Bluetooth HCI H4
6.  
0x01)]
7.  
Event (0x04)
8.  
Bluetooth HCI Event - Command Status
9.  
Event Code: Command Status (0x0f)
10.  
4
11.  
0x00)
12.  
of Allowed Command Packets: 1
13.  
0x0406)
14.  
0000 01.. .... .... = Opcode Group Field: Link Control Commands (0x01)
15.  
.00 0000 0110 = Opcode Command Field: Disconnect (0x006)
16.  
in frame: 1490]
17.  
in frame: 1492]
18.  
4.262ms]
19.  
93.566ms]
20.  
Frame 1492: 7 bytes on wire (56 bits), 7 bytes captured (56 bits)
21.  
Bluetooth
22.  
    [Source: controller]
23.  
    [Destination: host]
24.  
Bluetooth HCI H4
25.  
0x01)]
26.  
Type: HCI Event (0x04)
27.  
Bluetooth HCI Event - Disconnect Complete
28.  
0x05) //断开连接成功
29.  
4
30.  
0x00)
31.  
0x0004
32.  
Local Host (0x16)
33.  
in frame: 1490]
34.  
in frame: 1491]
35.  
93.566ms]
36.  
97.828ms]

5.手机通过蓝牙耳机录音解决办法

经过查阅资料可以知道大部分手机并不支持蓝牙耳机录音功能,但我们在通话过程中使用蓝牙耳机的确可以正常输入语音的,那么可以推断想要通过蓝牙耳机录音是不是需要在录音APP中开启相应的服务支持。

其实经过上面的分析已经知道打电话之所以可以通过蓝牙输入和输出声音,实际上是通过建立SCO连接完成的,所以需要在APP代码内控制SCO连接。也就是说想要使用APP蓝牙录音,也要建立SCO连接。是不是确实建立成功可以通过蓝牙HCI log分析确定。

先来看Android 6.0蓝牙架构

蓝牙系统服务通过JNI与蓝牙协议栈,通过Binder IPC和应用进行通信。系统服务为开发人员提供了访问各种蓝牙配置文件的机会。

电话中是如何建立SCO连接的?

通过电话接通后,选择蓝牙音频输出入口

1.  
@Override
2.  
public boolean onMenuItemClick(MenuItem item) {
3.  
this, "- onMenuItemClick: " + item);
4.  
this, "  id: " + item.getItemId());
5.  
this, "  title: '" + item.getTitle() + "'");
6.   
7.  
        int mode = CallAudioState.ROUTE_WIRED_OR_EARPIECE;
8.   
9.  
        switch (item.getItemId()) {
10.  
            case R.id.audio_mode_speaker:
11.  
                mode = CallAudioState.ROUTE_SPEAKER;
12.  
break;
13.  
            case R.id.audio_mode_earpiece:
14.  
            case R.id.audio_mode_wired_headset:
15.  
// InCallCallAudioState.ROUTE_EARPIECE means either the handset earpiece,
16.  
// or the wired headset (if connected.)
17.  
                mode = CallAudioState.ROUTE_WIRED_OR_EARPIECE;
18.  
break;
19.  
            case R.id.audio_mode_bluetooth:
20.  
                mode = CallAudioState.ROUTE_BLUETOOTH;
21.  
break;
22.  
default:
23.  
this, "onMenuItemClick:  unexpected View ID " + item.getItemId()
24.  
" (MenuItem = '" + item + "')");
25.  
break;
26.  
        }
27.   
28.  
        getPresenter().setAudioMode(mode);
29.   
30.  
return true;
31.  
    }

看到了MVP模式中的P,通过点击菜单上不同的选项调用setAudioMode(mode),设置音频模式

packages/apps/InCallUI/src/com/android/incallui/CallButtonPresenter.java
1.  
public void setAudioMode(int mode) {
2.   
3.  
// TODO: Set a intermediate state in this presenter until we get
4.  
// an update for onAudioMode().  This will make UI response immediate
5.  
// if it turns out to be slow
6.   
7.  
this, "Sending new Audio Mode: " + CallAudioState.audioRouteToString(mode));
8.  
        TelecomAdapter.getInstance().setAudioRoute(mode);
9.  
    }

进入TelecomAdapter单例,设置音频路由,发现实际是调用InCallService的setAudioRoute(route)方法


if (mInCallService != null) {
3.  
            mInCallService.setAudioRoute(route);
4.  
else {
5.  
this, "error setAudioRoute, mInCallService is null");
6.  
        }
7.  
    }

实际是调用Phone的setAudioRoute(route)方法

frameworks/base/telecomm/java/android/telecom/InCallService.java
1.  
/**
2.  
is implemented by any app that wishes to provide the user-interface for managing
3.  
to this service while there exists a live (active or incoming) call,
4.  
and uses it to notify the in-call app of any live and recently disconnected calls. An app must
5.  
set as the default phone app (See {@link TelecomManager#getDefaultDialerPackage()})
6.  
to its {@code InCallService} implementation.
7.  
 * <p>
8.  
is an example manifest registration for an {@code InCallService}. The meta-data
9.  
 * ({@link TelecomManager#METADATA_IN_CALL_SERVICE_UI}) indicates that this particular
10.  
to replace the built-in in-call UI.
11.  
 * <pre>
12.  
 * {@code
13.  
"your.package.YourInCallServiceImplementation"
14.  
"android.permission.BIND_IN_CALL_SERVICE">
15.  
"android.telecom.IN_CALL_SERVICE_UI" android:value="true" />
16.  
filter>
17.  
"android.telecom.InCallService"/>
18.  
filter>
19.  
 * </service>
20.  
 * }
21.  
 * </pre>
22.  
 */
23.  
public abstract class InCallService extends Service {
24.  
    ...
25.  
    /**
26.  
request is honored, there will
27.  
to the {@link #getCallAudioState()}.
28.  
     *
29.  
to use.
30.  
     */
31.  
public final void setAudioRoute(int route) {
32.  
if (mPhone != null) {
33.  
            mPhone.setAudioRoute(route);
34.  
        }
35.  
    }
36.  
    ...
37.  
}
1.  
/**
2.  
     * Sets the audio route (speaker, bluetooth, etc...).  When this request is honored, there will
3.  
@link #getAudioState()}.
4.  
     *
5.  
@param route The audio route to use.
6.  
     */
7.  
public final void setAudioRoute(int route) {
8.  
        mInCallAdapter.setAudioRoute(route);
9.  
    }

实际是使用InCallAdapter的setAudioRoute(route)方法

1.  
/**
2.  
@link CallAudioState}.
3.  
     *
4.  
@param route The audio route to use.
5.  
     */
6.  
public void setAudioRoute(int route) {
7.  
try {
8.  
            mAdapter.setAudioRoute(route);
9.  
catch (RemoteException e) {
10.  
        }
11.  
    }

android.telecom.InCallAdapter实际使用了com.android.server.telecom.InCallAdapter的setAudioRoute(route)

1.  
/**
2.  
 * Internal remote callback interface for in-call services.
3.  
 *
4.  
@see android.telecom.InCallAdapter
5.  
 *
6.  
@hide}
7.  
 */
8.  
oneway interface IInCallAdapter {
9.  
    ...
10.   
11.  
void setAudioRoute(int route);
12.   
13.  
    ...
14.  
}
1.  
/**
2.  
call commands and updates from in-call app and passes them through to CallsManager.
3.  
class and passes it to the in-call app after
4.  
to it. This adapter can receive commands and updates until the in-call app is unbound.
5.  
 */
6.  
class InCallAdapter extends IInCallAdapter.Stub {
7.  
    ...
8.  
    @Override
9.  
public void setAudioRoute(int route) {
10.  
        long token = Binder.clearCallingIdentity();
11.  
        try {
12.  
            synchronized (mLock) {
13.  
                mCallsManager.setAudioRoute(route);
14.  
            }
15.  
        } finally {
16.  
            Binder.restoreCallingIdentity(token);
17.  
        }
18.  
    }
19.  
    ...
20.  
}
1.  
    /**
2.  
in-call UI to change the audio route, for example to change from earpiece to
3.  
      * speaker phone.
4.  
      */
5.  
int route) {
6.  
        mCallAudioManager.setAudioRoute(route);
7.  
    }
packages/services/Telecomm/src/com/android/server/telecom/CallAudioManager.java
1.  
/**
2.  
     * Changed the audio route, for example from earpiece to speaker phone.
3.  
     *
4.  
@param route The new audio route to use. See {@link CallAudioState}.
5.  
     */
6.  
void setAudioRoute(int route) {
7.  
// This can happen even when there are no calls and we don't have focus.
8.  
if (!hasFocus()) {
9.  
return;
10.  
        }
11.   
12.  
this, "setAudioRoute, route: %s", CallAudioState.audioRouteToString(route));
13.   
14.  
// Change ROUTE_WIRED_OR_EARPIECE to a single entry.
15.  
int newRoute = selectWiredOrEarpiece(route, mCallAudioState.getSupportedRouteMask());
16.   
17.  
// If route is unsupported, do nothing.
18.  
if ((mCallAudioState.getSupportedRouteMask() | newRoute) == 0) {
19.  
this, "Asking to set to a route that is unsupported: %d", newRoute);
20.  
return;
21.  
        }
22.   
23.  
if (mCallAudioState.getRoute() != newRoute) {
24.  
// Remember the new speaker state so it can be restored when the user plugs and unplugs
25.  
// a headset.
26.  
            mWasSpeakerOn = newRoute == CallAudioState.ROUTE_SPEAKER;
27.  
            setSystemAudioState(mCallAudioState.isMuted(), newRoute,
28.  
                    mCallAudioState.getSupportedRouteMask());
29.  
        }
30.  
    }
31.   
32.  
private void setSystemAudioState(boolean isMuted, int route, int supportedRouteMask) {
33.  
false /* force */, isMuted, route, supportedRouteMask);
34.  
    }
35.   
36.  
private void setSystemAudioState(
37.  
boolean force, boolean isMuted, int route, int supportedRouteMask) {
38.  
if (!hasFocus()) {
39.  
return;
40.  
        }
41.   
42.  
        CallAudioState oldAudioState = mCallAudioState;
43.  
new CallAudioState(isMuted, route, supportedRouteMask));
44.  
if (!force && Objects.equals(oldAudioState, mCallAudioState)) {
45.  
return;
46.  
        }
47.   
48.  
this, "setSystemAudioState: changing from %s to %s", oldAudioState, mCallAudioState);
49.  
        Log.event(mCallsManager.getForegroundCall(), Log.Events.AUDIO_ROUTE,
50.  
                CallAudioState.audioRouteToString(mCallAudioState.getRoute()));
51.   
52.  
        mAudioManagerHandler.obtainMessage(
53.  
                MSG_AUDIO_MANAGER_SET_MICROPHONE_MUTE,
54.  
1 : 0,
55.  
0)
56.  
                .sendToTarget();
57.   
58.  
// Audio route.
59.  
if (mCallAudioState.getRoute() == CallAudioState.ROUTE_BLUETOOTH) {
60.  
false);
61.  
true);
62.  
else if (mCallAudioState.getRoute() == CallAudioState.ROUTE_SPEAKER) {
63.  
false);
64.  
true);
65.  
else if (mCallAudioState.getRoute() == CallAudioState.ROUTE_EARPIECE ||
66.  
                mCallAudioState.getRoute() == CallAudioState.ROUTE_WIRED_HEADSET) {
67.  
false);
68.  
false);
69.  
        }
70.   
71.  
if (!oldAudioState.equals(mCallAudioState)) {
72.  
            mCallsManager.onCallAudioStateChanged(oldAudioState, mCallAudioState);
73.  
            updateAudioForForegroundCall();
74.  
        }
75.  
    }
•  
• 分析到这里看到了关于切换蓝牙输出的代码:
76.  
if (mCallAudioState.getRoute() == CallAudioState.ROUTE_BLUETOOTH) {
77.  
false);
78.  
true);
79.  
}

赶紧看看turnOnBluetooth(true)方法,这一定是打开蓝牙语音的代码

1.  
2.  
if (mBluetoothManager.isBluetoothAvailable()) {
3.  
            boolean isAlreadyOn = mBluetoothManager.isBluetoothAudioConnectedOrPending();
4.  
if (on != isAlreadyOn) {
5.  
this, "connecting bluetooth %s", on);
6.  
if (on) {
7.  
                    mBluetoothManager.connectBluetoothAudio();
8.  
else {
9.  
                    mBluetoothManager.disconnectBluetoothAudio();
10.  
                }
11.  
            }
12.  
        }
13.  
    }

先判断蓝牙设备是否存在,是否已经使用蓝牙设备作为输出,如果不是才进行切换。在此进入了BluetoothManager管辖范围

1.  
void connectBluetoothAudio() {
2.  
this, "connectBluetoothAudio()...");
3.  
if (mBluetoothHeadset != null) {
4.  
            mBluetoothHeadset.connectAudio();
5.  
        }
6.   
7.  
// Watch out: The bluetooth connection doesn't happen instantly;
8.  
// the connectAudio() call returns instantly but does its real
9.  
// work in another thread.  The mBluetoothConnectionPending flag
10.  
// is just a little trickery to ensure that the onscreen UI updates
11.  
// instantly. (See isBluetoothAudioConnectedOrPending() above.)
12.  
true;
13.  
        mBluetoothConnectionRequestTime = SystemClock.elapsedRealtime();
14.  
    }

这个方法实际是调用BluetoothHeadset对象的connectAudio()方法,启动一个蓝牙耳机连接,使用SCO信道,到此已经知道电话切换蓝牙音频输出确实是用蓝牙SCO信道实现的

1.  
    /**
2.  
     * Initiates a connection of headset audio.
3.  
with remote connected headset device.
4.  
     *
5.  
true if successful
6.  
false if there was some error such as
7.  
is no connected headset
8.  
     * @hide
9.  
     */
10.  
public boolean connectAudio() {
11.  
if (mService != null && isEnabled()) {
12.  
            try {
13.  
                return mService.connectAudio();
14.  
            } catch (RemoteException e) {
15.  
Log.e(TAG, e.toString());
16.  
            }
17.  
else {
18.  
Log.w(TAG, "Proxy not attached to service");
19.  
if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable()));
20.  
        }
21.  
false;
22.  
    }
1.  
/**
2.  
 * API for Bluetooth Headset service
3.  
 *
4.  
@hide}
5.  
 */
6.  
interface IBluetoothHeadset {
7.  
// Public API
8.  
    ...
9.  
boolean connectAudio();
10.  
    ...
11.  
}

BluetoothManager中调用connectBluetoothAudio(),实际上是远程调用HeadsetService服务中的connectAudio()

1.  
public boolean connectAudio() {  
2.  
    HeadsetService service = getService();  
3.  
if (service == null) return false;  
4.  
return service.connectAudio();  
5.  
}
6.  
    boolean connectAudio() {  
7.  
// TODO(BT) BLUETOOTH or BLUETOOTH_ADMIN permission  
8.  
"Need BLUETOOTH permission");  
9.  
if (!mStateMachine.isConnected()) {  
10.  
return false;  
11.  
         }  
12.  
if (mStateMachine.isAudioOn()) {  
13.  
return false;  
14.  
         }  
15.  
         mStateMachine.sendMessage(HeadsetStateMachine.CONNECT_AUDIO);  
16.  
return true;  
17.  
     }

先检查权限BLUETOOTH或者BLUETOOTH_ADMIN,然后判断连接状态,未连接和音频已经通过蓝牙输出都返回false,什么都没做。只有在已连接蓝牙耳机但还没使用蓝牙耳机作为输出的时候才去发出Message,从HeadsetStateMachine命名也可以知道它是状态机,当接收到CONNECT_AUDIO命令时就会将蓝牙状态切换为AudioOn

1.  
/**
2.  
 * Bluetooth Handset StateMachine
3.  
 *                      (Disconnected)
4.  
|    ^
5.  
| DISCONNECTED
6.  
 *                           V    |
7.  
 *                         (Pending)
8.  
|    ^
9.  
| CONNECT
10.  
 *                           V    |
11.  
 *                        (Connected)
12.  
|    ^
13.  
| DISCONNECT_AUDIO
14.  
 *                           V    |
15.  
 *                         (AudioOn)
16.  
/

从分发的消息分支很容易找到下面的方法

connectAudioNative(getByteAddress(device));

进入了Native层

private native boolean connectAudioNative(byte[] address);
1.  
static jboolean connectAudioNative(JNIEnv *env, jobject object, jbyteArray address) {
2.  
jbyte *addr;
3.  
bt_status_t status;
4.   
5.  
if (!sBluetoothHfpInterface) return JNI_FALSE;
6.   
7.  
addr = env->GetByteArrayElements(address, NULL);
8.  
if (!addr) {
9.  
jniThrowIOException(env, EINVAL);
10.  
return JNI_FALSE;
11.  
}
12.   
13.  
if ( (status = sBluetoothHfpInterface->connect_audio((bt_bdaddr_t *)addr)) !=
14.  
BT_STATUS_SUCCESS) {
15.  
ALOGE("Failed HF audio connection, status: %d", status);
16.  
}
17.  
env->ReleaseByteArrayElements(address, addr, 0);
18.  
return (status == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
19.  
}

分析到这里关键在sBluetoothHfpInterface->connect_audio((bt_bdaddr_t *)addr))这个方法调用,进入到了蓝牙协议栈

1.  
/*******************************************************************************
2.  
**
3.  
** Function connect_audio
4.  
**
5.  
** Description create an audio connection
6.  
**
7.  
** Returns bt_status_t
8.  
**
9.  
*******************************************************************************/
10.  
static bt_status_t connect_audio( bt_bdaddr_t *bd_addr )
11.  
{
12.  
CHECK_BTHF_INIT();
13.   
14.  
int idx = btif_hf_idx_by_bdaddr(bd_addr);
15.   
16.  
if ((idx < 0) || (idx >= BTIF_HF_NUM_CB))
17.  
{
18.  
BTIF_TRACE_ERROR("%s: Invalid index %d", __FUNCTION__, idx);
19.  
return BT_STATUS_FAIL;
20.  
}
21.   
22.  
/* Check if SLC is connected */
23.  
if (btif_hf_check_if_slc_connected() != BT_STATUS_SUCCESS)
24.  
return BT_STATUS_NOT_READY;
25.   
26.  
if (is_connected(bd_addr) && (idx != BTIF_HF_INVALID_IDX))
27.  
{
28.  
BTA_AgAudioOpen(btif_hf_cb[idx].handle);
29.   
30.  
/* Inform the application that the audio connection has been initiated successfully */
31.  
btif_transfer_context(btif_in_hf_generic_evt, BTIF_HFP_CB_AUDIO_CONNECTING,
32.  
(char *)bd_addr, sizeof(bt_bdaddr_t), NULL);
33.  
return BT_STATUS_SUCCESS;
34.  
}
35.   
36.  
return BT_STATUS_FAIL;
37.  
}
1.  
/*******************************************************************************
2.  
**
3.  
** Function BTA_AgAudioOpen
4.  
**
5.  
** Description Opens an audio connection to the currently connected
6.  
** headset or hnadsfree.
7.  
**
8.  
**
9.  
** Returns void
10.  
**
11.  
*******************************************************************************/
12.  
void BTA_AgAudioOpen(UINT16 handle)
13.  
{
14.  
BT_HDR *p_buf;
15.   
16.  
if ((p_buf = (BT_HDR *) GKI_getbuf(sizeof(BT_HDR))) != NULL)
17.  
{
18.  
p_buf->event = BTA_AG_API_AUDIO_OPEN_EVT;
19.  
p_buf->layer_specific = handle;
20.  
bta_sys_sendmsg(p_buf);
21.  
}
22.  
}
1.  
/* Define the header of each buffer used in the Bluetooth stack.*/
2.  
typedef struct
3.  
{
4.  
uint16_t event;
5.  
uint16_t len;
6.  
uint16_t offset;
7.  
uint16_t layer_specific;
8.  
uint8_t data[];
9.  
} BT_HDR;
1.  
/*******************************************************************************
2.  
**
3.  
** Function bta_sys_sendmsg
4.  
**
5.  
** Description Send a GKI message to BTA. This function is designed to
6.  
** optimize sending of messages to BTA. It is called by BTA
7.  
** API functions and call-in functions.
8.  
**
9.  
**
10.  
** Returns void
11.  
**
12.  
*******************************************************************************/
13.  
void bta_sys_sendmsg(void *p_msg)
14.  
{
15.  
// There is a race condition that occurs if the stack is shut down while
16.  
// there is a procedure in progress that can schedule a task via this
17.  
// message queue. This causes |btu_bta_msg_queue| to get cleaned up before
18.  
// it gets used here; hence we check for NULL before using it.
19.  
if (btu_bta_msg_queue)
20.  
fixed_queue_enqueue(btu_bta_msg_queue, p_msg);
21.  
}
• system/bt/osi/src/fixed_queue.c
22.  
void fixed_queue_enqueue(fixed_queue_t *queue, void *data) {
23.  
assert(queue != NULL);
24.  
assert(data != NULL);
25.   
26.  
semaphore_wait(queue->enqueue_sem);
27.   
28.  
pthread_mutex_lock(&queue->lock);
29.  
list_append(queue->list, data);
30.  
pthread_mutex_unlock(&queue->lock);
31.   
32.  
semaphore_post(queue->dequeue_sem);
33.  
}

后续进入到了linux内核,后续步骤可以猜得到,经过蓝牙驱动让蓝牙模块Host下发指令:Setup Synchronous Connection

APP建立SCO信道控制代码

实现蓝牙耳机录音功能

打开sco,关键代码:

1.  AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
2.  mAudioManager.startBluetoothSco();

关闭sco:

mAudioManager.stopBluetoothSco();

参考资料:

https://zhuanlan.zhihu.com/p/21943377

http://androidxref.com