android usb audio

class AudioPolicyManager:<frameworks/av/services/audiopolicy/manager/default/AudioPolicyManager.h>

     class AudioPolicyInterface: <frameworks/av/services/audiopolicy/AudioPolicyInterface.h>

    class AudioPolicyManagerObserver

    

AudioPolicyService创建:
<frameworks/av/services/audiopolicy/service/AudioPolicyService.cpp>
在所有实际的操作前其会调用void AudioPolicyService::onFirstRef()
该函数调用了hardware层一些函数,也引用了hardware层一些函数,其定义在如下的函数中。
./hardware/libhardware/include/hardware/hardware.h

84行,未定义USE_LEGACY_AUDIO_POLICY,执行else语句分支。
114行~115行:

mAudioPolicyClient = new AudioPolicyClient(this);
mAudioPolicyManager = createAudioPolicyManager(mAudioPolicyClient);

<AudioPolicyService.h>

AudioPolicyInterface *mAudioPolicyManager;
AudioPolicyClient *mAudioPolicyClient;

<frameworks/av/services/audiopolicy/AudioPolicyInterface.h>
336~337行如下代码:

​extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface);
extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface);

上述函数的实现位置是

<./frameworks/av/services/audiopolicy/manager/AudioPolicyFactory.cpp>

 21 extern "C" AudioPolicyInterface* createAudioPolicyManager(
 22         AudioPolicyClientInterface *clientInterface)
 23 {
 24     return new AudioPolicyManager(clientInterface);
 25 }​​

AudioPolicyManager函数定义在<frameworks/av/services/audiopolicy/managerdefault/AudioPolicyManager.cpp>

 ​2712 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
2713     :
2714 #ifdef AUDIO_POLICY_TEST
2715     Thread(false),
2716 #endif //AUDIO_POLICY_TEST
2717     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2718     mA2dpSuspended(false),
2719     mSpeakerDrcEnabled(false),
2720     mAudioPortGeneration(1),
2721     mBeaconMuteRefCount(0),
2722     mBeaconPlayingRefCount(0),
2723     mBeaconMuted(false),
2724     mTtsOutputAvailable(false)
2725 {
2726     audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
2727     if (!engineInstance) {
2728         ALOGE("%s:  Could not get an instance of policy engine", __FUNCTION__);
2729         return;
2730     }
2731     // Retrieve the Policy Manager Interface
2732     mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
2733     if (mEngine == NULL) {
2734         ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
2735         return;
2736     }
2737     mEngine->setObserver(this);
2738     status_t status = mEngine->initCheck();
2739     ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
2740 
2741     mUidCached = getuid();
2742     mpClientInterface = clientInterface;
2743 
2744     mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
2745     if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE,
2746                  mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2747                  mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
2748         if (ConfigParsingUtils::loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE,
2749                                   mHwModules, mAvailableInputDevices, mAvailableOutputDevices,
2750                                   mDefaultOutputDevice, mSpeakerDrcEnabled) != NO_ERROR) {
2751             ALOGE("could not load audio policy configuration file, setting defaults");
2752             defaultAudioPolicyConfig();
2753         }
2754     }
2755     // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
2756 
2757     // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
2758     mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
2759 
2760     // open all output streams needed to access attached devices
2761     audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2762     audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
2763     for (size_t i = 0; i < mHwModules.size(); i++) {
2764         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2765         if (mHwModules[i]->mHandle == 0) {
2766             ALOGW("could not open HW module %s", mHwModules[i]->mName);
2767             continue;
2768         }
2769         // open all output streams needed to access attached devices
2770         // except for direct output streams that are only opened when they are actually
2771         // required by an app.
2772         // This also validates mAvailableOutputDevices list
2773         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2774         {
2775             const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
。。。
2813             status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
2814                                                             &output,
2815                                                             &config,
2816                                                             &outputDesc->mDevice,
2817                                                             String8(""),
2818                                                             &outputDesc->mLatency,
2819                                                             outputDesc->mFlags);
2820 
2821             if (status != NO_ERROR) {
2822                 ALOGW("Cannot open output stream for device %08x on hw module %s",
2823                       outputDesc->mDevice,
2824                       mHwModules[i]->mName);
2825             } else {
2826                 outputDesc->mSamplingRate = config.sample_rate;
2827                 outputDesc->mChannelMask = config.channel_mask;
2828                 outputDesc->mFormat = config.format;
2829 
2830                 for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
2831                     audio_devices_t type = outProfile->mSupportedDevices[k]->type();
2832                     ssize_t index =
2833                             mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2834                     // give a valid ID to an attached device once confirmed it is reachable
2835                     if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
2836                         mAvailableOutputDevices[index]->attach(mHwModules[i]);
2837                     }
2838                 }
2839                 if (mPrimaryOutput == 0 &&
2840                         outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2841                     mPrimaryOutput = outputDesc;
2842                 }
2843                 addOutput(output, outputDesc);

2844                 setOutputDevice(outputDesc,
2845                                 outputDesc->mDevice,
2846                                 true);
2847             }
2848         }
2849         // open input streams needed to access attached devices to validate
2850         // mAvailableInputDevices list
2851         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2852         {
2853             const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
2854 
2855             if (inProfile->mSupportedDevices.isEmpty()) {
2856                 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2857                 continue;
2858             }
2859             // chose first device present in mSupportedDevices also part of
2860             // inputDeviceTypes
2861             audio_devices_t profileType = AUDIO_DEVICE_NONE;
2862             for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
2863                 profileType = inProfile->mSupportedDevices[k]->type();
2864                 if (profileType & inputDeviceTypes) {
2865                     break;
2866                 }
2867             }
2868             if ((profileType & inputDeviceTypes) == 0) {
2869                 continue;
2870             }
2871             sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2872 
2873             inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2874             inputDesc->mDevice = profileType;
2875 
2876             // find the address
2877             DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
2878             //   the inputs vector must be of size 1, but we don't want to crash here
2879             String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
2880                     : String8("");
2881             ALOGV("  for input device 0x%x using address %s", profileType, address.string());
2882             ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
2883 
2884             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2885             config.sample_rate = inputDesc->mSamplingRate;
2886             config.channel_mask = inputDesc->mChannelMask;
2887             config.format = inputDesc->mFormat;
2888             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2889             status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
2890                                                            &input,
2891                                                            &config,
2892                                                            &inputDesc->mDevice,
2893                                                            address,
2894                                                            AUDIO_SOURCE_MIC,
2895                                                            AUDIO_INPUT_FLAG_NONE);
2896 
2897             if (status == NO_ERROR) {
2898                 for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
2899                     audio_devices_t type = inProfile->mSupportedDevices[k]->type();
2900                     ssize_t index =
2901                             mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2902                     // give a valid ID to an attached device once confirmed it is reachable
2903                     if (index >= 0) {
2904                         sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
2905                         if (!devDesc->isAttached()) {
2906                             devDesc->attach(mHwModules[i]);
2907                             devDesc->importAudioPort(inProfile);
2908                         }
2909                     }
2910                 }
2911                 mpClientInterface->closeInput(input);
2912             } else {
2913                 ALOGW("Cannot open input stream for device %08x on hw module %s",
2914                       inputDesc->mDevice,
2915                       mHwModules[i]->mName);
2916             }
2917         }
2918     }
2919     // make sure all attached devices have been allocated a unique ID
2920     for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
2921         if (!mAvailableOutputDevices[i]->isAttached()) {
2922             ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->type());
2923             mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2924             continue;
2925         }
2926         // The device is now validated and can be appended to the available devices of the engine
2927         mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
2928                                           AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
2929         i++;
2930     }
2931     for (size_t i = 0; i  < mAvailableInputDevices.size();) {
2932         if (!mAvailableInputDevices[i]->isAttached()) {
2933             ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
2934             mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2935             continue;
2936         }
2937         // The device is now validated and can be appended to the available devices of the engine
2938         mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
2939                                           AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
2940         i++;
2941     }
2942     // make sure default device is reachable
2943     if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
2944         ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
2945     }
2946 
2947     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2948 
2949     updateDevicesAndOutputs();
2950 
2951 #ifdef AUDIO_POLICY_TEST
2952     if (mPrimaryOutput != 0) {
2953         AudioParameter outputCmd = AudioParameter();
2954         outputCmd.addInt(String8("set_id"), 0);
2955         mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
2956 
2957         mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2958         mTestSamplingRate = 44100;
2959         mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2960         mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
2961         mTestLatencyMs = 0;
2962         mCurOutput = 0;
2963         mDirectOutput = false;
2964         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2965             mTestOutputs[i] = 0;
2966         }
2967 
2968         const size_t SIZE = 256;
2969         char buffer[SIZE];
2970         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2971         run(buffer, ANDROID_PRIORITY_AUDIO);
2972     }
2973 #endif //AUDIO_POLICY_TEST
2974 }

2748行会解析/system/etc/audio_policy.conf配置文件,这是在找不到vendor定义的配置文件后的执行动作。

经过这个解析后,mAvailableOutputDevices和mAvailableInputDevices包括了所有的输出和输入设备。

2763行针对每一个设备进行加载。

2764行加载Hwmodule。

<frameworks/av/services/audioplolicy/AudioPolicyInterface.h>

class  ​ AudioPolicyClientInterface {
...
// loads a HW module.
    virtual audio_module_handle_t loadHwModule(const char *name) = 0;
...
}

<./frameworks/av/services/audioflinger/AudioFlinger.cpp>

 ​1561 audio_module_handle_t AudioFlinger::loadHwModule(const char *name)
1562 {
1563     if (name == NULL) {
1564         return 0;
1565     }
1566     if (!settingsAllowed()) {
1567         return 0;
1568     }
1569     Mutex::Autolock _l(mLock);
1570     return loadHwModule_l(name);
1571 }
1572 
1573 // loadHwModule_l() must be called with AudioFlinger::mLock held
1574 audio_module_handle_t AudioFlinger::loadHwModule_l(const char *name)
1575 {
...
1583     audio_hw_device_t *dev;
1584 
1585     int rc = load_audio_interface(name, &dev);


1643     audio_module_handle_t handle = nextUniqueId();
1644     mAudioHwDevs.add(handle, new AudioHwDevice(handle, name, dev, flags));

1649     return handle;
}

load_audio_interface也定义在AudioFlinger函数里的定义如下:

 ​ 140 static int load_audio_interface(const char *if_name, audio_hw_device_t **dev)
 141 {
 142     const hw_module_t *mod;
 143     int rc;
 144 
 145     rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, &mod);

 151     rc = audio_hw_device_open(mod, dev);

 167 }

145行查看这类型的hw module是否存在,如果存在则会调用151行的open函数打开设备。

<./hardware/libhardware/include/hardware/audio.h>

 ​680 static inline int audio_hw_device_open(const struct hw_module_t* module,
681                                        struct audio_hw_device** device)
682 {
683     return module->methods->open(module, AUDIO_HARDWARE_INTERFACE,
684                                  (struct hw_device_t**)device);
685 }

实际上的open函数定义于具体声卡类型的文件中,针对与usb audio设备,其定义于

<hardware/libhardware/modules/usbaudio/audio_hal.c>

 ​1076 static struct hw_module_methods_t hal_module_methods = {
1077     .open = adev_open,
1078 };
1079 
1080 struct audio_module HAL_MODULE_INFO_SYM = {
1081     .common = {
1082         .tag = HARDWARE_MODULE_TAG,
1083         .module_api_version = AUDIO_MODULE_API_VERSION_0_1,
1084         .hal_api_version = HARDWARE_HAL_API_VERSION,
1085         .id = AUDIO_HARDWARE_MODULE_ID,
1086         .name = "USB audio HW HAL",
1087         .author = "The Android Open Source Project",
1088         .methods = &hal_module_methods,
1089     },
1090 };

不出意外,这个open应该是成功的。接着打开流程loadHwModule的1644行。创建了一个硬件设备。该类的构造函数如下:

 ​    AudioHwDevice(audio_module_handle_t handle,
                  const char *moduleName,
                  audio_hw_device_t *hwDevice,
                  Flags flags)
        : mHandle(handle)
        , mModuleName(strdup(moduleName))
        , mHwDevice(hwDevice)
        , mFlags(flags) { }

设备打开和添加的操作是完成了,接下来是打开对应的stream。AudioPolicyManager的2773行。

<./frameworks/av/services/audioflinger/AudioFlinger.cpp>

1775 sp<AudioFlinger::PlaybackThread> AudioFlinger::openOutput_l(audio_module_handle_t module,
1776                                                             audio_io_handle_t *output,
1777                                                             audio_config_t *config,
1778                                                             audio_devices_t devices,
1779                                                             const String8& address,
1780                                                             audio_output_flags_t flags)
1781 {
1782     AudioHwDevice *outHwDev = findSuitableHwDev_l(module, devices);
1787     audio_hw_device_t *hwDevHal = outHwDev->hwDevice();
1816     status_t status = outHwDev->openOutputStream(
1817             &outputStream,
1818             *output,
1819             devices,
1820             flags,
1821             config,
1822             address.string());
...
}

 
​1848 status_t AudioFlinger::openOutput(audio_module_handle_t module,
1849                                   audio_io_handle_t *output,
1850                                   audio_config_t *config,
1851                                   audio_devices_t *devices,
1852                                   const String8& address,
1853                                   uint32_t *latencyMs,
1854                                   audio_output_flags_t flags)
1855 {
1870     sp<PlaybackThread> thread = openOutput_l(module, output, config, *devices, address, flags);

关键函数是1816行,打开stream。

<./frameworks/av/services/audioflinger/AudioHwDevice.cpp>

 34 status_t AudioHwDevice::openOutputStream(
 35         AudioStreamOut **ppStreamOut,
 36         audio_io_handle_t handle,
 37         audio_devices_t devices,
 38         audio_output_flags_t flags,
 39         struct audio_config *config,
 40         const char *address)
 41 {
​ 
 44     AudioStreamOut *outputStream = new AudioStreamOut(this, flags);
status_t status = outputStream->open(handle, devices, config, address);

AudioStreamOut类的作用是管理对HAL层output Stream的操作。

<./frameworks/av/services/audioflinger/AudioStreamOut.cpp>

112 status_t AudioStreamOut::open(
113         audio_io_handle_t handle,
114         audio_devices_t devices,
115         struct audio_config *config,
116         const char *address)
117 {
118     audio_stream_out_t *outStream;
119     int status = hwDev()->open_output_stream(
120             hwDev(),
121             handle,
122             devices,
123             flags,
124             config,
125             &outStream,
126             address);
127     ALOGV("AudioStreamOut::open(), HAL open_output_stream returned "
128             " %p, sampleRate %d, Format %#x, "
129             "channelMask %#x, status %d",
130             outStream,
131             config->sample_rate,
132             config->format,
133             config->channel_mask,
134             status);
135 
136     if (status == NO_ERROR) {
137         stream = outStream;
138         mHalFormatIsLinearPcm = audio_is_linear_pcm(config->format);
139         ALOGI("AudioStreamOut::open(), mHalFormatIsLinearPcm = %d", (int)mHalFormatIsLinearPcm);
140         mHalFrameSize = audio_stream_out_frame_size(stream);
141     }
142 
143     return status;
144 }

AudioStreamOut.cpp文件里的绝大多数函数是调用HAL层代码完成其工作的。

上面的函数119行调用hardware/libhardware/modules/usbaudio/audio_hal.c的adev_open_output_stream完成实际的打开动作。

engin函数会对设备的类型和config参数进行相应的设置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shichaog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值