Android Audio System深入探究之AudioPolicyService(基于Android9)

1. AudioPolicyService初始化

AudioPolicyService 简称APS

同AudioFlinger诞生一样,APS也从audioserver启动。同样作为一个Binder服务,初始化后及被加入SM(ServiceManager)中。

[–>main_audioserver.cpp]

int main(int argc __unused, char **argv)
{
......
	sp<IServiceManager> sm = defaultServiceManager();
        ALOGI("ServiceManager: %p", sm.get());
        //初始化AF
        AudioFlinger::instantiate();
        //初始化APS
        AudioPolicyService::instantiate(); //instantiate定义在BinderService.h中
......
}

Android Audio System深入探究之AudioPolicyService(基于Android9)_第1张图片
和AudioPolicyService生命周期关联的三个函数, 构造函数AudioPolicyService、onFirstRef和初始化有关, 析构函数~AudioPolicyService和销毁有关。
看下APS初始化做的事情, 只展示重要流程代码,省略次要流程代码

AudioPolicyService::AudioPolicyService()
    : BnAudioPolicyService(), //定义在IAudioPolicyService.h中, 作为Binder调用的Bn端
      mpAudioPolicyDev(NULL),  //设备
      mpAudioPolicy(NULL), //策略
      mAudioPolicyManager(NULL), //APM 
      mAudioPolicyClient(NULL), //APC, APS作为Binder服务端, 其他使用Binder调用的Client使用APC管理
      mPhoneState(AUDIO_MODE_INVALID) //通话状态
{
}

void AudioPolicyService::onFirstRef()
{
    {
        Mutex::Autolock _l(mLock);

        // start tone playback thread, tone音播放相关命令管理
        mTonePlaybackThread = new AudioCommandThread(String8("ApmTone"), this);
        // start audio commands thread , audio命令相关,如音量控制、音频参数设置
        mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);
        // start output activity command thread, Output管理
        mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);
		//创建APC
        mAudioPolicyClient = new AudioPolicyClient(this);
        //创建APM
        mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);
    }
    ......
}

在看下对象销毁做了那些事情

AudioPolicyService::~AudioPolicyService()
{
	//退出初始化创建的各个线程
    mTonePlaybackThread->exit();
    mAudioCommandThread->exit();
    mOutputCommandThread->exit();
    //销毁APM
    destroyAudioPolicyManager(mAudioPolicyManager);
    //回收APC
    delete mAudioPolicyClient;
	......
}

销毁做的事情基本是对初始化创建对象的回收。

再来看下APM的创建
[–>AudioPolicyFactory.cpp]

extern "C" AudioPolicyInterface* createAudioPolicyManager(
        AudioPolicyClientInterface *clientInterface)
{
    return new AudioPolicyManager(clientInterface);
}

AudioPolicyManager的初始化
[–>AudioPolicyManager.cpp]

AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
        : AudioPolicyManager(clientInterface, false /*forTesting*/) //覆盖另外一个构造函数,都是一些变量初始化,看代码
{	
	//加载audio_policy.conf文件,Android6以后配置文件改为了xml格式的audio_policy_configuration.xml
	//比较简单不做展开了
    loadConfig();
    //初始化操作
    initialize();
}

接着看initialize做了那些事情

status_t AudioPolicyManager::initialize() {
	......
    // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
    audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
    ......
    // Retrieve the Policy Manager Interface
    mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
   	......
    ......
    // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
    // open all output streams needed to access attached devices
    audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
    audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
    //(1)第一个for循环遍历所有module
    for (const auto& hwModule : mHwModulesAll) {
        // open all output streams needed to access attached devices
        // except for direct output streams that are only opened when they are actually
        // required by an app.
        // This also validates mAvailableOutputDevices list
        //(2) 遍历每个module所有输出设备
        for (const auto& outProfile : hwModule->getOutputProfiles()) {
            ......
            audio_devices_t profileType = outProfile->getSupportedDevicesType();
            ......
            //SwAudioOutputDescriptor定义在AudioOutputDescriptor.h/.cpp
            sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
                                                                                 mpClientInterface);
            const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
            const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
            String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
                    : String8("");
            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
           	// (3) 函数内部会调用`mClientInterface->openOutput` ,mClientInterface原型是AudioPolicyClient, 
           	//,其定义在APS中,实现在AudioPolicyClientImpl.cpp中,可能是考虑APS代码太多,做了代码拆分
           	//AudioPolicyClient实在APS中定义的,单独定义了文件用于实现Client功能, openOutput最终又回到了
           	//AF中openOutput函数
            status_t status = outputDesc->open(nullptr, profileType, address,
                                           AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);

            if (status != NO_ERROR) {
               ......
            } else {
               ......
                addOutput(output, outputDesc);
                setOutputDevice(outputDesc,
                                profileType,
                                true,
                                0,
                                NULL,
                                address);
            }
        }
        // open input streams needed to access attached devices to validate
        // mAvailableInputDevices list
        ......
    }
    // make sure all attached devices have been allocated a unique ID
    ......
    // make sure default device is reachable
    ......
    // If microphones address is empty, set it according to device type
	......
    updateDevicesAndOutputs();
    return status;
}

2. openOutput

继续看标号(3) 的实现

[–>AudioPolicyClientImpl.cpp]

status_t AudioPolicyService::AudioPolicyClient::openOutput(audio_module_handle_t module,
                                                           audio_io_handle_t *output,
                                                           audio_config_t *config,
                                                           audio_devices_t *devices,
                                                           const String8& address,
                                                           uint32_t *latencyMs,
                                                           audio_output_flags_t flags)
{
    sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();
    ......
    //调用AF的openOutput函数
    return af->openOutput(module, output, config, devices, address, latencyMs, flags);
}

//TODO 跳转到AF的分析流程

从上面代码流程我们可以发现,APS初始化时,会遍历audio_policy.conf文件中所有Module,然后再遍历所有的输出及输入设备并打开,在放音流程中我们找到了设备打开的线索。原来最终设备open操作还是回到了AF中。真是摸不到头脑。

你可能感兴趣的:(Android源码剖析,android系统分析)