转载请注明出处:http://blog.csdn.net/adits/article/details/8242146
开发环境简介
1. 主机系统: Unbuntu10.10
2. android系统版本: 4.0.3(Linux kernel 3.0.8)
综述
android的音频系统非常庞大复杂:涉及到java应用程序,java框架层,JNI,本地服务(AudioFlinger和AudioPolicyService),硬件抽象层HAL,ALSA-LIB和ALSA-DRIVER。
本文将先分析音频系统的启动与模块加载流程,并具体分析一个JAVA API的调用流程;最后在此基础上自然地为android系统添加USB AUDIO设备的放音和录音功能。
全文可分为如下几大部分:
1. 本地服务的启动流程分析。
1.1 AudioFlinger启动流程及其所涉及的HAL层模块启动流程分析。
1.2 AudioPolicyService启动流程及其所涉及的HAL层模块启动流程分析。
2. JAVA API setDeviceConnectionState()调用流程详解,同时为android系统添加USB AUDIO设备的放音和录音功能。
3. ALSA-LIB浅述以及asound.conf配置文件的书写。
4. 重新获取USB AUDIO设备的硬件参数。
详述
1. 本地服务的启动流程分析。
AudioFlinger和AudioPolicyService两大音频服务都是在android系统启动时就启动的。
当linux kenerl启动完成后,会启动android的init进程(system/core/init/init.c)。
-
"font-size:24px;">int main(int argc, char **argv)
-
{
-
.....
-
-
init_parse_config_file("/color:#ff0000;">init.rc");
-
-
.....
-
}
init.rc文件中保存了许多系统启动时需要启动的服务。其中就有多媒体服务mediaserver的启动:
-
service media /system/bin/mediaserver
此服务在文件frameworks/base/media/mediaserver/main_mediaserver.cpp中定义,而音频子系统的两大本地服务AudioFlinger和AudioPolicyService就是在此启动的。
-
"" style="font-size:24px;">int main(int argc, char** argv)
-
{
-
.....
-
-
"color:#ff0000;">AudioFlinger::instantiate(); "color:#3333ff;">
-
.....
-
-
"color:#ff0000;">AudioPolicyService::instantiate(); "color:#3333ff;">
-
-
.....
-
}
1.1 AudioFlinger启动流程及其所涉及的HAL层模块启动流程分析。
根据上文分析,将调用AudioFlinger::instantiate()函数实例化AudioFlinger。但是AudioFlinger.cpp中并没有找到此函数,那必然在其父类中。AudioFlinger类有很多父类,一时难以确定instantiate()到底在哪个父类中定义的。直接搜索吧!
grep -rn "instantiate" frameworks/base/
很快找到instantiate()函数的定义处在./frameworks/base/include/binder/BinderService.h头文件中
-
"" style="font-size:24px;">template<typename SERVICE>
-
class BinderService
-
{
-
public:
-
static status_t publish() {
-
sp sm(defaultServiceManager());
-
return sm->addService(String16("color:#ff0000;">SERVICE::getServiceName()), "color:#ff0000;">new SERVICE());
-
-
......
-
-
static void instantiate() { publish(); }
-
-
.....
-
}
-
}
这里用到了模板,需要确定SERVICE是什么东东。
AudioFlinger类是在AudioFlinger.h中定义的,而恰好包含了头文件BinderService.h。
-
"" style="font-size:24px;">class AudioFlinger :
-
public "color:#ff0000;">BinderService,
-
public BnAudioFlinger
-
{
-
friend class BinderService;
-
public:
-
static char const* getServiceName() { return "media.audio_flinger"; }
-
-
.....
-
-
}
原来AudioFlinger类继承了BinderService类,同时把自己(AudioFlinger)传递给SERVICE。而addService函数第一个参数调用了AudioFlinger类的静态成员函数getServiceName()获取AudioFlinger的服务名称;其第二个参数便是创建了一个AudioFlinger的实例。至此,明白了实例化函数instantiate()就是要向服务管理器注册的服务是AudioFlinger。
既然此时实例化了AudioFlinger,那么看看AudioFlinger类的构造函数具体做了哪些初始化工作。
-
"" style="font-size:24px;">AudioFlinger::AudioFlinger()
-
: BnAudioFlinger(),
-
mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
-
mBtNrecIsOff(false)
-
{
-
}
此构造函数做了一些无关紧要的事情,不管它。既然AudioFlinger服务是第一次启动,则将调到函数AudioFlinger::onFirstRef(至于为什么,我还没有搞明白,可以通过log信息确信确实是这么回事)。
void AudioFlinger::onFirstRef()
{
......
for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
const hw_module_t *mod;
audio_hw_device_t *dev;
rc = load_audio_interface(audio_interfaces[i], &mod,&dev);
.....
mAudioHwDevs.push(dev); // 把通过load_audio_interface()函数获得的设备存入元素为audio_hw_device_t
// 类型的模板变量mAudioHwDevs中
.....
}
看到load_audio_interface()函数的名字,知晓,应当是加载音频接口的。
-
"font-size:24px;">static int load_audio_interface(const char *if_name, const hw_module_t **mod,
-
audio_hw_device_t **dev)
-
{
-
......
-
-
rc = "color:#ff0000;">hw_get_module_by_class("color:#ff0000;">AUDIO_HARDWARE_MODULE_ID, if_name, mod);
-
if (rc)
-
goto out;
-
-
rc = "color:#ff0000;">audio_hw_device_open(*mod, "color:#ff0000;">dev);
-
-
.....
-
-
}
首先通过函数hw_get_module_by_class获取ID号为AUDIO_HARDWARE_MODULE_ID的音频模块,此ID在头文件hardware/libhardware/include/hardware/audio.h中定义。此头文件中定义了一个十分重要的结构体struct audio_hw_device,其中包含了许多函数接口(函数指针):
-
"font-size:24px;">struct audio_hw_device {
-
struct hw_device_t common;
-
-
-
-
-
-
-
-
uint32_t (*"color:#ff0000;">get_supported_devices)(const struct audio_hw_device *dev);
-
-
-
-
-
-
int (*"color:#ff0000;">init_check)(const struct audio_hw_device *dev);
-
-
......
-
-
-
int (*"color:#ff0000;">set_parameters)(struct audio_hw_device *dev, const char *kv_pairs);
-
-
.....
-
-
-
int (*"color:#ff0000;">open_output_stream)(struct audio_hw_device *dev, uint32_t devices,
-
int *format, uint32_t *channels,
-
uint32_t *sample_rate,
-
struct audio_stream_out **out);
-
-
......
-
-
-
int (*open_input_stream)(struct audio_hw_device *dev, uint32_t devices,
-
int *format, uint32_t *channels,
-
uint32_t *sample_rate,
-
audio_in_acoustics_t acoustics,
-
struct audio_stream_in **stream_in);
-
-
.....
-
}
ID为AUDIO_HARDWARE_MODULE_ID的音频模块到底在哪儿定义的那?既然是HAL层模块,必定在hardware目录下定义的
-
$ grep -rn AUDIO_HARDWARE_MODULE_ID hardware/
-
hardware/libhardware_legacy/audio/audio_hw_hal.cpp:602:id: AUDIO_HARDWARE_MODULE_ID,
-
hardware/libhardware/modules/audio/audio_hw.c:435: .id = AUDIO_HARDWARE_MODULE_ID,
-
hardware/libhardware/include/hardware/audio.h:37:
-
#define AUDIO_HARDWARE_MODULE_ID "audio"
从搜索结果发现,AUDIO_HARDWARE_MODULE_ID的音频模块有两处定义,具体用的是哪一个那?
先分析下这两个模块最终编译进哪些模块。
通过查阅Android.mk晓得,audio_hw.c先被编译进audio_policy.stub模块,而后被编译进libhardware模块;
同样的,audio_hw_hal.cpp先被编译进libaudiopolicy_legacy模块,而后被编译进libhardware_legacy模块;
而libhardware和libhardware_legacy模块都在audioFlinger中用到。
通过log信息,确认使用的是libaudiopolicy_legacy模块,即具体调到hardware/libhardware_legacy/audio/audio_hw_hal.cpp文件中所定义的模块了。
在获取到HAL层音频模块后,接下来执行audio_hw_device_open()函数,打开设备。此函数也在audio.h头文件中定义,函数体如下:
-
"font-size:24px;">
-
-
static inline int audio_hw_device_open(const struct hw_module_t* module,
-
struct audio_hw_device** device)
-
{
-
return module->methods->open(module, AUDIO_HARDWARE_INTERFACE,
-
(struct hw_device_t**)device);
-
}
struct hw_module_t是在hardware/libhardware/include/hardware/hardware.h头文件中定义的,其中嵌套了struct hw_module_methods_t。此结构体很简单,只有一个函数指针open
-
"font-size:24px;">typedef struct hw_module_methods_t {
-
-
int (*open)(const struct hw_module_t* module, const char* id,
-
struct hw_device_t** device);
-
-
} hw_module_methods_t;
在确定具体模块后,很容易确定open函数指针的具体实现
-
"font-size:24px;">struct legacy_audio_module HAL_MODULE_INFO_SYM = {
-
module: {
-
common: {
-
tag: HARDWARE_MODULE_TAG,
-
version_major: 1,
-
version_minor: 0,
-
id: AUDIO_HARDWARE_MODULE_ID,
-
name: "LEGACY Audio HW HAL",
-
author: "The Android Open Source Project",
-
methods: &"color:#ff0000;">legacy_audio_module_methods,
-
dso : NULL,
-
reserved : {0},
-
},
-
},
-
};
-
"font-size:24px;">static struct hw_module_methods_t legacy_audio_module_methods = {
-
open: "color:#ff0000;">legacy_adev_open
-
};
open()的实现就是legacy_adev_open()函数了!
-
"font-size:24px;">static int legacy_adev_open(const hw_module_t* module, const char* name,
-
hw_device_t** device)
-
{
-
struct legacy_audio_device *ladev;
-
int ret;
-
-
if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)
-
return -EINVAL;
-
-
.....
-
-
ladev->device.get_supported_devices = adev_get_supported_devices;
-
ladev->device.init_check = "color:#ff0000;">adev_init_check;
-
-
.....
-
-
ladev->device.open_output_stream = "color:#ff0000;">adev_open_output_stream;
-
ladev->device.close_output_stream = adev_close_output_stream;
-
ladev->device.open_input_stream = adev_open_input_stream;
-
ladev->device.close_input_stream = adev_close_input_stream;
-
-
.....
-
-
ladev->hwif = "color:#ff0000;">createAudioHardware();
-
-
.....
-
"color:#ff0000;">*device = &ladev->device.common; "color:#3333ff;">
-
-
-
-
return 0;
-
}
这里主要做了一些初始化工作,即给函数指针提供具体实现函数;但createAudioHardware()应该做了更多的事情。
先从函数createAudioHardware()的返回值入手。struct legacy_audio_device的定义如下:
-
"font-size:24px;">struct legacy_audio_device {
-
struct audio_hw_device device;
-
-
struct AudioHardwareInterface *hwif;
-
};
原来createAudioHardware()的返回值是一个硬件设备接口AudioHardwareInterface。
类AudioHardwareInterface正好在audio_hw_hal.cpp文件中所包含的头文件hardware_legacy/AudioHardwareInterface.h中定义的虚类(结构体能调到类,还是头一遭见到,虽然结构体和类长得很象)。那么我很想知道createAudioHardware()具体做了哪些事情。
首先需要确定函数createAudioHardware()的定义在哪儿?有几处定义?调用的具体是哪一个?
AudioHardwareInterface.h头文件中对createAudioHardware函数的声明,没有包含在任何类中,而仅仅包含在名字空间android_audio_legacy中,这和audio_hw_hal.cpp同在一个名字空间中。
-
"font-size:24px;">namespace android_audio_legacy {
-
-
.....
-
-
extern "C" AudioHardwareInterface* createAudioHardware(void);
-
};
经搜索,发现createAudioHardware()函数有四处定义。
-
"font-size:24px;">$ grep -rn createAudioHardware hardware/ --exclude-dir=.svn
-
hardware/alsa_sound/AudioHardwareALSA.cpp:45:
-
android_audio_legacy::AudioHardwareInterface *createAudioHardware(void) {
-
hardware/msm7k/libaudio-qsd8k/AudioHardware.cpp:2021:
-
extern "C" AudioHardwareInterface* createAudioHardware(void) {
-
hardware/msm7k/libaudio-qdsp5v2/AudioHardware.cpp:337:
-
extern "C" AudioHardwareInterface* createAudioHardware(void) {
-
hardware/msm7k/libaudio/AudioHardware.cpp:1132:
-
extern "C" AudioHardwareInterface* createAudioHardware(void) {
只有AudioHardwareALSA.cpp文件中包含了头文件hardware_legacy/AudioHardwareInterface.h,并且返回值是android_audio_legacy名字空间的AudioHardwareInterface类对象。则createAudioHardware函数的具体实现很可能是它了,通过log信息证明了这一点。
进入AudioHardwareALSA.cpp,不难看出,此函数,最后会通过执行代码如下代码创建AudioHardwareALSA类对象。
-
"font-size:24px;">return new AudioHardwareALSA();
AudioHardwareALSA类的构造函数如下:
-
"" style="font-size:24px;">AudioHardwareALSA::AudioHardwareALSA() :
-
mALSADevice(0),
-
mAcousticDevice(0)
-
{
-
......
-
-
int err = "color:#ff0000;">hw_get_module("color:#ff0000;">ALSA_HARDWARE_MODULE_ID,
-
(hw_module_t const**)"color:#ff0000;">&module);
-
-
if (err == 0) {
-
hw_device_t* device;
-
err = "color:#ff0000;">module->methods->open(module, "color:#ff0000;">ALSA_HARDWARE_NAME, &device);
-
if (err == 0) {
-
mALSADevice = (alsa_device_t *)device;
-
"color:#ff0000;">mALSADevice->init("color:#ff0000;">mALSADevice, "color:#ff0000;">mDeviceList);
-
-
.....
-
-
err = hw_get_module(ACOUSTICS_HARDWARE_MODULE_ID,
-
(hw_module_t const**)&module);
-
-
if (err == 0) {
-
hw_device_t* device;
-
err = module->methods->open(module, ACOUSTICS_HARDWARE_NAME, &device);
-
-
.....
-
}
宏ALSA_HARDWARE_MODULE_ID是在头文件hardware/alsa_sound/AudioHardwareALSA.h中定义的。
模块所对应的结构体类型为hw_module_t,在头文件hardware/libhardware/include/hardware/hardware.h中定义。
在构造函数中,首先调用函数hw_get_module()获取ID为ALSA_HARDWARE_MODULE_ID的ALSA硬件模块,看来即将进入庞大而又功能强大的ALSA音频子系统了!
经过搜索,很快确定ID为ALSA_HARDWARE_MODULE_ID的ALSA硬件抽象层的具体实现在文件hardware/alsa_sound/alsa_default.cpp中。
-
"" style="font-size:24px;">$ grep -rn ALSA_HARDWARE_MODULE_ID hardware/ --exclude-dir=.svn
-
hardware/alsa_sound/AudioHardwareALSA.h:39:#define ALSA_HARDWARE_MODULE_ID "alsa"
-
hardware/alsa_sound/alsa_default.cpp:59:
-
id : ALSA_HARDWARE_MODULE_ID,
-
hardware/alsa_sound/AudioHardwareALSA.cpp:150:
-
int err = hw_get_module(ALSA_HARDWARE_MODULE_ID,
则很快找到此模块的具体内容如下:
-
"" style="font-size:24px;">extern "C" const hw_module_t HAL_MODULE_INFO_SYM = {
-
tag : HARDWARE_MODULE_TAG,
-
version_major : 1,
-
version_minor : 0,
-
id : ALSA_HARDWARE_MODULE_ID,
-
name : "ALSA module",
-
author : "Wind River",
-
methods : &"color:#ff0000;">s_module_methods,
-
dso : 0,
-
reserved : { 0, },
-
};
s_module_methods函数的实现如下:
-
"" style="font-size:24px;">static hw_module_methods_t s_module_methods = {
-
open : s_device_open
-
};
s_device_open函数的实现如下:
-
"" style="font-size:24px;">static int s_device_open(const hw_module_t* module, const char* name, "color:#3333ff;">//有些困惑,
-
-
hw_device_t** device) "color:#3333ff;">"background-color: rgb(255, 255, 255);">
-
{
-
alsa_device_t *dev;
-
dev = (alsa_device_t *) malloc(sizeof(*dev));
-
if (!dev) return -ENOMEM;
-
-
memset(dev, 0, sizeof(*dev));
-
-
-
dev->common.tag = HARDWARE_DEVICE_TAG;
-
dev->common.version = 0;
-
dev->common.module = (hw_module_t *) module;
-
dev->common.close = s_device_close;
-
dev->init = "color:#ff0000;">s_init;
-
dev->open = "color:#ff0000;">s_open;
-
dev->close = s_close;
-
dev->route = "color:#ff0000;">s_route;
-
-
"color:#ff0000;">*device = &dev->common; "color:#3333ff;">
-
return 0;
-
}
经过上述分析,知道了module->methods->open函数具体调用流程了。
然后对ALSA硬件抽象层模块做了初始化的工作。
这里用到一个结构体变量mALSADevice,它在头文件hardware/alsa_sound/AudioHardwareALSA.h中定义的struct alsa_device_t变量。
-
"" style="font-size:24px;">struct alsa_device_t {
-
hw_device_t common;
-
-
status_t (*init)(alsa_device_t *, ALSAHandleList &);
-
status_t (*open)(alsa_handle_t *, uint32_t, int);
-
status_t (*close)(alsa_handle_t *);
-
status_t (*route)(alsa_handle_t *, uint32_t, int);
-
};
此结构体仅仅提供了一些函数调用接口,在这里都有了具体的实现。则mALSADevice->init()将调到s_init()函数中。
-
"" style="font-size:24px;">static status_t s_init(alsa_device_t *module, "color:#ff0000;">ALSAHandleList &list)
-
{
-
list.clear();
-
-
snd_pcm_uframes_t bufferSize = "color:#ff0000;">_defaultsOut.bufferSize;
-
-
for (size_t i = 1; (bufferSize & ~i) != 0; i <<= 1)
-
bufferSize &= ~i;
-
-
_defaultsOut.module = module;
-
_defaultsOut.bufferSize = bufferSize;
-
-
"color:#ff0000;">list.push_back(_defaultsOut);
-
-
bufferSize = "color:#ff0000;">_defaultsIn.bufferSize;
-
-
.....
-
-
"color:#ff0000;">list.push_back(_defaultsIn);
-
-
.....
-
}
这里会把_defaultsOut和_defaultsIn东东保存在ALSA句柄列表ALSAHandleList中。
首先需要明确_defaultsOut和_defaultsIn具体是什么东东。
-
"" style="font-size:24px;">static alsa_handle_t _defaultsOut = {
-
module : 0,
-
devices : android_audio_legacy::AudioSystem::DEVICE_OUT_ALL, "color:#3333ff;">
-
-
curDev : 0,
-
curMode : 0,
-
handle : 0, "color:#3333ff;">
-
format : SND_PCM_FORMAT_S16_LE,
-
channels : 2,
-
sampleRate : DEFAULT_SAMPLE_RATE,
-
latency : 200000,
-
bufferSize : DEFAULT_SAMPLE_RATE / 5,
-
modPrivate : 0,
-
};
-
-
static alsa_handle_t _defaultsIn = {
-
module : 0,
-
devices : android_audio_legacy::AudioSystem::DEVICE_IN_ALL, "color:#3333ff;">
-
-
curDev : 0,
-
curMode : 0,
-
handle : 0, "color:#3333ff;">
-
format : SND_PCM_FORMAT_S16_LE,
-
channels : 2, "color:#3333ff;">
-
-
sampleRate : DEFAULT_SAMPLE_RATE, "color:#3333ff;">
-
-
"color:#000000;">latency : 250000,
-
bufferSize : 2048,
-
modPrivate : 0,
-
};
那ALSAHandleList又是什么东东?
ALSAHandleList在头文件hardware/alsa_sound/AudioHardwareALSA.h中定义的List模板变量。
typedef List ALSAHandleList;
原来就是struct asla_handle_t的一个列表而已,而_defaultsOut和_defaultsIn正是这样的结构体变量。
-
"" style="font-size:24px;">struct alsa_handle_t {
-
alsa_device_t * module;
-
uint32_t devices;
-
uint32_t curDev;
-
int curMode;
-
snd_pcm_t * handle; "color:#3333ff;">
-
snd_pcm_format_t format;
-
"color:#ff0000;"> uint32_t channels;
-
uint32_t sampleRate;
-
unsigned int latency;
-
unsigned int bufferSize;
-
void * modPrivate;
-
};
ALSA硬件抽象层正是这样获得了输出音频通道和输入音频通道的相关初始化硬件参数,以后在使用中并不试图改变这些硬件参数(针对真能手机和平板来说,也却是不需要改变)。因此,在扩展android系统功能,为其添加对USB AUDIO设备的支持时,就不得不考虑时事改变channels和sampleRate这两个硬件参数的值。
至此,AudioFlinger服务首次启动过程分析完毕!
1.2 AudioPolicyService启动流程及其所涉及的HAL层模块启动流程分析。
AudioPolicyService服务的启动流程类似于AudioFlinger服务的启动过程,将简要分析。
先看下AudioPolicyService类的定义(AudioPolicyService.h)(提供此类的定义,主要是为下面instantiate()函数服务的):
-
"" style="font-size:24px;">class AudioPolicyService :
-
public "color:#ff0000;">BinderService, "color:#3333ff;">
-
-
-
public BnAudioPolicyService,
-
-
public IBinder::DeathRecipient
-
{
-
friend class BinderService;
-
-
public:
-
-
static const char *"color:#ff0000;">getServiceName() { return "media.audio_policy"; }
-
-
.....
-
}
根据前面的分析,晓得将通过调用如下代码启动AudioPolicyService服务。
-
"" style="font-size:24px;">AudioPolicyService::instantiate();
此代码最后将调到AudioPolicyService类的构造函数
-
"" style="font-size:24px;">AudioPolicyService::AudioPolicyService()
-
: BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)
-
{
-
char value[PROPERTY_VALUE_MAX];
-
const struct hw_module_t *module;
-
int forced_val;
-
int rc;
-
-
Mutex::Autolock _l(mLock);
-
-
-
mTonePlaybackThread = new AudioCommandThread(String8(""));
-
-
mAudioCommandThread = new "color:#ff0000;">AudioCommandThread(String8("ApmCommandThread"));
-
-
-
rc = "color:#ff0000;">hw_get_module("color:#ff0000;">AUDIO_POLICY_HARDWARE_MODULE_ID, &module);
-
if (rc)
-
return;
-
-
rc = "color:#ff0000;">audio_policy_dev_open(module, "color:#ff0000;">&mpAudioPolicyDev);
-
LOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));
-
if (rc)
-
return;
-
-
rc = "color:#ff0000;">mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, "background-color: rgb(192, 192, 192);">"color:#ff0000;">&aps_ops, this,
-
"color:#ff0000;">&mpAudioPolicy);
-
LOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));
-
if (rc)
-
return;
-
-
rc = "color:#ff0000;">mpAudioPolicy->init_check(mpAudioPolicy);
-
-
.....
-
-
}
(1)首先开启了放音线程和音频命令线程。这些工作都是通过创建AudioCommandThread线程类对象完成。
AudioCommandThread类在头文件frameworks/base/services/audioflinger/AudioPolicyService.h中定义
-
"" style="font-size:24px;">class AudioCommandThread : public Thread {
是AudioPolicyService类的私有子类。
AudioCommandThread线程类创建了对象后,将进入死循环中,等待要处理的事件传来。
-
"" style="font-size:24px;">bool AudioPolicyService::AudioCommandThread::threadLoop()
-
{
-
nsecs_t waitTime = INT64_MAX;
-
-
mLock.lock();
-
while (!exitPending())
-
{
-
while(!mAudioCommands.isEmpty()) {
-
.....
-
-
switch (command->mCommand) {
-
-
.....
-
-
"color:#ff0000;">case SET_PARAMETERS: {
-
ParametersData *data = (ParametersData *)command->mParam;
-
LOGV("AudioCommandThread() processing set parameters string %s, io %d",
-
data->mKeyValuePairs.string(), data->mIO);
-
command->mStatus = "color:#ff0000;">AudioSystem::setParameters(data->mIO, data->mKeyValuePairs);
-
if (command->mWaitStatus) {
-
command->mCond.signal();
-
mWaitWorkCV.wait(mLock);
-
}
-
delete data;
-
}break;
-
-
.....
-
}
这里只列出了switch语句中的一种情况的处理代码,因为后面分析setDeviceConnectionState()函数的调用流程时将用到。
当command->mCommand值为SET_PARAMETERS时,将调用libmedia库(frameworks/base/media/libmedia/AudioSystem.cpp)中的函数setParameters()做进一步处理。
(2)然后调用函数hw_get_module()获得ID号为AUDIO_POLICY_HARDWARE_MODULE_ID的硬件抽象层的音频策略模块。宏AUDIO_POLICY_HARDWARE_MODULE_ID在头文件hardware/libhardware/include/hardware/audio_policy.h中定义。
ID号为AUDIO_POLICY_HARDWARE_MODULE_ID的模块也有两处具体实现,同样通过log信息,确认调用的是libhardware_legacy模块中的AUDIO_POLICY_HARDWARE_MODULE_ID子模块的具体实现。
-
"" style="font-size:24px;">$ grep -rn AUDIO_POLICY_HARDWARE_MODULE_ID hardware/ --exclude-dir=.svn
-
hardware/libhardware_legacy/audio/audio_policy_hal.cpp:414:
-
id: AUDIO_POLICY_HARDWARE_MODULE_ID,
-
hardware/libhardware/modules/audio/audio_policy.c:318:
-
.id = AUDIO_POLICY_HARDWARE_MODULE_ID,
audio_policy_hal.cpp文件中定义的AUDIO_POLICY_HARDWARE_MODULE_ID模块如下:
struct legacy_ap_module HAL_MODULE_INFO_SYM = {
module: {
common: {
tag: HARDWARE_MODULE_TAG,
version_major: 1,
version_minor: 0,
id: AUDIO_POLICY_HARDWARE_MODULE_ID,
name: "LEGACY Audio Policy HAL",
author: "The Android Open Source Project",
methods: &legacy_ap_module_methods,
dso : NULL,
reserved : {0},
},
},
};
(3)再然后调用audio_policy_dev_open()函数(在头文件hardware/libhardware/include/hardware/audio_policy.h中定义)。
首先分析函数参数:第一个参数就是上面获取的模块,第二个参数mpAudioPolicyDev是struct audio_policy_device 指针变量,在头文件AudioPolicyService.h中定义。而struct audio_policy_device是在头文件audio_policy.h中定义的。
-
"" style="font-size:24px;">struct audio_policy_device {
-
struct hw_device_t common;
-
-
int (*create_audio_policy)(const struct audio_policy_device *device,
-
struct audio_policy_service_ops "color:#ff0000;background-color: rgb(153, 153, 153);">*aps_ops,
-
void *service,
-
struct audio_policy **ap);
-
.....
-
}
最后看下audio_policy_dev_open()函数的实现
-
"" style="font-size:24px;">"" style="">
-
-
static inline int audio_policy_dev_open(const hw_module_t* module,
-
struct audio_policy_device** device)
-
{
-
return module->methods->open(module, AUDIO_POLICY_INTERFACE,
-
(hw_device_t**)device);
-
}
由上述分析可知,open函数指针就指向legacy_ap_dev_open()函数。
-
"" style="">"" style="">static int legacy_ap_dev_open(const hw_module_t* module, const char* name,
-
hw_device_t** device) "color:#3333ff;">
-
{
-
struct legacy_ap_device *dev;
-
-
if (strcmp(name, AUDIO_POLICY_INTERFACE) != 0)"color:#3333ff;">
-
-
return -EINVAL;
-
-
dev = (struct legacy_ap_device *)calloc(1, sizeof(*dev));
-
if (!dev)
-
return -ENOMEM;
-
-
dev->device.common.tag = HARDWARE_DEVICE_TAG;
-
dev->device.common.version = 0;
-
dev->device.common.module = const_cast(module);
-
dev->device.common.close = legacy_ap_dev_close;
-
dev->device.create_audio_policy = "color:#ff0000;">create_legacy_ap;
-
dev->device.destroy_audio_policy = destroy_legacy_ap;
-
-
"color:#ff0000;">*device = &dev->device.common; "color:#3333ff;">
-
-
return 0;
-
}
(4)再接下来调用的mpAudioPolicyDev->create_audio_policy()函数指针具体就是create_legacy_ap()。
第二个参数&aps_ops是struct audio_policy_service_ops变量,是APS(AudioPolicyService)的操作接口,并且传递的是aps_ops的地址,则被调用者使用的将是在APS中函数接口的实现。
-
"" style="">"" style="">namespace {
-
struct audio_policy_service_ops aps_ops = {
-
"color:#ff0000;">open_output : aps_open_output,
-
open_duplicate_output : aps_open_dup_output,
-
close_output : aps_close_output,
-
suspend_output : aps_suspend_output,
-
restore_output : aps_restore_output,
-
open_input : aps_open_input,
-
close_input : aps_close_input,
-
set_stream_volume : aps_set_stream_volume,
-
set_stream_output : aps_set_stream_output,
-
"color:#ff0000;">set_parameters : aps_set_parameters,
-
get_parameters : aps_get_parameters,
-
start_tone : aps_start_tone,
-
stop_tone : aps_stop_tone,
-
set_voice_volume : aps_set_voice_volume,
-
move_effects : aps_move_effects,
-
};
-
};
struct audio_policy_service_ops在头文件hardware/libhardware/include/hardware/audio_policy.h中定义,是包含音频相关控制函数的接口。可见aps_ops接口将为HAL层提供服务。
第四个参数是&mpAudioPolicy。mpAudioPolicy是struct audio_policy的指针变量(AudioPolicyService.h)。而struct audio_policy也是在audio_policy.h中定义,将要用到的接口如下:
-
"" style="">"" style="">struct audio_policy {
-
-
-
-
-
-
int (*set_device_connection_state)(struct audio_policy *pol,
-
audio_devices_t device,
-
audio_policy_dev_state_t state,
-
const char *device_address);
-
-
.....
-
-
-
int (*init_check)(const struct audio_policy *pol);
-
-
.....
-
}
接下来看看create_audio_policy()函数指针的具体实现:
-
"" style="">"" style="">static int create_legacy_ap(const struct audio_policy_device *device,
-
struct audio_policy_service_ops *aps_ops,
-
void *service,
-
struct audio_policy **ap)
-
{
-
struct legacy_audio_policy *lap;
-
int ret;
-
-
if (!service || !aps_ops)
-
return -EINVAL;
-
-
lap = (struct legacy_audio_policy *)calloc(1, sizeof(*lap));
-
if (!lap)
-
return -ENOMEM;
-
-
lap->policy.set_device_connection_state = "color:#ff0000;">ap_set_device_connection_state;
-
-
......
-
-
lap->policy.init_check = ap_init_check;
-
lap->policy.get_output = ap_get_output;
-
lap->policy.start_output = ap_start_output;
-
lap->policy.stop_output = ap_stop_output;
-
lap->policy.release_output = ap_release_output;
-
lap->policy.get_input = ap_get_input;
-
lap->policy.start_input = "color:#ff0000;">ap_start_input;
-
lap->policy.stop_input = ap_stop_input;
-
lap->policy.release_input = ap_release_input;
-
-
.....
-
"color:#ff0000;">
-
lap->service = service; "color:#3333ff;">
-
lap->aps_ops = aps_ops; "color:#3333ff;">
-
lap->service_client =
-
new AudioPolicyCompatClient(aps_ops, service);
-
if (!lap->service_client) {
-
ret = -ENOMEM;
-
goto err_new_compat_client;
-
}
-
"color:#ff0000;">
-
lap->apm = createAudioPolicyManager(lap->service_client);
-
-
......
-
-
"color:#ff0000;">*ap = &lap->policy; "color:#3333ff;">
-
-
......
-
}
此函数中创建了重要对象:AudioPolicyCompatClient类对象和createAudioPolicyManager函数创建音频策略管理器,需要分析下。
先分析AudioPolicyCompatClient类对象的创建。此类在头文件hardware/libhardware_legacy/audio/AudioPolicyCompatClient.h中定义。
-
"" style="">"" style="">namespace android_audio_legacy {
-
class AudioPolicyCompatClient : public AudioPolicyClientInterface {
-
"color:#3333ff;">
-
-
-
public:
-
AudioPolicyCompatClient(struct audio_policy_service_ops *serviceOps,
-
void *service) :
-
"color:#ff0000;">mServiceOps(serviceOps) , mService(service) {} "color:#3333ff;">
-
-
-
......
-
-
private:
-
struct audio_policy_service_ops* mServiceOps;
-
void* mService;
-
-
......
-
}
此构造函数主要初始化两个私有化变量mServiceOps和mService,并把创建的对象作为函数createAudioPolicyManager的唯一参数,来创建音频策略管理器。
然而,函数createAudioPolicyManager有多个定义,搜索结果如下:
-
"" style="">"" style="">$ grep -rn createAudioPolicyManager hardware/ --exclude-dir=.svn
-
hardware/alsa_sound/AudioPolicyManagerALSA.cpp:31:
-
extern "C" android_audio_legacy::AudioPolicyInterface*
-
createAudioPolicyManager(
-
android_audio_legacy::AudioPolicyClientInterface *clientInterface)
-
hardware/libhardware_legacy/audio/AudioPolicyManagerDefault.cpp:24:
-
extern "C" AudioPolicyInterface*
-
createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
-
hardware/msm7k/libaudio-qsd8k/AudioPolicyManager.cpp:39:
-
extern "C" AudioPolicyInterface*
-
createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
-
hardware/msm7k/libaudio-qdsp5v2/AudioPolicyManager.cpp:39:
-
extern "C" AudioPolicyInterface*
-
createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
-
hardware/msm7k/libaudio/AudioPolicyManager.cpp:35:
-
extern "C" AudioPolicyInterface*
-
createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
函数createAudioPolicyManager虽然有多个定义,但是它们最后将创建AudioPolicyManagerBase类对象,以AudioPolicyManagerALSA类为例分析
-
"" style="">"" style="">AudioPolicyManagerALSA::AudioPolicyManagerALSA(
-
android_audio_legacy::AudioPolicyClientInterface *"color:#ff0000;">clientInterface)
-
: AudioPolicyManagerBase("color:#ff0000;">clientInterface) "color:#3333ff;">
-
-
-
{
-
}
-
-
AudioPolicyManagerBase::AudioPolicyManagerBase(
-
AudioPolicyClientInterface *clientInterface)
-
:
-
#ifdef AUDIO_POLICY_TEST
-
Thread(false),
-
#endif //AUDIO_POLICY_TEST
-
mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
-
mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
-
mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
-
mA2dpSuspended(false)
-
{
-
"color:#ff0000;">mpClientInterface = clientInterface; "color:#3333ff;">
-
-
for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
-
mForceUse[i] = AudioSystem::FORCE_NONE;
-
}
-
-
initializeVolumeCurves();
-
-
-
mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
-
AudioSystem::DEVICE_OUT_SPEAKER; "color:#3333ff;">
-
mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC; "color:#3333ff;">
-
-
......
-
-
"color:#ff0000;">mHardwareOutput = "color:#cc0000;">mpClientInterface->openOutput(&outputDesc->mDevice,
-
&outputDesc->mSamplingRate,
-
&outputDesc->mFormat,
-
&outputDesc->mChannels,
-
&outputDesc->mLatency,
-
outputDesc->mFlags);
-
-
......
-
-
"color:#ff0000;">setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER,
-
true);
-
-
......
-
-
}
-
mpClientInterface->openOutput()函数先回掉到AudioPolicyCompatClient类的openOutput()函数。
-
"" style="">"" style="">audio_io_handle_t AudioPolicyCompatClient::openOutput(uint32_t *pDevices,
-
uint32_t *pSamplingRate,
-
uint32_t *pFormat,
-
uint32_t *pChannels,
-
uint32_t *pLatencyMs,
-
AudioSystem::output_flags flags)
-
{
-
return "color:#ff0000;">mServiceOps->open_output(mService, pDevices, pSamplingRate, pFormat,
-
pChannels, pLatencyMs,
-
(audio_policy_output_flags_t)flags);
-
}
由前面分析可知,在创建AudioPolicyCompatClient类对象时,mServiceOps被初始化为APS的struct audio_policy_service_ops变量aps_ops;则将回调到ops中的open_output()函数,具体调到aps_open_output()函数:
-
"" style="font-size:24px;">static audio_io_handle_t aps_open_output(void *service,
-
uint32_t *pDevices,
-
uint32_t *pSamplingRate,
-
uint32_t *pFormat,
-
uint32_t *pChannels,
-
uint32_t *pLatencyMs,
-
audio_policy_output_flags_t flags)
-
{
-
sp af = AudioSystem::get_audio_flinger();
-
if (af == NULL) {
-
LOGW("%s: could not get AudioFlinger", __func__);
-
return 0;
-
}
-
-
return "color:#ff0000;">af->openOutput(pDevices, pSamplingRate, pFormat, pChannels,
-
pLatencyMs, flags);
-
}
不难看出,将调到AudioFlinger的openOutput()函数。
-
"" style="font-size:24px;">int AudioFlinger::openOutput(uint32_t *pDevices,
-
uint32_t *pSamplingRate,
-
uint32_t *pFormat,
-
uint32_t *pChannels,
-
uint32_t *pLatencyMs,
-
uint32_t flags)
-
{
-
......
-
-
audio_hw_device_t *outHwDev;
-
-
......
-
-
outHwDev = findSuitableHwDev_l(*pDevices);
-
if (outHwDev == NULL)
-
return 0;
-
-
status = "color:#ff0000;">outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
-
&channels, &samplingRate, &outStream);
-
-
......
-
-
return 0;
-
}
struct audio_hw_device_t是在头文件hardware/libhardware/include/hardware/audio.h中定义的一个结构体。
-
"" style="font-size:24px;">typedef struct audio_hw_device audio_hw_device_t;
前面在分析AudioFlinger类的load_audio_interface函数时,已经分析过struct audio_hw_device。
-
"" style="font-size:24px;">audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
-
{
-
-
for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
-
audio_hw_device_t *dev = "color:#ff0000;">mAudioHwDevs[i];
-
if (("color:#ff0000;">dev->get_supported_devices(dev) & devices) == devices)
-
return dev;
-
}
-
return NULL;
-
}
由前文分析可知,此处的get_supported_devices()函数指针将具体调到audio_hw_hal.cpp文件中的adev_get_supported_devices(),如下所示,这里列出了系统所支持的所有输出/输入音频设备。因此,我们要也要仿照此音频设备的定义名称,在这里添加USB AUDIO音频设备的名称,以及它们在别处的定义。
-
"" style="font-size:24px;">static uint32_t adev_get_supported_devices(const struct audio_hw_device *dev)
-
{
-
-
-
-
-
-
-
return (
-
AUDIO_DEVICE_OUT_EARPIECE |
-
AUDIO_DEVICE_OUT_SPEAKER |
-
AUDIO_DEVICE_OUT_WIRED_HEADSET |
-
AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
-
AUDIO_DEVICE_OUT_AUX_DIGITAL |
-
AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
-
AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
-
AUDIO_DEVICE_OUT_ALL_SCO |
-
AUDIO_DEVICE_OUT_DEFAULT |
-
-
AUDIO_DEVICE_IN_COMMUNICATION |
-
AUDIO_DEVICE_IN_AMBIENT |
-
AUDIO_DEVICE_IN_BUILTIN_MIC |
-
AUDIO_DEVICE_IN_WIRED_HEADSET |
-
AUDIO_DEVICE_IN_AUX_DIGITAL |
-
AUDIO_DEVICE_IN_BACK_MIC |
-
AUDIO_DEVICE_IN_ALL_SCO |
-
AUDIO_DEVICE_IN_DEFAULT);
-
}
当找到合适的设备之后,将调用outHwDev->open_output_stream()函数打开相应设备的输出流;同样的道理,将具体调到audio_hw_hal.cpp文件中的adev_open_output_stream()函数。
-
"" style="font-size:24px;">static int adev_open_output_stream(struct audio_hw_device *dev,
-
uint32_t devices,
-
int *format,
-
uint32_t *channels,
-
uint32_t *sample_rate,
-
struct audio_stream_out **stream_out)
-
{
-
struct legacy_audio_device *ladev = to_ladev(dev);
-
status_t status;
-
struct legacy_stream_out *out;
-
int ret;
-
-
out = (struct legacy_stream_out *)calloc(1, sizeof(*out));
-
if (!out)
-
return -ENOMEM;
-
-
out->legacy_out = "color:#ff0000;">ladev->hwif->openOutputStream(devices, format, channels,
-
sample_rate, &status);
-
-
......
-
}
由前文分析可知,ladev->hwif具体指AudioHardwareALSA类;则ladev->hwif->openOutputStream()函数调到AudioHardwareALSA::openOutputStream()函数。
-
"" style="font-size:24px;">android_audio_legacy::AudioStreamOut *
-
AudioHardwareALSA::openOutputStream(uint32_t devices,
-
int *format,
-
uint32_t *channels,
-
uint32_t *sampleRate,
-
status_t *status)
-
{
-
......
-
-
-
for(ALSAHandleList::iterator it = mDeviceList.begin(); "color:#3333ff;">
-
-
-
-
it != mDeviceList.end(); ++it)
-
if (it->devices & devices) {
-
err = "color:#ff0000;">mALSADevice->open(&(*it), devices, mode()); "color:#3333ff;">
-
-
-
-
if (err) break;
-
out = "color:#ff0000;">new AudioStreamOutALSA(this, &(*it)); "color:#3333ff;">
-
-
-
err = out->set(format, channels, sampleRate);
-
break;
-
}
-
-
......
-
}
由前文对AudioHardwareALSA类的启动流程分析可知,mDeviceList是用来存储输出/输入音频通道信息的句柄的。
mALSADevice表示在初始化ALSA设备时所指向的一个具体ALSA设备的操作接口。则mALSADevice->open()函数,将具体调到ALSA模块的s_open()函数。
-
"" style="font-size:24px;">static status_t s_open(alsa_handle_t *handle, uint32_t devices, int mode)
-
{
-
-
-
-
-
-
s_close(handle); "color:#3333ff;">
-
-
LOGD("open called for devices %08x in mode %d...", devices, mode);
-
-
const char *stream = "color:#ff0000;">streamName(handle);
-
const char *devName = "color:#ff0000;">deviceName(handle, devices, mode);
-
-
int err;
-
-
for (;;) {
-
-
-
-
err = "color:#ff0000;">snd_pcm_open("color:#ff0000;">&handle->handle, "color:#ff0000;">devName, "color:#ff0000;">direction(handle),
-
"color:#3333ff;">
-
SND_PCM_ASYNC);
-
if (err == 0) break;
-
-
-
-
char *tail = strrchr(devName, '_');
-
if (!tail) break;
-
*tail = 0;
-
}
-
-
if (err < 0) {
-
-
"color:#ff0000;">devName = "default";
-
err = "color:#ff0000;">snd_pcm_open(&handle->handle, devName, direction(handle), 0);
-
}
-
if (err < 0) {
-
LOGE("Failed to Initialize any ALSA %s device: %s",
-
stream, strerror(err));
-
return NO_INIT;
-
}
-
-
err = "color:#ff0000;">setHardwareParams(handle);
-
-
if (err == NO_ERROR) err = setSoftwareParams(handle);
-
-
LOGI("Initialized ALSA %s device %s", stream, devName);
-
-
handle->curDev = devices;
-
handle->curMode = mode;
-
-
return err;
-
}
-
(1) 调用函数streamName()函数获取音频流名称。
-
"" style="font-size:24px;">const char *streamName(alsa_handle_t *handle)
-
{
-
return snd_pcm_stream_name(direction(handle));
-
}
snd_pcm_stream_name()函数是ALSA-LIB API,在external/alsa-lib/src/pcm/pcm.c文件中定义。
要想获得音频流名称,不得不先分析direction()函数。
-
"" style="font-size:24px;">snd_pcm_stream_t direction(alsa_handle_t *handle)
-
{
-
return (handle->devices & android_audio_legacy::AudioSystem::DEVICE_OUT_ALL) ? SND_PCM_STREAM_PLAYBACK
-
: SND_PCM_STREAM_CAPTURE;
-
}
原来direction()函数就是用来返回PCM流的方向(放音或者录音)。
direction()函数的返回值将作为snd_pcm_stream_name()的参数,
-
"" style="font-size:24px;">const char *snd_pcm_stream_name(snd_pcm_stream_t stream)
-
{
-
if (stream > SND_PCM_STREAM_LAST)
-
return NULL;
-
return "color:#ff0000;">snd_pcm_stream_names[stream];
-
}
-
"" style="font-size:24px;">static const char *const snd_pcm_stream_names[] = {
-
STREAM(PLAYBACK),
-
STREAM(CAPTURE),
-
};
好吧,音频流的名称不是放音就是录音。
(2)接下来调用deviceName()函数获取设备名称。这点很重要,将为我们在asound.conf为新添加的USB AUDIO音频设备命名提供规则。
-
"" style="font-size:24px;">const char *deviceName(alsa_handle_t *handle, uint32_t device, int mode)
-
{
-
static char "color:#ff0000;">devString[ALSA_NAME_MAX];
-
int hasDevExt = 0;
-
-
strcpy(devString, devicePrefix[direction(handle)]);
-
-
for (int dev = 0; device && dev < deviceSuffixLen; dev++)
-
if (device & "color:#ff0000;">deviceSuffix[dev].device) {
-
ALSA_STRCAT (devString, deviceSuffix[dev].suffix);
-
device &= ~deviceSuffix[dev].device;
-
"color:#ff0000;">hasDevExt = 1;
-
}
-
-
if (hasDevExt) switch (mode) {
-
case android_audio_legacy::AudioSystem::MODE_NORMAL:
-
ALSA_STRCAT (devString, "_normal")
-
;
-
break;
-
case android_audio_legacy::AudioSystem::MODE_RINGTONE:
-
ALSA_STRCAT (devString, "_ringtone")
-
;
-
break;
-
case android_audio_legacy::AudioSystem::MODE_IN_CALL:
-
ALSA_STRCAT (devString, "_incall")
-
;
-
break;
-
};
-
-
return devString;
-
}
用字符数组devString存储设备名称。
首先把设备前缀复制给devString。因此,作为输出音频通道设备的名称,必以AndroidPlayback为前缀;作为输入音频通道设备的名称,必以AndroidCapture为前缀。
-
"" style="font-size:24px;">static const char *devicePrefix[SND_PCM_STREAM_LAST + 1] = {
-
"AndroidPlayback",
-
"AndroidCapture",
-
};
接下来从deviceSuffix数组中查找合适的后缀,追加到devString字符数组中。
-
"" style="font-size:24px;">
-
-
static const device_suffix_t deviceSuffix[] = {
-
{android_audio_legacy::AudioSystem::DEVICE_OUT_EARPIECE, "_Earpiece"},
-
{android_audio_legacy::AudioSystem::DEVICE_OUT_SPEAKER, "_Speaker"},
-
{android_audio_legacy::AudioSystem::DEVICE_OUT_BLUETOOTH_SCO, "_Bluetooth"},
-
{android_audio_legacy::AudioSystem::DEVICE_OUT_WIRED_HEADSET, "_Headset"},
-
{android_audio_legacy::AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP, "_Bluetooth-A2DP"},
-
};
struct device_suffix_t的定义如下:
-
"" style="font-size:24px;">struct device_suffix_t {
-
const android_audio_legacy::AudioSystem::audio_devices device;
-
const char *suffix;
-
};
PS: 我们也要在此数组中添加USB AUDIO音频设备的相关信息。同时也要在定义了类似DEVICE_OUT_EARPIECE设备的类中定义USB AUDIO音频设备:
-
"" style="font-size:24px;"> 1.frameworks/base/media/java/android/media/AudioSystem.java
-
2.frameworks/base/media/java/android/media/AudioManager.java
-
3.hardware/libhardware_legacy/include/hardware_legacy/AudioSystemLegacy.h
-
4.system/core/include/system/audio.h
题外话:android系统中对音频设备的定义如下(AudioSystem.java):
-
"" style=""> "font-size:24px;"> public static final int DEVICE_OUT_EARPIECE = 0x1; // 0x1 << 0
-
public static final int DEVICE_OUT_SPEAKER = 0x2;
-
public static final int DEVICE_OUT_WIRED_HEADSET = 0x4;
-
public static final int DEVICE_OUT_WIRED_HEADPHONE = 0x8;
-
public static final int DEVICE_OUT_BLUETOOTH_SCO = 0x10;
-
public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20;
-
public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40;
-
public static final int DEVICE_OUT_BLUETOOTH_A2DP = 0x80;
-
public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100;
-
-
public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200;
-
public static final int DEVICE_OUT_AUX_DIGITAL = 0x400;
-
public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800;
-
public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000;
-
public static final int DEVICE_OUT_DEFAULT = 0x8000;
-
-
public static final int DEVICE_IN_COMMUNICATION = 0x10000;
-
public static final int DEVICE_IN_AMBIENT = 0x20000;
-
public static final int DEVICE_IN_BUILTIN_MIC1 = 0x40000;
-
public static final int DEVICE_IN_BUILTIN_MIC2 = 0x80000;
-
public static final int DEVICE_IN_MIC_ARRAY = 0x100000;
-
public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x200000;
-
-
public static final int DEVICE_IN_WIRED_HEADSET = 0x400000;
-
public static final int DEVICE_IN_AUX_DIGITAL = 0x800000;
当设备越来越多时,很难保证等号右边的数字中零的个数不写错。采用注释部分的定义方式较好。
当找到了设备后缀后,将对变量hasDevExt赋值为1,表示还会有扩展名称(_normal,_ringtone或者_incall)。
至此,一个设备的PCM节点名称就形成了!
(3)程序将执行到调用snd_pcm_open() ALSA-LIB API,并把刚才得到的设备名称devName作为参数之一,调到ALSA-LIB,进而调到ALSA-DRIVER,去打开所指定的音频设备。如果打开指定的音频设备失败了,将打开默认的音频设备。
(4)如果成功打开音频设备,程序继续往下执行,将调用setHardwareParams()函数设置硬件参数。这些硬件参数包括缓冲区大小,采样率,声道数和音频格式等。其实这些硬件参数都在struct alsa_handle_t中定义,在分析初始化函数s_init()函数时已有分析,在默认音频设备配置_defaultsOut和_defaultsIn中已经指定。
但是,在使用USB AUDIO输入音频设备时,默认的输入音频配置中的声道数和采样率很有可能与实际使用的USB AUDIO的不一致,导致USB AUDIO设备不可用或者音频失真。因此,需要在执行setHardwareParams()函数前,并且知道是要打开输入音频通道时(输出音频通道的硬件参数配置可用),需要检测时间使用的USB AUDIO音频设备的这两个硬件参数,重新对_defaultsIn中声道数和采样率进行赋值。将在后面做详细分析。
-
"" style="font-size:24px;">status_t setHardwareParams(alsa_handle_t *handle)
-
{
-
......
-
-
unsigned int requestedRate = "color:#ff0000;">handle->sampleRate;
-
-
......
-
-
"color:#ff0000;"> err = snd_pcm_hw_params_set_channels(handle->handle, hardwareParams,
-
"color:#ff0000;">handle->channels);
-
-
......
-
-
err = "color:#ff0000;">snd_pcm_hw_params_set_rate_near(handle->handle, hardwareParams,
-
"color:#ff0000;">&requestedRate, 0);
-
-
......
-
}
-
(5)最后程序会执行到设置软件参数的函数setHardwareParams()中。在添加USB AUDIO音频设备时,这里没有遇到问题,不再分析。
2. JAVA API setDeviceConnectionState()调用流程详解。
把最复杂的两大本地服务分析完后,后面的任务就很轻了!
JAVA API setDeviceConnectionState()在文件frameworks/base/media/java/android/media/AudioSystem.java中定义。
public static native int setDeviceConnectionState(int device, int state, String device_address);
第一个参数就是要打开的音频设备的标识符,将一路传递下去,直到ALSA模块(alsa_default.cpp);
第二个参数表示第一个参数所指的音频设备是否可用;
第三个参数表示设备地址,一般为空。
看到java关键字native,晓得将调到对应的JNI(frameworks/base/core/jni/android_media_AudioSystem.cpp)代码。
-
"" style="font-size:24px;">static int
-
android_media_AudioSystem_setDeviceConnectionState(JNIEnv *env, jobject thiz,
-
jint device, jint state, jstring device_address)
-
{
-
const char *c_address = env->GetStringUTFChars(device_address, NULL);
-
int status = check_AudioSystem_Command(
-
"color:#ff0000;">AudioSystem::setDeviceConnectionState(static_cast (device),
-
static_cast (state),
-
c_address));
-
env->ReleaseStringUTFChars(device_address, c_address);
-
return status;
-
}
显然,又调到libmedia库(frameworks/base/media/libmedia/AudioSystem.cpp)中setDeviceConnectionState()函数。
-
"" style="font-size:24px;">status_t AudioSystem::setDeviceConnectionState(audio_devices_t device,
-
audio_policy_dev_state_t state,
-
const char *device_address)
-
{
-
const sp& aps = AudioSystem::get_audio_policy_service();
-
const char *address = "";
-
-
if (aps == 0) return PERMISSION_DENIED;
-
-
if (device_address != NULL) {
-
address = device_address;
-
}
-
-
return "color:#ff0000;">aps->setDeviceConnectionState(device, state, address);
-
}
显然,调到APS的setDeviceConnectionState()函数。
-
"" style="font-size:24px;">status_t AudioPolicyService::setDeviceConnectionState(audio_devices_t device,
-
audio_policy_dev_state_t state,
-
const char *device_address)
-
{
-
......
-
-
return "color:#ff0000;">mpAudioPolicy->set_device_connection_state(mpAudioPolicy, device,
-
state, device_address);
-
}
-
根据前面对AudioPolicyService服务的启动流程分析可知,mpAudioPolicy指向在文件audio_policy_hal.cpp中定义的音频策略模块。则mpAudioPolicy->set_device_connection_state()函数具体调到函数ap_set_device_connection_state()函数。
-
"" style="font-size:24px;">static int ap_set_device_connection_state(struct audio_policy *pol,
-
audio_devices_t device,
-
audio_policy_dev_state_t state,
-
const char *device_address)
-
{
-
struct legacy_audio_policy *lap = to_lap(pol);
-
return "color:#ff0000;">lap->apm->setDeviceConnectionState(
-
(AudioSystem::audio_devices)device,
-
(AudioSystem::device_connection_state)state,
-
device_address);
-
}
同样,由前面对AudioPolicyService服务的启动流程分析可知,lap->apm指向AudioPolicyManagerBase类对象。则lap->apm->setDeviceConnectionState()函数将调到AudioPolicyManagerBase::setDeviceConnectionState()函数。
-
"" style="font-size: 24px;">"font-size:18px;">status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
-
AudioSystem::device_connection_state state,
-
const char *device_address)
-
{
-
......
-
-
-
if (AudioSystem::isOutputDevice(device)) { "font-size:18px;color:#3333ff;">
-
"font-size:18px;">
-
......
-
-
switch (state)
-
{
-
-
case AudioSystem::DEVICE_STATE_AVAILABLE:
-
if (mAvailableOutputDevices & device) {
-
LOGW("setDeviceConnectionState() device already connected: %x", device);
-
return INVALID_OPERATION;
-
}
-
LOGV("setDeviceConnectionState() connecting device %x", device);
-
-
-
mAvailableOutputDevices |= device; "color:#3333ff;">
-
-
.....
-
-
-
case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
-
if (!(mAvailableOutputDevices & device)) {
-
LOGW("setDeviceConnectionState() device not connected: %x", device);
-
return INVALID_OPERATION;
-
}
-
-
-
LOGV("setDeviceConnectionState() disconnecting device %x", device);
-
-
mAvailableOutputDevices &= ~device; "color:#3333ff;">
-
-
......
-
}
-
-
-
uint32_t newDevice = "color:#ff0000;">getNewDevice(mHardwareOutput, false);
-
-
......
-
-
"color:#ff0000;">updateDeviceForStrategy();
-
"font-size:24px;">"background-color: rgb(153, 153, 153);">"color:#ff0000;">setOutputDevice(mHardwareOutput, newDevice);
-
-
"color:#3333ff;">
-
if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
-
device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
-
} else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
-
device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
-
device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
-
device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
-
} else {
-
return NO_ERROR;
-
}
-
}
-
-
if (AudioSystem::isInputDevice(device)) { "color:#3333ff;">
-
-
switch (state)
-
{
-
-
case AudioSystem::DEVICE_STATE_AVAILABLE: {
-
if (mAvailableInputDevices & device) {
-
LOGW("setDeviceConnectionState() device already connected: %d", device);
-
return INVALID_OPERATION;
-
}
-
mAvailableInputDevices |= device;
-
}
-
break;
-
-
-
case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
-
if (!(mAvailableInputDevices & device)) {
-
LOGW("setDeviceConnectionState() device not connected: %d", device);
-
return INVALID_OPERATION;
-
}
-
mAvailableInputDevices &= ~device;
-
} break;
-
-
default:
-
LOGE("setDeviceConnectionState() invalid state: %x", state);
-
return BAD_VALUE;
-
}
-
-
audio_io_handle_t activeInput = getActiveInput();
-
if (activeInput != 0) {
-
AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
-
uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
-
if (newDevice != inputDesc->mDevice) {
-
LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
-
inputDesc->mDevice, newDevice, activeInput);
-
inputDesc->mDevice = newDevice;
-
AudioParameter param = AudioParameter();
-
param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
-
mpClientInterface->setParameters(activeInput, param.toString());
-
}
-
}
-
-
return NO_ERROR;
-
}
-
-
LOGW("setDeviceConnectionState() invalid device: %x", device);
-
return BAD_VALUE;
-
}
-
(1) 当前设备是输出设备时,程序执行到getNewDevice()函数,将获得新设备,作为设置输出设备函数setOutputDevice()的第二个参数。
-
"" style="">uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
-
{
-
uint32_t device = 0;
-
-
AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
-
-
-
-
-
-
-
-
-
-
-
-
if (outputDesc->"color:#ff0000;">isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) { "color:#3333ff;">
-
-
device = "color:#ff0000;">getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache); "color:#3333ff;">
-
-
} else if (isInCall() ||
-
outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
-
device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
-
} else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
-
device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
-
} else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
-
device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
-
} else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
-
device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
-
}
-
-
......
-
-
return device;
-
}
-
-
......
-
-
-
uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
-
{
-
uint32_t device = 0;
-
-
if (fromCache) {
-
LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
-
return mDeviceForStrategy[strategy];
-
}
-
-
switch (strategy) {
-
case STRATEGY_DTMF:
-
if (!isInCall()) {
-
-
device = getDeviceForStrategy(STRATEGY_MEDIA, false);
-
break;
-
}
-
-
-
-
case STRATEGY_PHONE: "color:#3333ff;">
-
-
-
-
......
-
-
break;
-
-
case STRATEGY_SONIFICATION: "color:#3333ff;">
-
-
-
-
-
......
-
-
case STRATEGY_ENFORCED_AUDIBLE:
-
-
-
-
......
-
-
case STRATEGY_MEDIA: { "color:#3333ff;">
-
uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
-
if (device2 == 0) {
-
device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
-
}
-
-
.......
-
-
"color:#3333ff;">
-
"color:#33cc00;"> if (device2 == 0) {
-
device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_USB_AUDIO;
-
}
-
"color:#3333ff;">
-
-
.......
-
}
(2)获取到新设备后,程序继续向下执行到updateDeviceForStrategy()函数,根据音频策略更新了相应的设备。
-
"" style="">void AudioPolicyManagerBase::updateDeviceForStrategy()
-
{
-
for (int i = 0; i < NUM_STRATEGIES; i++) {
-
mDeviceForStrategy[i] = "color:#ff0000;">getDeviceForStrategy((routing_strategy)i, false);
-
}
-
}
由于此函数仍将调到刚刚分析的函数getDeviceForStrategy(),故不再深入分析。
(3)更新完设备后,程序继续向下执行到setOutputDevice()函数,用新获取到的设备名称作为第二个参数(第一个参数是在创建AudioPolicyManagerBase类对象时获得的输出音频通道),来设置输出设备。此函数很重要,它将调到ALSA模块(alsa_default.cpp)。
-
"" style="">void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
-
{
-
LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
-
AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
-
-
......
-
-
-
AudioParameter param = AudioParameter();
-
param.addInt(String8(AudioParameter::keyRouting), (int)device); "color:#3333ff;">
-
-
mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs); "color:#3333ff;">
-
-
......
-
}
调用函数setOutputDevice()时,明明只有两个参数,怎么函数原型却有4个参数了那。有点儿诡异吧!我也困惑了好大会儿。最后才发现此函数的声明(AudioPolicyManagerBase.h)中,最后两个参数(第三个和第四个参数)已经有了默认值。原来,C++中有了默认值的参数,在调用时可以不写出来!!!
void setOutputDevice(audio_io_handle_t output, uint32_t device, bool force = false, int delayMs = 0);
此函数的重点在于调用了函数mpClientInterface->setParameters()。
第一个参数mHardwareOutput:表示输出音频通道,
第三个参数delayMs:表示等待时间,值为默认值0。
通过前文分析可知,mpClientInterface就是AudioPolicyCompatClient类的对象,则mpClientInterface->setParameters()函数将调到AudioPolicyCompatClient类的setParameters()函数。
-
"" style="font-size:24px;">void AudioPolicyCompatClient::setParameters(audio_io_handle_t ioHandle,
-
const String8& keyValuePairs,
-
int delayMs)
-
{
-
"color:#ff0000;">mServiceOps->set_parameters(mService, ioHandle, keyValuePairs.string(),
-
"color:#3333ff;">
-
-
delayMs);
-
}
而mServiceOps在创建AudioPolicyCompatClient类对象时,指向APS的struct audio_policy_service_ops变量aps_ops。则mServiceOps->set_parameters()函数将调到APS的aps_set_parameters()函数。
-
"" style="font-size:24px;">static void aps_set_parameters(void *service, audio_io_handle_t io_handle,
-
const char *kv_pairs, int delay_ms)
-
{
-
AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
-
-
audioPolicyService->setParameters(io_handle, kv_pairs, delay_ms);
-
}
显然将调到APS类的setParameters()函数。
-
"" style="font-size:24px;">void AudioPolicyService::setParameters(audio_io_handle_t ioHandle,
-
const char *keyValuePairs,
-
int delayMs)
-
{
-
"color:#ff0000;">mAudioCommandThread->parametersCommand((int)ioHandle, keyValuePairs,
-
delayMs); <