Android(4.4)音頻系統之AudioPolicyService服務

轉載地址:https://blog.csdn.net/yangwen123/article/details/39497375

AudioPolicyService是策略的制定者,比如什麼時候打開音頻接口設備、某種Stream類型的音頻對應什麼設備等等。而AudioFlinger則是策略的執行者,例如具體如何與音頻設備通信,如何維護現有系統中的音頻設備,以及多個音頻流的混音如何處理等等都得由它來完成。AudioPolicyService根據用戶配置來指導AudioFlinger加載設備接口,起到路由功能。

AudioPolicyService啓動過程

AudioPolicyService服務運行在mediaserver進程中,隨着mediaserver進程啓動而啓動。

frameworks\av\media\mediaserver\ Main_mediaserver.cpp

  1. int main(int argc, char** argv)  
  2. {  
  3.     sp<ProcessState> proc(ProcessState::self());  
  4.     sp<IServiceManager> sm = defaultServiceManager();  
  5.     ALOGI("ServiceManager: %p", sm.get());  
  6.     VolumeManager::instantiate(); // volumemanager have to be started before audioflinger  
  7.     AudioFlinger::instantiate();  
  8.     MediaPlayerService::instantiate();  
  9.     CameraService::instantiate();  
  10.     AudioPolicyService::instantiate();  
  11.     ProcessState::self()->startThreadPool();  
  12.     IPCThreadState::self()->joinThreadPool();  
  13. }  

AudioPolicyService繼承了模板類BinderService,該類用於註冊native service。

frameworks\native\include\binder\ BinderService.h

  1. template<typename SERVICE>  
  2. class BinderService  
  3. {  
  4. public:  
  5.     static status_t publish(bool allowIsolated = false) {  
  6.         sp<IServiceManager> sm(defaultServiceManager());  
  7.         return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);  
  8.     }  
  9.     static void instantiate() { publish(); }  
  10. };  

BinderService是一個模板類,該類的publish函數就是完成向ServiceManager註冊服務。

  1. static const char *getServiceName() { return "media.audio_policy"; }  

AudioPolicyService註冊名爲media.audio_policy的服務。

  1. AudioPolicyService::AudioPolicyService()  
  2.     : BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)  
  3. {  
  4.     char value[PROPERTY_VALUE_MAX];  
  5.     const struct hw_module_t *module;  
  6.     int forced_val;  
  7.     int rc;  
  8.     Mutex::Autolock _l(mLock);  
  9.     // start tone playback thread  
  10.     mTonePlaybackThread = new AudioCommandThread(String8("ApmTone"), this);  
  11.     // start audio commands thread  
  12.     mAudioCommandThread = new AudioCommandThread(String8("ApmAudio"), this);  
  13.     // start output activity command thread  
  14.     mOutputCommandThread = new AudioCommandThread(String8("ApmOutput"), this);  
  15.     /* instantiate the audio policy manager */  
  16.     /* 加載audio_policy.default.so庫得到audio_policy_module模塊 */  
  17.     rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);  
  18.     if (rc)  
  19.         return;  
  20.     /* 通過audio_policy_module模塊打開audio_policy_device設備 */  
  21.     rc = audio_policy_dev_open(module, &mpAudioPolicyDev);  
  22.     ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));  
  23.     if (rc)  
  24.         return;  
  25.     //通過audio_policy_device設備創建audio_policy  
  26.     rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,  
  27.                                                &mpAudioPolicy);  
  28.     ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));  
  29.     if (rc)  
  30.         return;  
  31.     rc = mpAudioPolicy->init_check(mpAudioPolicy);  
  32.     ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));  
  33.     if (rc)  
  34.         return;  
  35.     /* SPRD: maybe set this property better, but here just change the default value @{ */  
  36.     property_get("ro.camera.sound.forced", value, "1");  
  37.     forced_val = strtol(value, NULL, 0);  
  38.     ALOGV("setForceUse() !forced_val=%d ",!forced_val);  
  39.     mpAudioPolicy->set_can_mute_enforced_audible(mpAudioPolicy, !forced_val);  
  40.     ALOGI("Loaded audio policy from %s (%s)", module->name, module->id);  
  41.     // 讀取audio_effects.conf文件  
  42.     if (access(AUDIO_EFFECT_VENDOR_CONFIG_FILE, R_OK) == 0) {  
  43.         loadPreProcessorConfig(AUDIO_EFFECT_VENDOR_CONFIG_FILE);  
  44.     } else if (access(AUDIO_EFFECT_DEFAULT_CONFIG_FILE, R_OK) == 0) {  
  45.         loadPreProcessorConfig(AUDIO_EFFECT_DEFAULT_CONFIG_FILE);  
  46.     }  
  47. }  
  1. 創建AudioCommandThread (ApmToneApmAudioApmOutput)
  2. 加載legacy_ap_module
  3. 打開legacy_ap_device
  4. 創建legacy_audio_policy
  5. 讀取audio_effects.conf

創建AudioCommandThread線程

在AudioPolicyService對象構造過程中,分別創建了ApmTone、ApmAudio、ApmOutput三個AudioCommandThread線程:

1、 ApmTone用於播放tone音;

2、 ApmAudio用於執行audio命令;

3、ApmOutput用於執行輸出命令;

在第一次強引用AudioCommandThread線程對象時,AudioCommandThread的onFirstRef函數被回調,在此啓動線程

  1. void AudioPolicyService::AudioCommandThread::onFirstRef()  
  2. {  
  3.     run(mName.string(), ANDROID_PRIORITY_AUDIO);  
  4. }  

這裏採用異步方式來執行audio command,當需要執行上表中的命令時,首先將命令投遞到AudioCommandThread的mAudioCommands命令向量表中,然後通過mWaitWorkCV.signal()喚醒AudioCommandThread線程,被喚醒的AudioCommandThread線程執行完command後,又通過mWaitWorkCV.waitRelative(mLock, waitTime)睡眠等待命令到來。

加載audio_policy_module模塊

audio_policy硬件抽象層動態庫位於/system/lib/hw/目錄下,命名爲:audio_policy.$(TARGET_BOARD_PLATFORM).so。audiopolicy的硬件抽象層定義在hardware\libhardware_legacy\audio\audio_policy_hal.cpp中,AUDIO_POLICY_HARDWARE_MODULE_ID硬件抽象模塊定義如下:

hardware\libhardware_legacy\audio\ audio_policy_hal.cpp【audio_policy.scx15.so】

  1. struct legacy_ap_module HAL_MODULE_INFO_SYM = {  
  2.     module: {  
  3.         common: {  
  4.             tag: HARDWARE_MODULE_TAG,  
  5.             version_major: 1,  
  6.             version_minor: 0,  
  7.             id: AUDIO_POLICY_HARDWARE_MODULE_ID,  
  8.             name: "LEGACY Audio Policy HAL",  
  9.             author: "The Android Open Source Project",  
  10.             methods: &legacy_ap_module_methods,  
  11.             dso : NULL,  
  12.             reserved : {0},  
  13.         },  
  14.     },  
  15. };  

legacy_ap_module繼承於audio_policy_module


 

關於hw_get_module函數加載硬件抽象層模塊的過程請參考Android硬件抽象Hardware庫加載過程源碼分析

打開audio_policy_device設備

hardware\libhardware\include\hardware\ audio_policy.h

  1. static inline int audio_policy_dev_open(const hw_module_t* module,  
  2.                                     struct audio_policy_device** device)  
  3. {  
  4.     return module->methods->open(module, AUDIO_POLICY_INTERFACE,  
  5.                                  (hw_device_t**)device);  
  6. }  

通過legacy_ap_module模塊的open方法來打開一個legacy_ap_device設備。

hardware\libhardware_legacy\audio\ audio_policy_hal.cpp

  1. static int legacy_ap_dev_open(const hw_module_t* module, const char* name,  
  2.                                     hw_device_t** device)  
  3. {  
  4.     struct legacy_ap_device *dev;  
  5.     if (strcmp(name, AUDIO_POLICY_INTERFACE) != 0)  
  6.         return -EINVAL;  
  7.     dev = (struct legacy_ap_device *)calloc(1, sizeof(*dev));  
  8.     if (!dev)  
  9.         return -ENOMEM;  
  10.     dev->device.common.tag = HARDWARE_DEVICE_TAG;  
  11.     dev->device.common.version = 0;  
  12.     dev->device.common.module = const_cast<hw_module_t*>(module);  
  13.     dev->device.common.close = legacy_ap_dev_close;  
  14.     dev->device.create_audio_policy = create_legacy_ap;  
  15.     dev->device.destroy_audio_policy = destroy_legacy_ap;  
  16.     *device = &dev->device.common;  
  17.     return 0;  
  18. }  

打開得到一個legacy_ap_device設備,通過該抽象設備可以創建一個audio_policy對象。

創建audio_policy對象

在打開legacy_ap_device設備時,該設備的create_audio_policy成員初始化爲create_legacy_ap函數指針,我們通過legacy_ap_device設備可以創建一個legacy_audio_policy對象。

  1. rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,  
  2.                                                &mpAudioPolicy);  

這裏通過audio_policy_device設備創建audio策略對象

hardware\libhardware_legacy\audio\ audio_policy_hal.cpp

  1. static int create_legacy_ap(const struct audio_policy_device *device,  
  2.                             struct audio_policy_service_ops *aps_ops,  
  3.                             void *service,  
  4.                             struct audio_policy **ap)  
  5. {  
  6.     struct legacy_audio_policy *lap;  
  7.     int ret;  
  8.     if (!service || !aps_ops)  
  9.         return -EINVAL;  
  10.     lap = (struct legacy_audio_policy *)calloc(1, sizeof(*lap));  
  11.     if (!lap)  
  12.         return -ENOMEM;  
  13. lap->policy.set_device_connection_state = ap_set_device_connection_state;  
  14. …  
  15.     lap->policy.dump = ap_dump;  
  16.     lap->policy.is_offload_supported = ap_is_offload_supported;  
  17.     lap->service = service;  
  18.     lap->aps_ops = aps_ops;  
  19.     lap->service_client = new AudioPolicyCompatClient(aps_ops, service);  
  20.     if (!lap->service_client) {  
  21.         ret = -ENOMEM;  
  22.         goto err_new_compat_client;  
  23.     }  
  24.     lap->apm = createAudioPolicyManager(lap->service_client);  
  25.     if (!lap->apm) {  
  26.         ret = -ENOMEM;  
  27.         goto err_create_apm;  
  28.     }  
  29.     *ap = &lap->policy;  
  30.     return 0;  
  31. err_create_apm:  
  32.     delete lap->service_client;  
  33. err_new_compat_client:  
  34.     free(lap);  
  35.     *ap = NULL;  
  36.     return ret;  
  37. }  

audio_policy實現在audio_policy_hal.cpp中,audio_policy_service_ops實現在AudioPolicyService.cpp中。create_audio_policy()函數就是創建並初始化一個legacy_audio_policy對象。

audio_policy與AudioPolicyService、AudioPolicyCompatClient之間的關係如下:

AudioPolicyClient創建

hardware\libhardware_legacy\audio\ AudioPolicyCompatClient.h

  1. AudioPolicyCompatClient(struct audio_policy_service_ops *serviceOps,void *service) :  
  2.         mServiceOps(serviceOps) , mService(service) {}  

AudioPolicyCompatClient是對audio_policy_service_ops的封裝類,對外提供audio_policy_service_ops數據結構中定義的接口。

AudioPolicyManager創建

  1. extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)  
  2. {  
  3.     ALOGI("SPRD policy manager created.");  
  4.     return new AudioPolicyManagerSPRD(clientInterface);  
  5. }  

使用AudioPolicyClientInterface對象來構造AudioPolicyManagerSPRD對象,AudioPolicyManagerSPRD繼承於AudioPolicyManagerBase,而AudioPolicyManagerBase又繼承於AudioPolicyInterface。

hardware\libhardware_legacy\audio\ AudioPolicyManagerBase.cpp

  1. AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)  
  2.     :  
  3. #ifdef AUDIO_POLICY_TEST  
  4.     Thread(false),  
  5. #endif //AUDIO_POLICY_TEST  
  6.     //變量初始化  
  7.     mPrimaryOutput((audio_io_handle_t)0),  
  8.     mAvailableOutputDevices(AUDIO_DEVICE_NONE),  
  9.     mPhoneState(AudioSystem::MODE_NORMAL),  
  10.     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),  
  11.     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),  
  12.     mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),  
  13.     mSpeakerDrcEnabled(false), mFmOffGoing(false)  
  14. {  
  15.     //引用AudioPolicyCompatClient對象,這樣音頻管理器AudioPolicyManager就可以使用audio_policy_service_ops中的接口  
  16.     mpClientInterface = clientInterface;  
  17.     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {  
  18.         mForceUse[i] = AudioSystem::FORCE_NONE;  
  19.     }  
  20.     mA2dpDeviceAddress = String8("");  
  21.     mScoDeviceAddress = String8("");  
  22.     mUsbCardAndDevice = String8("");  
  23.     /** 
  24.      * 優先加載/vendor/etc/audio_policy.conf配置文件,如果該配置文件不存在,則 
  25.      * 加載/system/etc/audio_policy.conf配置文件,如果該文件還是不存在,則通過 
  26.      * 函數defaultAudioPolicyConfig()來設置默認音頻接口 
  27.      */  
  28.     if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {  
  29.         if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {  
  30.             ALOGE("could not load audio policy configuration file, setting defaults");  
  31.             defaultAudioPolicyConfig();  
  32.         }  
  33.     }  
  34.     //設置各種音頻流對應的音量調節點,must be done after reading the policy  
  35.     initializeVolumeCurves();  
  36.     // open all output streams needed to access attached devices  
  37.     for (size_t i = 0; i < mHwModules.size(); i++) {  
  38.         //通過名稱打開對應的音頻接口硬件抽象庫  
  39.         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);  
  40.         if (mHwModules[i]->mHandle == 0) {  
  41.             ALOGW("could not open HW module %s", mHwModules[i]->mName);  
  42.             continue;  
  43.         }  
  44.         // open all output streams needed to access attached devices  
  45.         // except for direct output streams that are only opened when they are actually  
  46.         // required by an app.  
  47.         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)  
  48.         {  
  49.             const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];  
  50.             //打開mAttachedOutputDevices對應的輸出  
  51.             if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&  
  52.                     ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {  
  53.                 //將輸出IOProfile封裝爲AudioOutputDescriptor對象  
  54.                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);  
  55.                 //設置當前音頻接口的默認輸出設備  
  56.                 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice & outProfile->mSupportedDevices);  
  57.                 //打開輸出,在AudioFlinger中創建PlaybackThread線程,並返回該線程的id  
  58.                 audio_io_handle_t output = mpClientInterface->openOutput(  
  59.                                                 outProfile->mModule->mHandle,  
  60.                                                 &outputDesc->mDevice,  
  61.                                                 &outputDesc->mSamplingRate,  
  62.                                                 &outputDesc->mFormat,  
  63.                                                 &outputDesc->mChannelMask,  
  64.                                                 &outputDesc->mLatency,  
  65.                                                 outputDesc->mFlags);  
  66.                 if (output == 0) {  
  67.                     delete outputDesc;  
  68.                 } else {  
  69.                     //設置可以使用的輸出設備爲mAttachedOutputDevices  
  70.                     mAvailableOutputDevices =(audio_devices_t)(mAvailableOutputDevices | (outProfile->mSupportedDevices & mAttachedOutputDevices));  
  71.                     if (mPrimaryOutput == 0 && outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {  
  72.                         mPrimaryOutput = output;  
  73.                     }  
  74.                     //將輸出描述符對象AudioOutputDescriptor及創建的PlaybackThread線程id以鍵值對形式保存  
  75.                     addOutput(output, outputDesc);  
  76.                     //設置默認輸出設備  
  77.                     setOutputDevice(output,(audio_devices_t)(mDefaultOutputDevice & outProfile->mSupportedDevices),true);  
  78.                 }  
  79.             }  
  80.         }  
  81.     }  
  82.     ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),  
  83.              "Not output found for attached devices %08x",  
  84.              (mAttachedOutputDevices & ~mAvailableOutputDevices));  
  85.     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");  
  86.     updateDevicesAndOutputs();  
  87.   
  88.     //  add for bug158794 start  
  89.     char bootvalue[PROPERTY_VALUE_MAX];  
  90.     // prop sys.boot_completed will set 1 when system ready (ActivityManagerService.java)...  
  91.     property_get("sys.boot_completed", bootvalue, "");  
  92.     if (strncmp("1", bootvalue, 1) != 0) {  
  93.         startReadingThread();  
  94.     }  
  95.     // add for bug158794 end  
  96.   
  97. #ifdef AUDIO_POLICY_TEST  
  98.     ...  
  99. #endif //AUDIO_POLICY_TEST  
  100. }  

AudioPolicyManagerBase對象構造過程中主要完成以下幾個步驟:

1、  loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE)加載audio_policy.conf配置文件;

2、  initializeVolumeCurves()初始化各種音頻流對應的音量調節點;

3、  加載audio policy硬件抽象庫:mpClientInterface->loadHwModule(mHwModules[i]->mName)

4、  打開attached_output_devices輸出:

mpClientInterface->openOutput();

5、  保存輸出設備描述符對象:addOutput(output, outputDesc);

讀取audio_policy.conf文件

Android爲每種音頻接口定義了對應的硬件抽象層,且編譯爲單獨的so庫。

每種音頻接口定義了不同的輸入輸出,一個接口可以具有多個輸入或者輸出,每個輸入輸出有可以支持不同的音頻設備。通過讀取audio_policy.conf文件可以獲取系統支持的音頻接口參數。

audio_policy.conf文件定義了兩種音頻配置信息:

1、  當前系統支持的音頻輸入輸出設備及默認輸入輸出設備;

這些信息時通過global_configuration配置項來設置,在global_configuration中定義了三種音頻設備信息:

attached_output_devices:已連接的輸出設備;

default_output_device:默認輸出設備;

attached_input_devices:已連接的輸入設備;

 

1、  系統支持的音頻接口信息;

audio_policy.conf定義了系統支持的所有音頻接口參數信息,比如primary、a2dp、usb等,對於primary定義如下:

a2dp定義:

usb定義:

每種音頻接口包含輸入輸出,每種輸入輸出又包含多種輸入輸出配置,每種輸入輸出配置又支持多種音頻設備。AudioPolicyManagerBase首先加載/vendor/etc/audio_policy.conf,如果該文件不存在,則加/system/etc/audio_policy.conf。

  1. status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)  
  2. {  
  3.     cnode *root;  
  4.     char *data;  
  5.     data = (char *)load_file(path, NULL);  
  6.     if (data == NULL) {  
  7.         return -ENODEV;  
  8.     }  
  9.     root = config_node("""");  
  10.     //讀取配置文件  
  11.     config_load(root, data);  
  12.     //解析global_configuration  
  13.     loadGlobalConfig(root);  
  14.     //解析audio_hw_modules  
  15.     loadHwModules(root);  
  16.     config_free(root);  
  17.     free(root);  
  18.     free(data);  
  19.     ALOGI("loadAudioPolicyConfig() loaded %s\n", path);  
  20.     return NO_ERROR;  
  21. }  

通過loadGlobalConfig(root)函數來讀取這些全局配置信息。

  1. void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)  
  2. {  
  3.     cnode *node = config_find(root, GLOBAL_CONFIG_TAG);  
  4.     if (node == NULL) {  
  5.         return;  
  6.     }  
  7.     node = node->first_child;  
  8.     while (node) {  
  9.         //attached_output_devices AUDIO_DEVICE_OUT_EARPIECE  
  10.         if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {  
  11.             mAttachedOutputDevices = parseDeviceNames((char *)node->value);  
  12.             ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,  
  13.                     "loadGlobalConfig() no attached output devices");  
  14.             ALOGV("loadGlobalConfig()mAttachedOutputDevices%04x", mAttachedOutputDevices);  
  15.         //default_output_device AUDIO_DEVICE_OUT_SPEAKER  
  16.         } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {  
  17.             mDefaultOutputDevice= (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,ARRAY_SIZE(sDeviceNameToEnumTable),(char *)node->value);  
  18.             ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,  
  19.                     "loadGlobalConfig() default device not specified");  
  20.             ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);  
  21.         //attached_input_devices AUDIO_DEVICE_IN_BUILTIN_MIC  
  22.         } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {  
  23.             mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;  
  24.             ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);  
  25.         //speaker_drc_enabled   
  26.         } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {  
  27.             mSpeakerDrcEnabled = stringToBool((char *)node->value);  
  28.             ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);  
  29.         }  
  30.         node = node->next;  
  31.     }  
  32. }  

audio_policy.conf同時定義了多個audio 接口,每一個audio 接口包含若干output和input,而每個output和input又同時支持多種輸入輸出模式,每種輸入輸出模式又支持若干種設備。

通過loadHwModules ()函數來加載系統配置的所有audio 接口:

  1. void AudioPolicyManagerBase::loadHwModules(cnode *root)  
  2. {  
  3.     //audio_hw_modules  
  4.     cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);  
  5.     if (node == NULL) {  
  6.         return;  
  7.     }  
  8.     node = node->first_child;  
  9.     while (node) {  
  10.         ALOGV("loadHwModules() loading module %s", node->name);  
  11.         //加載音頻接口  
  12.         loadHwModule(node);  
  13.         node = node->next;  
  14.     }  
  15. }  

由於audio_policy.conf可以定義多個音頻接口,因此該函數循環調用loadHwModule()來解析每個音頻接口參數信息。Android定義HwModule類來描述每一個audio 接口參數,定義IOProfile類來描述輸入輸出模式配置。


到此就將audio_policy.conf文件中音頻接口配置信息解析到了AudioPolicyManagerBase的成員變量mHwModules、mAttachedOutputDevices、mDefaultOutputDevice、mAvailableInputDevices中。

初始化音量調節點

音量調節點設置在Android4.1與Android4.4中的實現完全不同,在Android4.1中是通過VolumeManager服務來管理,通過devicevolume.xml文件來配置,但Android4.4取消了VolumeManager服務,將音量控制放到AudioPolicyManagerBase中。在AudioPolicyManagerBase中定義了音量調節對應的音頻流描述符數組:

  1. StreamDescriptor mStreams[AudioSystem::NUM_STREAM_TYPES];  

initializeVolumeCurves()函數就是初始化該數組元素:

  1. void AudioPolicyManagerBase::initializeVolumeCurves()  
  2. {  
  3.     for (int i = 0; i < AUDIO_STREAM_CNT; i++) {  
  4.         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {  
  5.             mStreams[i].mVolumeCurve[j] =  
  6.                     sVolumeProfiles[i][j];  
  7.         }  
  8.     }  
  9.   
  10.     // Check availability of DRC on speaker path: if available, override some of the speaker curves  
  11.     if (mSpeakerDrcEnabled) {  
  12. mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =  
  13.                 sDefaultSystemVolumeCurveDrc;  
  14. mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =  
  15.                 sSpeakerSonificationVolumeCurveDrc;  
  16. mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =  
  17.                 sSpeakerSonificationVolumeCurveDrc;  
  18. mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =sSpeakerSonificationVolumeCurveDrc;  
  19.     }  
  20. }  

sVolumeProfiles數組定義了不同音頻設備下不同音頻流對應的音量調節檔位,定義如下:

數組元素爲音量調節檔位,每種模式下的音量調節都包含4個檔位,定義如下:

加載audio_module模塊

AudioPolicyManager通過讀取audio_policy.conf配置文件,可以知道系統當前支持那些音頻接口以及attached的輸入輸出設備、默認輸出設備。接下來就需要加載這些音頻接口的硬件抽象庫。

這三中音頻接口硬件抽象定義如下:

/vendor/sprd/open-source/libs/audio/audio_hw.c 【audio.primary.scx15.so】

  1. struct audio_module HAL_MODULE_INFO_SYM = {  
  2.     .common = {  
  3.         .tag = HARDWARE_MODULE_TAG,  
  4.         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,  
  5.         .hal_api_version = HARDWARE_HAL_API_VERSION,  
  6.         .id = AUDIO_HARDWARE_MODULE_ID,  
  7.         .name = "Spreadtrum Audio HW HAL",  
  8.         .author = "The Android Open Source Project",  
  9.         .methods = &hal_module_methods,  
  10.     },  
  11. };  


external/bluetooth/bluedroid/audio_a2dp_hw/audio_a2dp_hw.c【audio.a2dp.default.so】

  1. struct audio_module HAL_MODULE_INFO_SYM = {  
  2.     .common = {  
  3.         .tag = HARDWARE_MODULE_TAG,  
  4.         .version_major = 1,  
  5.         .version_minor = 0,  
  6.         .id = AUDIO_HARDWARE_MODULE_ID,  
  7.         .name = "A2DP Audio HW HAL",  
  8.         .author = "The Android Open Source Project",  
  9.         .methods = &hal_module_methods,  
  10.     },  
  11. };  

hardware/libhardware/modules/usbaudio/audio_hw.c【audio. usb.default.so】

  1. struct audio_module HAL_MODULE_INFO_SYM = {  
  2.     .common = {  
  3.         .tag = HARDWARE_MODULE_TAG,  
  4.         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,  
  5.         .hal_api_version = HARDWARE_HAL_API_VERSION,  
  6.         .id = AUDIO_HARDWARE_MODULE_ID,  
  7.         .name = "USB audio HW HAL",  
  8.         .author = "The Android Open Source Project",  
  9.         .methods = &hal_module_methods,  
  10.     },  
  11. };  

AudioPolicyClientInterface提供了加載音頻接口硬件抽象庫的接口函數,通過前面的介紹,我們知道,AudioPolicyCompatClient通過代理audio_policy_service_ops實現AudioPolicyClientInterface接口。

hardware\libhardware_legacy\audio\ AudioPolicyCompatClient.cpp

  1. audio_module_handle_t AudioPolicyCompatClient::loadHwModule(const char *moduleName)  
  2. {  
  3.     return mServiceOps->load_hw_module(mService, moduleName);  
  4. }  

AudioPolicyCompatClient將音頻模塊加載工作交給audio_policy_service_ops

frameworks\av\services\audioflinger\ AudioPolicyService.cpp

  1. static audio_module_handle_t aps_load_hw_module(void *service,const char *name)  
  2. {  
  3.     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();  
  4.     if (af == 0) {  
  5.         ALOGW("%s: could not get AudioFlinger", __func__);  
  6.         return 0;  
  7.     }  
  8.     return af->loadHwModule(name);  
  9. }  

AudioPolicyService又將其轉交給AudioFlinger

frameworks\av\services\audioflinger\ AudioFlinger.cpp

  1. audio_module_handle_t AudioFlinger::loadHwModule(const char *name)  
  2. {  
  3.     if (!settingsAllowed()) {  
  4.         return 0;  
  5.     }  
  6.     Mutex::Autolock _l(mLock);  
  7.     return loadHwModule_l(name);  
  8. }  


  1. audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)  
  2. {  
  3.     for (size_t i = 0; i < mAudioHwDevs.size(); i++) {  
  4.         if (strncmp(mAudioHwDevs.valueAt(i)->moduleName(), name, strlen(name)) == 0) {  
  5.             ALOGW("loadHwModule() module %s already loaded", name);  
  6.             return mAudioHwDevs.keyAt(i);  
  7.         }  
  8.     }  
  9. audio_hw_device_t *dev;   
  10. //加載音頻接口對應的so庫,得到對應的音頻接口設備audio_hw_device_t  
  11.     int rc = load_audio_interface(name, &dev);  
  12.     if (rc) {  
  13.         ALOGI("loadHwModule() error %d loading module %s ", rc, name);  
  14.         return 0;  
  15.     }  
  16.     mHardwareStatus = AUDIO_HW_INIT;  
  17.     rc = dev->init_check(dev);  
  18.     mHardwareStatus = AUDIO_HW_IDLE;  
  19.     if (rc) {  
  20.         ALOGI("loadHwModule() init check error %d for module %s ", rc, name);  
  21.         return 0;  
  22.     }  
  23.     if ((mMasterVolumeSupportLvl != MVS_NONE) &&  
  24.         (NULL != dev->set_master_volume)) {  
  25.         AutoMutex lock(mHardwareLock);  
  26.         mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;  
  27.         dev->set_master_volume(dev, mMasterVolume);  
  28.         mHardwareStatus = AUDIO_HW_IDLE;  
  29.     }  
  30.     audio_module_handle_t handle = nextUniqueId();  
  31.     mAudioHwDevs.add(handle, new AudioHwDevice(name, dev));  
  32.     ALOGI("loadHwModule() Loaded %s audio interface from %s (%s) handle %d",  
  33.           name, dev->common.module->name, dev->common.module->id, handle);  
  34.     return handle;  
  35. }  

函數首先加載系統定義的音頻接口對應的so庫,並打開該音頻接口的抽象硬件設備audio_hw_device_t,爲每個音頻接口設備生成獨一無二的ID號,同時將打開的音頻接口設備封裝爲AudioHwDevice對象,將系統中所有的音頻接口設備保存到AudioFlinger的成員變量mAudioHwDevs中。

函數load_audio_interface根據音頻接口名稱來打開抽象的音頻接口設備audio_hw_device_t。

  1. static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)  
  2. {  
  3.     const hw_module_t *mod;  
  4. int rc;  
  5. //根據名字加載audio_module模塊  
  6.     rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);  
  7.     ALOGE_IF(rc, "%s couldn't load audio hw module %s.%s (%s)", __func__,  
  8.                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));  
  9.     if (rc) {  
  10.         goto out;  
  11. }  
  12. //打開audio_device設備  
  13.     rc = audio_hw_device_open(mod, dev);  
  14.     ALOGE_IF(rc, "%s couldn't open audio hw device in %s.%s (%s)", __func__,  
  15.                  AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));  
  16.     if (rc) {  
  17.         goto out;  
  18.     }  
  19.     if ((*dev)->common.version != AUDIO_DEVICE_API_VERSION_CURRENT) {  
  20.         ALOGE("%s wrong audio hw device version %04x", __func__, (*dev)->common.version);  
  21.         rc = BAD_VALUE;  
  22.         goto out;  
  23.     }  
  24.     return 0;  
  25. out:  
  26.     *dev = NULL;  
  27.     return rc;  
  28. }  

hardware\libhardware\include\hardware\ Audio.h

  1. static inline int audio_hw_device_open(const struct hw_module_t* module,  
  2.                                        struct audio_hw_device** device)  
  3. {  
  4.     return module->methods->open(module, AUDIO_HARDWARE_INTERFACE,  
  5.                                  (struct hw_device_t**)device);  
  6. }  

hardware\libhardware_legacy\audio\ audio_hw_hal.cpp

  1. static int legacy_adev_open(const hw_module_t* module, const char* name,  
  2.                             hw_device_t** device)  
  3. {  
  4.     struct legacy_audio_device *ladev;  
  5.     int ret;  
  6.     if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0)  
  7.         return -EINVAL;  
  8.     ladev = (struct legacy_audio_device *)calloc(1, sizeof(*ladev));  
  9.     if (!ladev)  
  10.         return -ENOMEM;  
  11.     ladev->device.common.tag = HARDWARE_DEVICE_TAG;  
  12.     ladev->device.common.version = AUDIO_DEVICE_API_VERSION_1_0;  
  13.     ladev->device.common.module = const_cast<hw_module_t*>(module);  
  14.     ladev->device.common.close = legacy_adev_close;  
  15.     ladev->device.get_supported_devices = adev_get_supported_devices;  
  16. …  
  17. ladev->device.dump = adev_dump;  
  18.     ladev->hwif = createAudioHardware();  
  19.     if (!ladev->hwif) {  
  20.         ret = -EIO;  
  21.         goto err_create_audio_hw;  
  22.     }  
  23.     *device = &ladev->device.common;  
  24.     return 0;  
  25. err_create_audio_hw:  
  26.     free(ladev);  
  27.     return ret;  
  28. }  

打開音頻接口設備過程其實就是構造並初始化legacy_audio_device對象過程,legacy_audio_device數據結構關係如下:

 

legacy_adev_open函數就是創建並初始化一個legacy_audio_device對象:


到此就加載完系統定義的所有音頻接口,並生成相應的數據對象,如下圖所示:

打開音頻輸出

AudioPolicyService加載完所有音頻接口後,就知道了系統支持的所有音頻接口參數,可以爲音頻輸出提供決策。

爲了能正常播放音頻數據,需要創建抽象的音頻輸出接口對象,打開音頻輸出過程如下:

  1. audio_io_handle_t AudioPolicyCompatClient::openOutput(audio_module_handle_t module,  
  2.                                               audio_devices_t *pDevices,  
  3.                                               uint32_t *pSamplingRate,  
  4.                                               audio_format_t *pFormat,  
  5.                                               audio_channel_mask_t *pChannelMask,    
  6.                                               uint32_t *pLatencyMs,  
  7.                                               audio_output_flags_t flags,  
  8.                                               const audio_offload_info_t *offloadInfo)  
  9. {  
  10.     return mServiceOps->open_output_on_module(mService,module, pDevices, pSamplingRate,  
  11.                                               pFormat, pChannelMask, pLatencyMs,  
  12.                                               flags, offloadInfo);  
  13. }  

 

  1. static audio_io_handle_t aps_open_output_on_module(void *service,  
  2.                                           audio_module_handle_t module,  
  3.                                           audio_devices_t *pDevices,  
  4.                                           uint32_t *pSamplingRate,  
  5.                                           audio_format_t *pFormat,  
  6.                                           audio_channel_mask_t *pChannelMask,  
  7.                                           uint32_t *pLatencyMs,  
  8.                                           audio_output_flags_t flags,  
  9.                                           const audio_offload_info_t *offloadInfo)  
  10. {  
  11.     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();  
  12.     if (af == 0) {  
  13.         ALOGW("%s: could not get AudioFlinger", __func__);  
  14.         return 0;  
  15.     }  
  16.     return af->openOutput(module, pDevices, pSamplingRate, pFormat, pChannelMask,  
  17.                           pLatencyMs, flags, offloadInfo);  
  18. }  



  1. audio_io_handle_t AudioFlinger::openOutput(audio_module_handle_t module,  
  2.                                            audio_devices_t *pDevices,  
  3.                                            uint32_t *pSamplingRate,  
  4.                                            audio_format_t *pFormat,  
  5.                                            audio_channel_mask_t *pChannelMask,  
  6.                                            uint32_t *pLatencyMs,  
  7.                                            audio_output_flags_t flags,  
  8.                                            const audio_offload_info_t *offloadInfo)  
  9. {  
  10.     PlaybackThread *thread = NULL;  
  11.     struct audio_config config;  
  12.     config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0;  
  13.     config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0;  
  14.     config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT;  
  15.     if (offloadInfo) {  
  16.         config.offload_info = *offloadInfo;  
  17.     }  
  18.     //創建一個音頻輸出流對象audio_stream_out_t  
  19.     audio_stream_out_t *outStream = NULL;  
  20.     AudioHwDevice *outHwDev;  
  21.     ALOGV("openOutput(), module %d Device %x, SamplingRate %d, Format %#08x, Channels %x, flags %x",  
  22.               module,  
  23.               (pDevices != NULL) ? *pDevices : 0,  
  24.               config.sample_rate,  
  25.               config.format,  
  26.               config.channel_mask,  
  27.               flags);  
  28.     ALOGV("openOutput(), offloadInfo %p version 0x%04x",  
  29.           offloadInfo, offloadInfo == NULL ? -1 : offloadInfo->version );  
  30.     if (pDevices == NULL || *pDevices == 0) {  
  31.         return 0;  
  32.     }  
  33.     Mutex::Autolock _l(mLock);  
  34.     //從音頻接口列表mAudioHwDevs中查找出對應的音頻接口,如果找不到,則重新加載音頻接口動態庫  
  35.     outHwDev = findSuitableHwDev_l(module, *pDevices);  
  36.     if (outHwDev == NULL)  
  37.         return 0;  
  38.     //取出module對應的audio_hw_device_t設備  
  39.     audio_hw_device_t *hwDevHal = outHwDev->hwDevice();  
  40.     //爲音頻輸出流生成一個獨一無二的id號  
  41.     audio_io_handle_t id = nextUniqueId();  
  42.     mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;  
  43.     //打開音頻輸出流  
  44.     status_t status = hwDevHal->open_output_stream(hwDevHal,  
  45.                                           id,  
  46.                                           *pDevices,  
  47.                                           (audio_output_flags_t)flags,  
  48.                                           &config,  
  49.                                           &outStream);  
  50.     mHardwareStatus = AUDIO_HW_IDLE;  
  51.     ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %#08x, "  
  52.             "Channels %x, status %d",  
  53.             outStream,  
  54.             config.sample_rate,  
  55.             config.format,  
  56.             config.channel_mask,  
  57.             status);  
  58.     if (status == NO_ERROR && outStream != NULL) {  
  59.         //使用AudioStreamOut來封裝音頻輸出流audio_stream_out_t  
  60.         AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream, flags);  
  61.         //根據flag標誌位,創建不同類型的線程  
  62.         if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {  
  63.             thread = new OffloadThread(this, output, id, *pDevices);  
  64.             ALOGV("openOutput() created offload output: ID %d thread %p", id, thread);  
  65.         } else if ((flags & AUDIO_OUTPUT_FLAG_DIRECT) ||  
  66.             (config.format != AUDIO_FORMAT_PCM_16_BIT) ||  
  67.             (config.channel_mask != AUDIO_CHANNEL_OUT_STEREO)) {  
  68.             thread = new DirectOutputThread(this, output, id, *pDevices);  
  69.             ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);  
  70.         } else {  
  71.             thread = new MixerThread(this, output, id, *pDevices);  
  72.             ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);  
  73.         }  
  74.         //將創建的線程及id以鍵值對的形式保存在mPlaybackThreads中  
  75.         mPlaybackThreads.add(id, thread);  
  76.         if (pSamplingRate != NULL) {  
  77.             *pSamplingRate = config.sample_rate;  
  78.         }  
  79.         if (pFormat != NULL) {  
  80.             *pFormat = config.format;  
  81.         }  
  82.         if (pChannelMask != NULL) {  
  83.             *pChannelMask = config.channel_mask;  
  84.         }  
  85.         if (pLatencyMs != NULL) {  
  86.             *pLatencyMs = thread->latency();  
  87.         }  
  88.         // notify client processes of the new output creation  
  89.         thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);  
  90.         // the first primary output opened designates the primary hw device  
  91.         if ((mPrimaryHardwareDev == NULL) && (flags & AUDIO_OUTPUT_FLAG_PRIMARY)) {  
  92.             ALOGI("Using module %d has the primary audio interface", module);  
  93.             mPrimaryHardwareDev = outHwDev;  
  94.             AutoMutex lock(mHardwareLock);  
  95.             mHardwareStatus = AUDIO_HW_SET_MODE;  
  96.             hwDevHal->set_mode(hwDevHal, mMode);  
  97.             mHardwareStatus = AUDIO_HW_IDLE;  
  98.         }  
  99.         return id;  
  100.     }  
  101.     return 0;  
  102. }  

打開音頻輸出流過程其實就是創建AudioStreamOut對象及PlaybackThread線程過程。首先通過抽象的音頻接口設備audio_hw_device_t來創建輸出流對象legacy_stream_out。

  1. static int adev_open_output_stream(struct audio_hw_device *dev,  
  2.                                    audio_io_handle_t handle,  
  3.                                    audio_devices_t devices,  
  4.                                    audio_output_flags_t flags,  
  5.                                    struct audio_config *config,  
  6.                                    struct audio_stream_out **stream_out)  
  7. {  
  8.     struct legacy_audio_device *ladev = to_ladev(dev);  
  9.     status_t status;  
  10.     struct legacy_stream_out *out;  
  11. int ret;  
  12. //分配一個legacy_stream_out對象  
  13.     out = (struct legacy_stream_out *)calloc(1, sizeof(*out));  
  14.     if (!out)  
  15.         return -ENOMEM;  
  16. devices = convert_audio_device(devices, HAL_API_REV_2_0, HAL_API_REV_1_0);  
  17. //創建AudioStreamOut對象  
  18.     out->legacy_out = ladev->hwif->openOutputStream(devices, (int *) &config->format,  
  19.                                                     &config->channel_mask,  
  20.                                                     &config->sample_rate, &status);  
  21.     if (!out->legacy_out) {  
  22.         ret = status;  
  23.         goto err_open;  
  24. }  
  25. //初始化成員變量audio_stream  
  26.     out->stream.common.get_sample_rate = out_get_sample_rate;  
  27.     …  
  28.     *stream_out = &out->stream;  
  29.     return 0;  
  30. err_open:  
  31.     free(out);  
  32.     *stream_out = NULL;  
  33.     return ret;  
  34. }  

由於legacy_audio_device的成員變量hwif的類型爲AudioHardwareInterface,因此通過調用AudioHardwareInterface的接口openOutputStream()來創建AudioStreamOut對象。

  1. AudioStreamOut* AudioHardwareStub::openOutputStream(  
  2.         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status)  
  3. {  
  4.     AudioStreamOutStub* out = new AudioStreamOutStub();  
  5.     status_t lStatus = out->set(format, channels, sampleRate);  
  6.     if (status) {  
  7.         *status = lStatus;  
  8.     }  
  9.     if (lStatus == NO_ERROR)  
  10.         return out;  
  11.     delete out;  
  12.     return 0;  
  13. }  


打開音頻輸出後,在AudioFlinger與AudioPolicyService中的表現形式如下:

 

打開音頻輸入

  1. audio_io_handle_t AudioPolicyCompatClient::openInput(audio_module_handle_t module,  
  2.                                              audio_devices_t *pDevices,  
  3.                                              uint32_t *pSamplingRate,  
  4.                                              audio_format_t *pFormat,  
  5.                                              audio_channel_mask_t *pChannelMask)  
  6. {  
  7.     return mServiceOps->open_input_on_module(mService, module, pDevices,pSamplingRate, pFormat, pChannelMask);  
  8. }  


 

  1. static audio_io_handle_t aps_open_input_on_module(void *service,  
  2.                                        audio_module_handle_t module,  
  3.                                        audio_devices_t *pDevices,  
  4.                                        uint32_t *pSamplingRate,  
  5.                                        audio_format_t *pFormat,  
  6.                                        audio_channel_mask_t *pChannelMask)  
  7. {  
  8.     sp<IAudioFlinger> af = AudioSystem::get_audio_flinger();  
  9.     if (af == 0) {  
  10.         ALOGW("%s: could not get AudioFlinger", __func__);  
  11.         return 0;  
  12.     }  
  13.     return af->openInput(module, pDevices, pSamplingRate, pFormat, pChannelMask);  
  14. }  

  1. audio_io_handle_t AudioFlinger::openInput(audio_module_handle_t module,  
  2.                                           audio_devices_t *pDevices,  
  3.                                           uint32_t *pSamplingRate,  
  4.                                           audio_format_t *pFormat,  
  5.                                           audio_channel_mask_t *pChannelMask)  
  6. {  
  7.     status_t status;  
  8.     RecordThread *thread = NULL;  
  9.     struct audio_config config;  
  10.     config.sample_rate = (pSamplingRate != NULL) ? *pSamplingRate : 0;  
  11.     config.channel_mask = (pChannelMask != NULL) ? *pChannelMask : 0;  
  12.     config.format = (pFormat != NULL) ? *pFormat : AUDIO_FORMAT_DEFAULT;  
  13.   
  14.     uint32_t reqSamplingRate = config.sample_rate;  
  15.     audio_format_t reqFormat = config.format;  
  16.     audio_channel_mask_t reqChannels = config.channel_mask;  
  17.     audio_stream_in_t *inStream = NULL;  
  18.     AudioHwDevice *inHwDev;  
  19.     if (pDevices == NULL || *pDevices == 0) {  
  20.         return 0;  
  21.     }  
  22.     Mutex::Autolock _l(mLock);  
  23.     inHwDev = findSuitableHwDev_l(module, *pDevices);  
  24.     if (inHwDev == NULL)  
  25.         return 0;  
  26.     audio_hw_device_t *inHwHal = inHwDev->hwDevice();  
  27.     audio_io_handle_t id = nextUniqueId();  
  28.     status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config,&inStream);  
  29.     ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, "  
  30.             "status %d",  
  31.             inStream,  
  32.             config.sample_rate,  
  33.             config.format,  
  34.             config.channel_mask,  
  35.             status);  
  36.   
  37.     // If the input could not be opened with the requested parameters and we can handle the  
  38.     // conversion internally, try to open again with the proposed parameters. The AudioFlinger can  
  39.     // resample the input and do mono to stereo or stereo to mono conversions on 16 bit PCM inputs.  
  40.     if (status == BAD_VALUE &&reqFormat == config.format && config.format == AUDIO_FORMAT_PCM_16_BIT && (config.sample_rate <= 2 * reqSamplingRate) &&  
  41.         (popcount(config.channel_mask) <= FCC_2) && (popcount(reqChannels) <= FCC_2)) {  
  42.         ALOGV("openInput() reopening with proposed sampling rate and channel mask");  
  43.         inStream = NULL;  
  44.         status = inHwHal->open_input_stream(inHwHal, id, *pDevices, &config, &inStream);  
  45.     }  
  46.   
  47.     if (status == NO_ERROR && inStream != NULL) {  
  48.   
  49. #ifdef TEE_SINK  
  50.         // Try to re-use most recently used Pipe to archive a copy of input for dumpsys,  
  51.         // or (re-)create if current Pipe is idle and does not match the new format  
  52.       ...  
  53. #endif  
  54.         AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);  
  55.         // Start record thread  
  56.         // RecordThread requires both input and output device indication to forward to audio  
  57.         // pre processing modules  
  58.         thread = new RecordThread(this,  
  59.                                   input,  
  60.                                   reqSamplingRate,  
  61.                                   reqChannels,  
  62.                                   id,  
  63.                                   primaryOutputDevice_l(),  
  64.                                   *pDevices  
  65. #ifdef TEE_SINK  
  66.                                   , teeSink  
  67. #endif  
  68.                                   );  
  69.         mRecordThreads.add(id, thread);  
  70.         ALOGV("openInput() created record thread: ID %d thread %p", id, thread);  
  71.         if (pSamplingRate != NULL) {  
  72.             *pSamplingRate = reqSamplingRate;  
  73.         }  
  74.         if (pFormat != NULL) {  
  75.             *pFormat = config.format;  
  76.         }  
  77.         if (pChannelMask != NULL) {  
  78.             *pChannelMask = reqChannels;  
  79.         }  
  80.         // notify client processes of the new input creation  
  81.         thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);  
  82.         return id;  
  83.     }  
  84.     return 0;  
  85. }  

打開音頻輸入流過程其實就是創建AudioStreamIn對象及RecordThread線程過程。首先通過抽象的音頻接口設備audio_hw_device_t來創建輸出流對象legacy_stream_in。

  1. static int adev_open_input_stream(struct audio_hw_device *dev,  
  2.                                   audio_io_handle_t handle,  
  3.                                   audio_devices_t devices,  
  4.                                   struct audio_config *config,  
  5.                                   struct audio_stream_in **stream_in)  
  6. {  
  7.     struct legacy_audio_device *ladev = to_ladev(dev);  
  8.     status_t status;  
  9.     struct legacy_stream_in *in;  
  10.     int ret;  
  11.     in = (struct legacy_stream_in *)calloc(1, sizeof(*in));  
  12.     if (!in)  
  13.         return -ENOMEM;  
  14.     devices = convert_audio_device(devices, HAL_API_REV_2_0, HAL_API_REV_1_0);  
  15.     in->legacy_in = ladev->hwif->openInputStream(devices, (int *) &config->format,  
  16.                                        &config->channel_mask,  
  17.                                        &config->sample_rate,  
  18.                                        &status, (AudioSystem::audio_in_acoustics)0);  
  19.     if (!in->legacy_in) {  
  20.         ret = status;  
  21.         goto err_open;  
  22.     }  
  23.     in->stream.common.get_sample_rate = in_get_sample_rate;  
  24.     …  
  25.     *stream_in = &in->stream;  
  26.     return 0;  
  27. err_open:  
  28.     free(in);  
  29.     *stream_in = NULL;  
  30.     return ret;  
  31. }  

 

  1. AudioStreamIn* AudioHardwareStub::openInputStream(  
  2.         uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate,  
  3.         status_t *status, AudioSystem::audio_in_acoustics acoustics)  
  4. {  
  5.     // check for valid input source  
  6.     if (!AudioSystem::isInputDevice((AudioSystem::audio_devices)devices)) {  
  7.         return 0;  
  8.     }  
  9.     AudioStreamInStub* in = new AudioStreamInStub();  
  10.     status_t lStatus = in->set(format, channels, sampleRate, acoustics);  
  11.     if (status) {  
  12.         *status = lStatus;  
  13.     }  
  14.     if (lStatus == NO_ERROR)  
  15.         return in;  
  16.     delete in;  
  17.     return 0;  
  18. }  

打開音頻輸入創建了以下legacy_stream_in對象:

打開音頻輸入後,在AudioFlinger與AudioPolicyService中的表現形式如下:

AudioPolicyManagerBase構造時,它會根據用戶提供的audio_policy.conf來分析系統中有哪些audio接口(primary,a2dp以及usb),然後通過AudioFlinger::loadHwModule加載各audio接口對應的庫文件,並依次打開其中的output(openOutput)input(openInput)

->打開音頻輸出時創建一個audio_stream_out通道,並創建AudioStreamOut對象以及新建PlaybackThread播放線程。

-> 打開音頻輸入時創建一個audio_stream_in通道,並創建AudioStreamIn對象以及創建RecordThread錄音線程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章