Android音频子系统,音量的调节控制(七)

音量的调节控制:

按下音量的加减键,对应的keyevent是:KEYCODE_VOLUME_DOWN,KEYCODE_VOLUME_UP。

主要看两个地方对这一事件的处理,一是:handleKeyDown()@AudioManager.java,一是:

interceptKeyBeforeQueueing ()@PhoneWindowManager.java。

 

先看AudioManager.java类中的处理:

frameworks/base/media/java/android/media/

public void handleKeyDown(KeyEvent event, int stream) @AudioManager.java{
	int keyCode = event.getKeyCode();
	switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_UP:
		case KeyEvent.KEYCODE_VOLUME_DOWN:
//在key-down事件时,调整音量,要更灵敏的相应用户,这里的flags是FLAG_SHOW_UI | FLAG_VIBRATE,会显示进度条,有震动,
			adjustSuggestedStreamVolume(
keyCode == KeyEvent.KEYCODE_VOLUME_UP ? ADJUST_RAISE: ADJUST_LOWER,
stream, FLAG_SHOW_UI | FLAG_VIBRATE);
		break;
}
}
public void handleKeyUp(KeyEvent event, int stream) @AudioManager.java {
	nt keyCode = event.getKeyCode();
	switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_UP:
		case KeyEvent.KEYCODE_VOLUME_DOWN:
//在key-up时,播放调节音量的声音。
			adjustSuggestedStreamVolume(ADJUST_SAME, stream,
				FLAG_PLAY_SOUND);
}
}

根据音量加减键,进一步调用:adjustSuggestedStreamVolume。


public void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags) {
	MediaSessionLegacyHelper helper = MediaSessionLegacyHelper.getHelper(getContext());
	helper.sendAdjustVolumeBy(suggestedStreamType, direction, flags);
	往下的过程,会通过ISessionManager这个Binder client 句柄,把调节音量的请求传到AudioService。
	这个调用,接下来会走到MediaSessionService.java中,调用SessionManagerImpl中的方法:dispatchAdjustVolumeLocked (),SessionManagerImpl是ISessionManager的服务端的实现类。
	class SessionManagerImpl extends ISessionManager.Stub;
}

MediaSessionService.java

private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags,
	MediaSessionRecord session) @SessionManagerImpl{
	String packageName = getContext().getOpPackageName();
//这个mAudioService就是AUDIO_SERVICE = "audio"对应的Binder服务。所以请求就到了AudioService的server端。
	mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
		flags, packageName, TAG);
}

private void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags,
	String callingPackage, String caller, int uid) {
//声音分为STREAM_MUSIC,STREAM_VOICE_CALL,等多种流类型,当前要调节的是哪一种流类型的音量,先通过getActiveStreamType获取当前活跃的流类型。
先判断是不是在通话,如果是通话,还要分是蓝牙STREAM_BLUETOOTH_SCO,还是STREAM_VOICE_CALL;然后是不是播放音乐,
	int streamType;
	streamType = getActiveStreamType(suggestedStreamType);
//执行调整音量
	adjustStreamVolume(streamType, direction, flags, callingPackage, caller, uid);
}

adjustStreamVolume稍后分析,

下面看下PhoneWindowManager.java中对音量键的处理:

public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) 
@ PhoneWindowManager.java {
	final int keyCode = event.getKeyCode();
	switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_DOWN:
		case KeyEvent.KEYCODE_VOLUME_UP:
//对一些物理按键,系统有优先拦截的权利,做些预处理,这里会根据当前的具体情况,如是不是做截屏处理,是不是在通话等,然后决定需要调整的的stream类型。通过mediasession进一步处理按键事件,跟audiomanager类似。
			MediaSessionLegacyHelper.getHelper(mContext)
				.sendVolumeKeyEvent(event, true);
}
}
public void sendVolumeKeyEvent(KeyEvent keyEvent, boolean musicOnly) 
@ MediaSessionLegacyHelper.java {
//接下来的处理,就是通过MediaSessionManager.,SessionManagerImpl(位于MediaSessionService.java中),把请求传到audioservice那边。
	mSessionManager.dispatchAdjustVolume(
AudioManager.USE_DEFAULT_STREAM_TYPE, direction, flags);
}

接着看audioservice,如何处理音量调节的。

private void adjustStreamVolume(int streamType, int direction, int flags,
	String callingPackage, String caller, int uid) @ AudioService.java {
//step1,为streamType查找alias归类,使用流类型别名是为了让有相同别名的流,有相同的行为。
	int streamTypeAlias = mStreamVolumeAlias[streamType];
	VolumeStreamState streamState = mStreamStates[streamTypeAlias];
//step2,为streamtypealias寻找匹配的device。
	final int device = getDeviceForStream(streamTypeAlias);
//step3,获取对应的aliasindex
	int aliasIndex = streamState.getIndex(device);
//step4,调节index,把UI上的加1、减1的步骤,转成流别名上内部单元中的数字。
	step = rescaleIndex(10, streamType, streamTypeAlias);
//step5,对音量模式的影响,
	if (((flags & AudioManager.FLAG_ALLOW_RINGER_MODES) != 0) ||
		(streamTypeAlias == getUiSoundsStreamType())) {
		int ringerMode = getRingerModeInternal();
//如果已经是震动模式,就不要震动了
		if (ringerMode == AudioManager.RINGER_MODE_VIBRATE) {
		flags &= ~AudioManager.FLAG_VIBRATE;
}
//检查这个调节是否会改变铃声模式,而不仅仅是调节音量,如果是这样,就要设置合适的铃声模式,在流状态上音量指数。
final int result = checkForRingerModeChange(aliasIndex, direction, step,
	streamState.mIsMuted, callingPackage, flags);
adjustVolume = (result & FLAG_ADJUST_VOLUME) != 0;
}	
//step6,将调节音量的事件发给下一个处理者。
	int oldIndex = mStreamStates[streamType].getIndex(device);
	sendMsg(mAudioHandler, MSG_SET_DEVICE_VOLUME, SENDMSG_QUEUE,
		device, 0, streamState,0);
	int index = mStreamStates[streamType].getIndex(device);
	sendVolumeUpdate(streamType, oldIndex, index, flags);
}


Step1,流类型别名,虽然stream有多种类型,但他们在某些方面的行为是一样的,这就是stream-alias存在的意义。

private final int[] STREAM_VOLUME_ALIAS_DEFAULT = new int[] {
        AudioSystem.STREAM_VOICE_CALL,      // STREAM_VOICE_CALL
        AudioSystem.STREAM_RING,            // STREAM_SYSTEM
        AudioSystem.STREAM_RING,            // STREAM_RING
        AudioSystem.STREAM_MUSIC,           // STREAM_MUSIC
        AudioSystem.STREAM_ALARM,           // STREAM_ALARM
        AudioSystem.STREAM_RING,            // STREAM_NOTIFICATION
        AudioSystem.STREAM_BLUETOOTH_SCO,   // STREAM_BLUETOOTH_SCO
        AudioSystem.STREAM_RING,            // STREAM_SYSTEM_ENFORCED
        AudioSystem.STREAM_RING,            // STREAM_DTMF
        AudioSystem.STREAM_MUSIC            // STREAM_TTS
};

Step3,通过VolumeStreamState获取音量值

public int getIndex(int device) {
            synchronized (VolumeStreamState.class) {
                int index = mIndexMap.get(device, -1);
                if (index == -1) {
        // there is always an entry for AudioSystem.DEVICE_OUT_DEFAULT
                    index = mIndexMap.get(AudioSystem.DEVICE_OUT_DEFAULT);
                }
                return index;
            }
        } 

mIndexMap实际是个数组,不含映射的,记录了device对应的index值。

Step6,sendMsg把消息投到队列,有mAudioHandler处理,一方面把音量值保存到系统设置文件,另一方面调用audiopolicyservice接口调整音频设备的音量。

private void persistVolume(VolumeStreamState streamState, int device) 
@ AudioHandler$ AudioService.java {
//把音量值写到系统文件。
	System.putIntForUser(mContentResolver,
		streamState.getSettingNameForDevice(device),
		(streamState.getIndex(device) + 5)/ 10,
		UserHandle.USER_CURRENT);
}

调用audiopolicyservice接口的流程:

public void applyDeviceVolume_syncVSS(int device)@ VolumeStreamState $ AudioService.java {
	AudioSystem.setStreamVolumeIndex(mStreamType, index, device);
}

setStreamVolumeIndex是native方法。

status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,…)
@ AudioSystem.cpp {
	const sp& aps = AudioSystem::get_audio_policy_service();
	return aps->setStreamVolumeIndex(stream, index, device);
}

IAudioPolicyService对应的服务端的实现:

status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream, int index, 
audio_devices_t device)@AudioPolicyInterfaceImplLegacy.cpp{
	return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
}

根据前面的分析,mpAudioPolicy的默认实现是legacy_audio_policy 结构体中的audio_policy 。相关实现(create_legacy_ap()@audio_policy_hal.cpp);

static int ap_set_stream_volume_index(struct audio_policy *pol, audio_stream_type_t stream,
	int index)@ audio_policy_hal.cpp {
	struct legacy_audio_policy *lap = to_lap(pol);
	return lap->apm->setStreamVolumeIndex((AudioSystem::stream_type)stream,
		index, AUDIO_DEVICE_OUT_DEFAULT);
}


setStreamVolumeIndex的最终实现调用了AudioPolicyManagerBase.cpp中接口。

status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
	int index, audio_devices_t device)@ AudioPolicyManagerBase.cpp {
//根据连接的设备,在所有的输出上计算、应用流音量,
	for (size_t i = 0; i < mOutputs.size(); i++) {
		audio_devices_t curDevice = getDeviceForVolume(mOutputs.valueAt(i)->device());
		if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), 
curDevice);
			status = volStatus;
		}
	}
	return status;
}

系统中有多个output,每个output又支持多个device,所以checkAndSetVolume函数,先计算音量,最终会调用Audioflinger的接口完成音量的设置。

主要看跳转到Audioflinger的流程:

status_t AudioPolicyManagerBase::checkAndSetVolume(…)@ AudioPolicyManagerBase.cpp{
	mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, 
delayMs);
}

AudioPolicyClientInterface*mpClientInterface;是在AudioPolicyManagerBase构造函数中赋值的。调用AudioPolicyManagerBase构造函数的根在audio_policy_hal.cpp

static int create_legacy_ap(struct audio_policy_service_ops *aps_ops,…)@ audio_policy_hal.cpp {
	lap->service_client = new AudioPolicyCompatClient(aps_ops, service);
//这个函数最终创建了AudioPolicyManagerBase实例。
	lap->apm = createAudioPolicyManager(lap->service_client);
}
status_t AudioPolicyCompatClient::setStreamVolume(…){
// mServiceOps即是函数create_legacy_ap中的aps_ops。想知道aps_ops是怎么来的,就是要知道谁调用了create_legacy_ap。
	return mServiceOps->set_stream_volume(mService, (audio_stream_type_t)stream,
		volume, output, delayMs);
}

想知道create_legacy_ap函数中的参数aps_ops是怎么来的,就是要知道谁调用了create_legacy_ap。

audio_policy_hal.cpp

//在打开一个hal层设备时,会执行这个函数:


static int legacy_ap_dev_open(…)@ audio_policy_hal.cpp{
	dev->device.create_audio_policy = create_legacy_ap;
}

函数指针create_audio_policy指向了create_legacy_ap。

AudioPolicyService.cpp

在AudioPolicyService实例第一次被引用时:

void AudioPolicyService::onFirstRef()@AudioPolicyService.cpp{
//create_legacy_ap函数中的参数aps_op是在这里赋值的(aps_ops)
	rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,
		&mpAudioPolicy);
}

根据aps_ops 结构体的定义,set_stream_volume实现指向了aps_set_stream_volume。

struct audio_policy_service_ops aps_ops = {
	.set_stream_volume     = aps_set_stream_volume,
}

有函数aps_set_stream_volume,经过AudioPolicyService.cpp,经过AudioCommandThread的SET_VOLUME命令,在经过AudioSystem.cpp,最终实现是在Audioflinger。

status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
        audio_io_handle_t output)@ AudioSystem.cpp {
	af->setStreamVolume(stream, value, output);
	const sp& af = AudioSystem::get_audio_flinger();
}
status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
        audio_io_handle_t output)@ AudioFlinger.cpp {
	PlaybackThread *thread = NULL;
//根据output找到对应的playbackthread,
	thread = checkPlaybackThread_l(output);
//把新的值记录到mStreamTypes中。
	mStreamTypes[stream].volume = value;
	thread->setStreamVolume(stream, value);
}


然后playbackthread对音量值做下记录,在混音线程准备音频数据时,会把playbackthread保存的值提取出来。

Frameworks/av/services/audiofligner/

AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
        Vector< sp > *tracksToRemove)@ Threads.cpp{
//读取音量控制的原始值。
	float typeVolume = mStreamTypes[track->streamType()].volume;
	float v = masterVolume * typeVolume;
	vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
	vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
//应用主音量和流类型音量。
	vlf *= v;
	vrf *= v;
	mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, &vlf);
	mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, &vrf);
}

读出之前这种的音量值后,和主音量综合运算,把计算后的值,通过setParameter传给AudioMixer。


你可能感兴趣的:(Android音频子系统,音量的调节控制(七))