Android Audio

发布时间 2023-08-28 17:21:07作者: xiaowang_lj

1.最常接触到的audioservice

frameworks\base\services\core\java\com\android\server\audio\AudioService.java

初始化音量的代码

// Initialize volume
        // Priority 1 - Android Property
        // Priority 2 - Audio Policy Service
        // Priority 3 - Default Value
        if (AudioProductStrategy.getAudioProductStrategies().size() > 0) {
            int numStreamTypes = AudioSystem.getNumStreamTypes();

            for (int streamType = numStreamTypes - 1; streamType >= 0; streamType--) {
                AudioAttributes attr =
                        AudioProductStrategy.getAudioAttributesForStrategyWithLegacyStreamType(
                                streamType);
                int maxVolume = AudioSystem.getMaxVolumeIndexForAttributes(attr);
                if (maxVolume != -1) {
                    MAX_STREAM_VOLUME[streamType] = maxVolume;
                }
                int minVolume = AudioSystem.getMinVolumeIndexForAttributes(attr);
                if (minVolume != -1) {
                    MIN_STREAM_VOLUME[streamType] = minVolume;
                }
            }
            if (mUseVolumeGroupAliases) {
                // Set all default to uninitialized.
                for (int stream = 0; stream < AudioSystem.DEFAULT_STREAM_VOLUME.length; stream++) {
                    AudioSystem.DEFAULT_STREAM_VOLUME[stream] = UNSET_INDEX;
                }
            }
        }

2.进入到audiosystem中获取最大音量getMaxVolumeIndexForAttributes

frameworks\base\media\java\android\media\AudioSystem.java

/**
     * @hide
     * get the maximum volume index for the given {@link AudioAttributes}.
     * @param attributes the {@link AudioAttributes} to be considered
     * @return maximum volume index for the given {@link AudioAttributes}.
     */
    public static native int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attributes);

方法为native方法,具体实现在frameworks\base\core\jni\android_media_AudioSystem.cpp

static jint
android_media_AudioSystem_getMaxVolumeIndexForAttributes(JNIEnv *env,
                                                         jobject thiz,
                                                         jobject jaa)
{
    // read the AudioAttributes values
    JNIAudioAttributeHelper::UniqueAaPtr paa = JNIAudioAttributeHelper::makeUnique();
    jint jStatus = JNIAudioAttributeHelper::nativeFromJava(env, jaa, paa.get());
    if (jStatus != (jint)AUDIO_JAVA_SUCCESS) {
        return jStatus;
    }
    int index;
    if (AudioSystem::getMaxVolumeIndexForAttributes(*(paa.get()), index)
            != NO_ERROR) {
        index = -1;
    }
    return (jint) index;
}

3.调用audiosystem的getMaxVolumeIndexForAttributes方法

frameworks\av\media\libaudioclient\AudioSystem.cpp

status_t AudioSystem::getMaxVolumeIndexForAttributes(const audio_attributes_t& attr, int& index) {
    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
    if (aps == 0) return PERMISSION_DENIED;

    media::AudioAttributesInternal attrAidl = VALUE_OR_RETURN_STATUS(
            legacy2aidl_audio_attributes_t_AudioAttributesInternal(attr));
    int32_t indexAidl;
    RETURN_STATUS_IF_ERROR(statusTFromBinderStatus(
            aps->getMaxVolumeIndexForAttributes(attrAidl, &indexAidl)));
    index = VALUE_OR_RETURN_STATUS(convertIntegral<int>(indexAidl));
    return OK;
}

4.进入IAudioPolicyService中进行获取

// establish binder interface to AudioPolicy service
const sp<IAudioPolicyService> AudioSystem::get_audio_policy_service() {
    sp<IAudioPolicyService> ap;
    sp<AudioPolicyServiceClient> apc;
    {
        Mutex::Autolock _l(gLockAPS);
        if (gAudioPolicyService == 0) {
            sp<IServiceManager> sm = defaultServiceManager();
            sp<IBinder> binder;
            do {
                binder = sm->getService(String16("media.audio_policy"));
                if (binder != 0)
                    break;
                ALOGW("AudioPolicyService not published, waiting...");
                usleep(500000); // 0.5 s
            } while (true);
            if (gAudioPolicyServiceClient == NULL) {
                gAudioPolicyServiceClient = new AudioPolicyServiceClient();
            }
            binder->linkToDeath(gAudioPolicyServiceClient);
            gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
            LOG_ALWAYS_FATAL_IF(gAudioPolicyService == 0);
            apc = gAudioPolicyServiceClient;
            // Make sure callbacks can be received by gAudioPolicyServiceClient
            ProcessState::self()->startThreadPool();
        }
        ap = gAudioPolicyService;
    }
    if (apc != 0) {
        int64_t token = IPCThreadState::self()->clearCallingIdentity();
        ap->registerClient(apc);
        ap->setAudioPortCallbacksEnabled(apc->isAudioPortCbEnabled());
        ap->setAudioVolumeGroupCallbacksEnabled(apc->isAudioVolumeGroupCbEnabled());
        IPCThreadState::self()->restoreCallingIdentity(token);
    }

    return ap;
}

最终进入到AudioPolicyManager进行获取

frameworks\av\services\audiopolicy\managerdefault\AudioPolicyManager.cpp

status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
                                                            int &index)
{
    index = getVolumeCurves(attr).getVolumeIndexMax();
    return NO_ERROR;
}

frameworks\av\services\audiopolicy\managerdefault\AudioPolicyManager.h

IVolumeCurves &getVolumeCurves(const audio_attributes_t &attr)
        {
            auto *curves = mEngine->getVolumeCurvesForAttributes(attr);
            ALOG_ASSERT(curves != nullptr, "No curves for attributes %s", toString(attr).c_str());
            return *curves;
        }

mEngine是EngineInstance 类型

EngineInstance mEngine;

frameworks\av\services\audiopolicy\engineconfigurable\src\EngineInstance.cpp

具体实现在frameworks\av\services\audiopolicy\engine\common\src\EngineBase.cpp

VolumeCurves *EngineBase::getVolumeCurvesForAttributes(const audio_attributes_t &attr) const
{
    volume_group_t volGr = mProductStrategies.getVolumeGroupForAttributes(attr);
    const auto &iter = mVolumeGroups.find(volGr);
    LOG_ALWAYS_FATAL_IF(iter == std::end(mVolumeGroups), "No volume groups for %s", toString(attr).c_str());
    return mVolumeGroups.at(volGr)->getVolumeCurves();
}

frameworks\av\services\audiopolicy\engine\common\include\VolumeCurve.h

int getVolumeIndexMax() const { return mIndexMax; }