Audio java部分代碼流程(4.1.2 version):
在frameworks/base/media/java/android/media中:
IAudioService.aidl提供了所有對外的接口函數,如下:
[cpp]
interface IAudioService {
void adjustVolume(int direction, int flags);
void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags);
void adjustStreamVolume(int streamType, int direction, int flags);
void setStreamVolume(int streamType, int index, int flags);
void setStreamSolo(int streamType, boolean state, IBinder cb);
void setStreamMute(int streamType, boolean state, IBinder cb);
boolean isStreamMute(int streamType);
int getStreamVolume(int streamType);
int getStreamMaxVolume(int streamType);
int getLastAudibleStreamVolume(int streamType);
void setRingerMode(int ringerMode);
.......................
}
這些函數的實現在服務AudioService.java中:
[cpp]
public class AudioService extends IAudioService.Stub {
........
}
該服務在services/java/com/android/server/SystemServer.java中注冊進servicemanager中:
[cpp]
492 try {
493 Slog.i(TAG, "Audio Service");
494 ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
495 } catch (Throwable e) {
496 reportWtf("starting Audio Service", e);
497 }
這樣在frameworks中可以通過ServiceManager.getService(Context.AUDIO_SERVICE)來獲得該服務。
而AudioManager.java則實現這些函數了對外應用的接口,比如:
[cpp]
496 public void adjustVolume(int direction, int flags) {
497 IAudioService service = getService(); //
498 try {
499 service.adjustVolume(direction, flags);
500 } catch (RemoteException e) {
501 Log.e(TAG, "Dead object in adjustVolume", e);
502 }
503 }
這裡的getService()獲得的是前面的AudioService,如下:
[cpp]
365 private static IAudioService getService()
366 {
367 if (sService != null) {
368 return sService;
369 }
370 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
371 sService = IAudioService.Stub.asInterface(b);
372 return sService;
373 }
要把AudioManager.java中的對外公開,則要在 core/java/android/app/ContextImpl.java中注冊:
[cpp]
281 registerService(AUDIO_SERVICE, new ServiceFetcher() {
282 public Object createService(ContextImpl ctx) {
283 return new AudioManager(ctx);
284 }});
而且,還要把這些函數變量等在api/current.txt中聲明:
[cpp]
10353 public class AudioManager {
10354 method public int abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener);
10355 method public void adjustStreamVolume(int, int, int);
10356 method public void adjustSuggestedStreamVolume(int, int, int);
10357 method public void adjustVolume(int, int);
10358 method public int getMode();
10359 method public java.lang.String getParameters(java.lang.String);
10360 method public int getRingerMode();
10361 method public deprecated int getRouting(int);
10362 method public int getStreamMaxVolume(int);
10363 method public int getStreamVolume(int);
10364 method public int getVibrateSetting(int);
10365 method public boolean isBluetoothA2dpOn();
這樣在應用中用(AudioManager) getSystemService(Context.AUDIO_SERVICE);即可獲得服務,從而使用AudioManager.java中的方法然後看看比如setStreamVolume是如何從java調用到底層的:
1、應用調用比如mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
2、AudioManager.java調用public void setStreamVolume(int streamType, int index, int flags){};
3、AudioService.java調用public void setStreamVolume(int streamType, int index, int flags){},在該函數中調用
[cpp]
setStreamVolumeInt(mStreamVolumeAlias[streamType],
831 index,
832 device,
833 false,
834 true);
-------->
1002 sendMsg(mAudioHandler,
1003 MSG_PERSIST_VOLUME,
1004 SENDMSG_QUEUE,
1005 PERSIST_LAST_AUDIBLE,
1006 device,
1007 streamState,
1008 PERSIST_DELAY);
而mAudioHandler = new AudioHandler(),看看這個AudioHandler類:private class AudioHandler extends Handler {};-------->
所以調用該類重寫的handleMessage方法--------->
[cpp]
2940 @Override
2941 public void handleMessage(Message msg) {
2942
2943 switch (msg.what) {
2944
2945 case MSG_SET_DEVICE_VOLUME:
2946 setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);
2947 break;
setDeviceVolume---------> mStreamStates[streamType].applyDeviceVolume(getDeviceForStream(streamType));---------->AudioSystem.setStreamVolumeIndex--------->
setStreamVolumeIndex的定義在AudioSystem.java中-------->public static native int setStreamVolumeIndex(int stream, int index, int device);
setStreamVolumeIndex的JNI實現在base/core/jni/android_media_AudioSystem.cpp中---------->
[cpp]
178 static int
179 android_media_AudioSystem_setStreamVolumeIndex(JNIEnv *env,
180 jobject thiz,
181 jint stream,
182 jint index,
183 jint device)
184 {
185 return check_AudioSystem_Command(
186 AudioSystem::setStreamVolumeIndex(static_cast <audio_stream_type_t>(stream),
187 index,
188 (audio_devices_t)device));
189 }
AudioSystem類在av/media/libmedia/AudioSystem.cpp中--------->
[cpp]
666 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,
667 int index,
668 audio_devices_t device)
669 {
670 const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();
671 if (aps == 0) return PERMISSION_DENIED;
672 return aps->setStreamVolumeIndex(stream, index, device);
673 }
到這裡就要涉及到進程間通訊binder的使用了,我們看AudioSystem::get_audio_policy_service()的實現:
[cpp]
514 const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()
515 {
516 gLock.lock();
517 if (gAudioPolicyService == 0) {
518 sp<IServiceManager> sm = defaultServiceManager();//取得BpServiceManager,通過這個代理可以調用BnServiceManager::onTransact,最後和ServiceManager通訊
519 sp<IBinder> binder;
520 do {
521 binder = sm->getService(String16("media.audio_policy"));//從ServiceManager獲得遠程AudioPolicyService的句柄
522 if (binder != 0)
523 break;
524 ALOGW("AudioPolicyService not published, waiting...");
525 usleep(500000); // 0.5 s
526 } while (true);
527 if (gAudioPolicyServiceClient == NULL) {
528 gAudioPolicyServiceClient = new AudioPolicyServiceClient();
529 }
530 binder->linkToDeath(gAudioPolicyServiceClient);
531 gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);
532 gLock.unlock();
533 } else {
534 gLock.unlock();
535 }
536 return gAudioPolicyService;
537 }
上面531行interface_cast<IAudioPolicyService>(binder),interface_cast是一個模版,在frameworks/native/include/binder/IInterface.h中定義如下:
[cpp]
42 inline sp<INTERFACE> interface_cast(const sp<IBinder>&obj)
43 {
44 return INTERFACE::asInterface(obj);
45 }
展開後是IAudioPolicyService::asInterface(obj);而IAudioPolicyService::asInterface的實現在frameworks/av/include/media/IAudioPolicyService.h中,通過宏
[cpp]
DECLARE_META_INTERFACE(AudioPolicyService)展開後得到的,DECLARE_META_INTERFACE定義在IInterface.h中:
74 #define DECLARE_META_INTERFACE(INTERFACE) \
75 static const android::String16 descriptor; \
76 static android::sp<I##INTERFACE> asInterface( \
77 const android::sp<android::IBinder>& obj); \
78 virtual const android::String16& getInterfaceDescriptor() const; \
79 I##INTERFACE(); \
80 virtual ~I##INTERFACE();
76行展開即可得到IAudioPolicyService::asInterface的定義,而這個定義的實現也是在IInterface.h,通過宏來定義的:
[cpp]
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)
........................
89 android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
90 const android::sp<android::IBinder>& obj) \
91 { \
92 android::sp<I##INTERFACE> intr; \
93 if (obj != NULL) { \
94 intr = static_cast<I##INTERFACE*>( \
95 obj->queryLocalInterface( \
96 I##INTERFACE::descriptor).get()); \
97 if (intr == NULL) { \
98 intr = new Bp##INTERFACE(obj); \
99 } \
100 } \
101 return intr; \
102 }
展開後最終是生成調用new BpAudioPolicyService(new BpBinder(handle)),這裡的handle是一個句柄;這樣我們最終得到了AudioPolicyService的代理BpAudioPolicyService,通過它就可以和AudioPolicyService的本地接口BnAudioPolicyService通訊了。
回到前面的AudioSystem.cpp,取得代理BpAudioPolicyService後調用aps->setStreamVolumeIndex,所以進入IAudioPolicyService.cpp:
class BpAudioPolicyService : public BpInterface<IAudioPolicyService>:
[cpp]
233 virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
234 int index,
235 audio_devices_t device)
236 {
237 Parcel data, reply;
238 data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());
239 data.writeInt32(static_cast <uint32_t>(stream));
240 data.writeInt32(index);
241 data.writeInt32(static_cast <uint32_t>(device));
242 remote()->transact(SET_STREAM_VOLUME, data, &reply);
243 return static_cast <status_t> (reply.readInt32());
244 }
242行的remote是通過繼承關系BpAudioPolicyService -> BpInterface -> BpRefBase,在類BpRefBase中定義的:
[cpp]
inline IBinder* remote() { return mRemote; }
IBinder* const mRemote;
這裡mRemote聲明為const,可見它是靜態不變,只賦值一次,它是在前面獲取遠程服務AudioPolicyService時候創建的BpBinder對象(主要是打開了binder驅動,獲得FD描述符,並且內存映射了空間),所以調用BpBinder.cpp的transact函數:
[cpp]
159 status_t BpBinder::transact(
160 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
161 {
162 // Once a binder has died, it will never come back to life.
163 if (mAlive) {
164 status_t status = IPCThreadState::self()->transact(
165 mHandle, code, data, reply, flags);
166 if (status == DEAD_OBJECT) mAlive = 0;
167 return status;
168 }
169
170 return DEAD_OBJECT;
171 }
從164行,調用IPCThreadState.cpp的transact,這裡就是最終和binder驅動打交道的地方了,165行通過mHandle,底層binder驅動知道了傳輸數據的目標地址為mediaserver進程,binder驅動將數據拷貝到service的內存共享空間,並告訴service這個內核空間相對用戶空間的偏移,遠程服務端就可以不用再次拷貝數據,直接從用戶空間就可以讀取數據了, 這樣remote()->transact(SET_STREAM_VOLUME, data, &reply)就通過binder傳遞到BnAudioPolicyService中了,這樣就調用IAudioPolicyService.cpp的BnAudioPolicyService::onTransact函數來處理該請求(但由於繼承關系最終是派發到Bn的派生類AudioPolicyService::onTransact來處理,不過我們後面也會發現派生類又調回Bn類的onTransact去處理,很有意思啊),我們看看BnAudioPolicyService是如何獲得remote()->transact(SET_STREAM_VOLUME, data, &reply)的請求的,這樣要從AudioPolicyService是如何將自己的服務添加到servicemanager中的說起,在frameworks/av/media/mediaserver/main_mediaserver.cpp中:
[cpp]
34 int main(int argc, char** argv)
35 {
36 sp<ProcessState> proc(ProcessState::self());
37 sp<IServiceManager> sm = defaultServiceManager();
38 ALOGI("ServiceManager: %p", sm.get());
39 AudioFlinger::instantiate();
40 MediaPlayerService::instantiate();
41 CameraService::instantiate();
42 AudioPolicyService::instantiate();
43 ProcessState::self()->startThreadPool();
44 IPCThreadState::self()->joinThreadPool();
45 }
36行,由於main_mediaserver.cpp是編譯成一個可執行文件,就是它的啟動是作為服務在一個獨立的進程中運行了,Main_MediaServer主函數由init.rc在啟動時調用,先明白這點,然後看:
frameworks/native/libs/binder/ProcessState.cpp:
[cpp]
74 sp<ProcessState> ProcessState::self()
75 {
76 Mutex::Autolock _l(gProcessMutex);
77 if (gProcess != NULL) {
78 return gProcess;
79 }
80 gProcess = new ProcessState;
81 return gProcess;
82 }
從77行可知,這是一個單例模式,在這個進程中以後再調用這個函數的話,就直接返回78行,這裡我們第一次進來,所以跑到80行,進入ProcessState構造函數:
[cpp]
335 ProcessState::ProcessState()
336 : mDriverFD(open_driver())
337 , mVMStart(MAP_FAILED)
338 , mManagesContexts(false)
339 , mBinderContextCheckFunc(NULL)
340 , mBinderContextUserData(NULL)
341 , mThreadPoolStarted(false)
342 , mThreadPoolSeq(1)
343 {
344 if (mDriverFD >= 0) {
345 // XXX Ideally, there should be a specific define for whether we
346 // have mmap (or whether we could possibly have the kernel module
347 // availabla).
348 #if !defined(HAVE_WIN32_IPC)
349 // mmap the binder, providing a chunk of virtual address space to receive transactions.
350 mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
.................................
}
336行打開Binder設備文件/dev/binder,並將打開設備文件描述符保存在成員變量mDriverFD中;350行mmap來把設備文件/dev/binder映射到內存中,這樣我們就有了一塊共享內存。
回到main_mediaserver.cpp,37行defaultServiceManager(),在frameworks/native/libs/binder/IServiceManager.cpp中:
[cpp]
34 sp<IServiceManager> defaultServiceManager()
35 {
36 if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
37
38 {
39 AutoMutex _l(gDefaultServiceManagerLock);
40 if (gDefaultServiceManager == NULL) {
41 gDefaultServiceManager = interface_cast<IServiceManager>(
42 ProcessState::self()->getContextObject(NULL));
43 }
44 }
45
46 return gDefaultServiceManager;
47 }
和前面一樣,也是一個單例模式,第一次進來肯定為NULL,所以進入41行,ProcessState::self()前面已經運行過一次,直接調用getContextObject(NULL),注意傳進來的是NULL參數,表示和ServiceManager通訊:
[cpp]
89 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)
90 {
91 return getStrongProxyForHandle(0);
92 }
getStrongProxyForHandle(0)最終會調用new BpBinder(0),這樣我們就得到了ServiceManager的代理BpBinder,回到IServiceManager.cpp的41行,就變成了interface_cast<IServiceManager>(new BpBinder(0)),interface_cast在前面已經分析過,所以最後變成new BpServiceManager(new BpBinder(0))。接著進入main_mediaserver.cpp42行AudioPolicyService::instantiate(),先看看frameworks/av/services/audioflinger/AudioPolicyService.h中的繼承關系:
[cpp]
37 class AudioPolicyService :
38 public BinderService<AudioPolicyService>,
39 public BnAudioPolicyService,
40 // public AudioPolicyClientInterface,
41 public IBinder::DeathRecipient
AudioPolicyService並沒有實現instantiate方法,而是繼承BinderService得到的,該類在frameworks/native/include/binder/BinderService.h中:
[cpp]
33 template<typename SERVICE>
34 class BinderService
35 {
36 public:
37 static status_t publish(bool allowIsolated = false) {
38 sp<IServiceManager> sm(defaultServiceManager());
39 return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
40 }
41
42 static void publishAndJoinThreadPool(bool allowIsolated = false) {
43 sp<IServiceManager> sm(defaultServiceManager());
44 sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
45 ProcessState::self()->startThreadPool();
46 IPCThreadState::self()->joinThreadPool();
47 }
48
49 static void instantiate() { publish(); }
50
51 static status_t shutdown() {
52 return NO_ERROR;
53 }
54 };
這是一個類模版,最終調用39行,得到sm->addService(String16(AudioPolicyService::getServiceName()), new AudioPolicyService(), false)即:
BpServiceManager(new BpBinder(0))->addService(String16("media.audio_policy", new AudioPolicyService(), false),進入BpServiceManger::addService的實現,這個函數實現在frameworks/native/libs/binder/IServiceManager.cpp:
[cpp]
154 virtual status_t addService(const String16& name, const sp<IBinder>&service, bool allowIsolated)
156 {
157 Parcel data, reply;
158 data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
159 data.writeString16(name);
160 data.writeStrongBinder(service);
161 data.writeInt32(allowIsolated ? 1 : 0);
162 status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
163 return err == NO_ERROR ? reply.readExceptionCode() : err;
164 }
這裡162行remote流程和前面分析的差不多,最終調用IPCThreadState.cpp的transact,這裡就是最終和binder驅動打交道的地方了,binder即為前面main_mediaserver.cpp中36行ProcessState::ProcessState打開的驅動,用這塊共享內存和servicemanager打交道,在底層的內核空間binder驅動會根據傳進來的mHandle值判斷目標服務地址,這裡的mHandle為0,所以調整servermanager的buffer指向本地內存共享空間,接著往下看main_mediaserver.cpp的43行ProcessState::self()->startThreadPool(),在frameworks/native/libs/binder/ProcessState.cpp中:
[cpp]
136 void ProcessState::startThreadPool()
137 {
138 AutoMutex _l(mLock);
139 if (!mThreadPoolStarted) {
140 mThreadPoolStarted = true;
141 spawnPooledThread(true);
142 }
143 }
看141行:
[cpp]
286 void ProcessState::spawnPooledThread(bool isMain)
287 {
288 if (mThreadPoolStarted) {
289 int32_t s = android_atomic_add(1, &mThreadPoolSeq);
290 char buf[16];
291 snprintf(buf, sizeof(buf), "Binder_%X", s);
292 ALOGV("Spawning new pooled thread, name=%s\n", buf);
293 sp<Thread> t = new PoolThread(isMain);
294 t->run(buf);
295 }
296 }
293行創建了線程,PoolThread類繼承列thread類,ProcessState.cpp中::
[cpp]
56 class PoolThread : public Thread
57 {
58 public:
59 PoolThread(bool isMain)
60 : mIsMain(isMain)
61 {
62 }
63
64 protected:
65 virtual bool threadLoop()
66 {
67 IPCThreadState::self()->joinThreadPool(mIsMain);
68 return false;
69 }
70
71 const bool mIsMain;
72 };
294行執行線程,thread在frameworks/native/libs/utils/Threads.cpp中,這樣run函數最終調用子類的threadLoop函數,看67行,調用的和main_mediaserver.cpp的44行一樣,進入IPCThreadState.cpp中,result =talkWithDriver()等待client請求,最終會調用 executeCommand(cmd)函數來處理請求,而在executeCommand函數中,最終會調用BBinder::transact來真正處理Client的請求,接下來再看一下BBinder::transact的實現,frameworks/native/libs/binder/Binder.cpp中:
[cpp]
97 status_t BBinder::transact(
98 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
99 {
100 data.setDataPosition(0);
101
102 status_t err = NO_ERROR;
103 switch (code) {
104 case PING_TRANSACTION:
105 reply->writeInt32(pingBinder());
106 break;
107 default:
108 err = onTransact(code, data, reply, flags);
109 break;
110 }
111
112 if (reply != NULL) {
113 reply->setDataPosition(0);
114 }
115
116 return err;
117 }
108行,調用onTransact方法,由於這裡的繼承關系,在前面分析main_mediaserver.cpp的42行AudioPolicyService::instantiate()就知道,這裡創建的是AudioPolicyService類,這樣由於虛函數onTransact的繼承關系,最終調用了AudioPolicyService的onTransact方法,AudioPolicyService.cpp中:
[cpp]
610 status_t AudioPolicyService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
612 {
613 return BnAudioPolicyService::onTransact(code, data, reply, flags);
614 }
613行調用的還是基類BnAudioPolicyService的方法.
到這裡BpAudioPolicyService和BnAudioPolicyService的binder通訊關系就完成了,回到前面IAudioPolicyService.cpp中的242行remote()->transact(SET_STREAM_VOLUME, data, &reply);這裡傳進來的是SET_STREAM_VOLUME,所以調用BnAudioPolicyService::onTransact:
[cpp]
512 case SET_STREAM_VOLUME:{
513 CHECK_INTERFACE(IAudioPolicyService, data, reply);
514 audio_stream_type_t stream =
515 static_cast <audio_stream_type_t>(data.readInt32());
516 int index = data.readInt32();
517 audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());
518 reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream,
519 index,
520 device)));
521 return NO_ERROR;
522 } break;
518行AudioPolicyService覆蓋了BpAudioPolicyService的setStreamVolumeIndex方法,所以最終調用了AudioPolicyService.cpp的setStreamVolumeIndex方法:
[cpp]
380 status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,
381 int index,
382 audio_devices_t device)
383 {
384 if (mpAudioPolicy == NULL) {
385 return NO_INIT;
386 }
387 if (!settingsAllowed()) {
388 return PERMISSION_DENIED;
389 }
390 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
391 return BAD_VALUE;
392 }
393
394 if (mpAudioPolicy->set_stream_volume_index_for_device) {
395 return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,
396 stream,
397 index,
398 device);
399 } else {
400 return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);
401 }
402 }
總結上面binder的通訊機制,理解了類之間的繼承派生關系,也就能把來龍去脈弄清楚,主要還是熟悉C++才行,還有要理解binder通訊的設計原理,即每個服務或者想要獲得服務的進程都會打開binder節點,並且內存映射有一塊空間,傳送數據時候,binder驅動根據client傳進來的數據大小、位置和目標service(在驅動中用target_proc來表示),用binder_alloc_buf函數在目標service之前mmap時候分配的內核空間中申請空間,然後用copy_from_user將數據從用戶空間拷貝到內核的這塊空間中來,又因為service端之前mmap申請內核空間的時候已經記錄了這塊空間在內核中和用戶空間的偏移量,從而計算binder_alloc_buf分配得到的內核空間對應用戶空間的地址,最後將該地址拷貝到service的用戶空間,service端就可以得到數據了,通過這樣的淺拷貝即可實現進程間傳輸數據只用拷貝一次即可的原理。繼續從AudioPolicyService.cpp往下走。先看它的構造函數:
[cpp]
58 AudioPolicyService::AudioPolicyService()
59 : BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)
60 {
61 char value[PROPERTY_VALUE_MAX];
62 const struct hw_module_t *module;
63 int forced_val;
64 int rc;
65
66 Mutex::Autolock _l(mLock);
67
68 // start tone playback thread
69 mTonePlaybackThread = new AudioCommandThread(String8(""));
70 // start audio commands thread
71 mAudioCommandThread = new AudioCommandThread(String8("ApmCommand"));
72
73 /* instantiate the audio policy manager */
74 rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);
75 if(rc)
76 return;
77
78 rc = audio_policy_dev_open(module, &mpAudioPolicyDev);
79 ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));
80 if (rc)
81 return;
82
83 rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,
84 &mpAudioPolicy);
85 ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));
86 if (rc)
87 return;
88
89 rc = mpAudioPolicy->init_check(mpAudioPolicy);
90 ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));
91 if (rc)
92 return;
.......................
}
74行AUDIO_POLICY_HARDWARE_MODULE_ID定義在libhardware/include/hardware/audio_policy.h中,
#define AUDIO_POLICY_HARDWARE_MODULE_ID "audio_policy"
根據hw_get_module的判斷關系,看hardware/libhardware_legacy/audio/Android.mk可知,最終調用的是audio_policy.default.so,通過hw_get_module函數的load(class_id, path, module)打開audio_policy.default.so並返回句柄,接著78行audio_policy_dev_open,在libhardware/include/hardware/audio_policy.h
[cpp]
424 static inline int audio_policy_dev_open(const hw_module_t* module,
425 struct audio_policy_device** device)
426 {
427 return module->methods->open(module, AUDIO_POLICY_INTERFACE,
428 (hw_device_t**)device);
429 }
這樣就調用了hardware/libhardware_legacy/audio/audio_policy_hal.cpp的open方法:
[cpp]
406 static int legacy_ap_dev_open(const hw_module_t* module, const char* name, hw_device_t** device)
408 {
409 struct legacy_ap_device *dev;
411 if (strcmp(name, AUDIO_POLICY_INTERFACE) != 0)
412 return -EINVAL;
414 dev = (struct legacy_ap_device *)calloc(1, sizeof(*dev));
415 if (!dev)
416 return -ENOMEM;
418 dev->device.common.tag = HARDWARE_DEVICE_TAG;
419 dev->device.common.version = 0;
420 dev->device.common.module = const_cast<hw_module_t*>(module);
421 dev->device.common.close = legacy_ap_dev_close;
422 dev->device.create_audio_policy = create_legacy_ap;
423 dev->device.destroy_audio_policy = destroy_legacy_ap;
425 *device = &dev->device.common;
427 return 0;
428 }
結構體legacy_ap_device定義:
[cpp]
40 struct legacy_ap_device {
41 struct audio_policy_device device;
42 };
結構體audio_policy_device定義:
[cpp]
410 struct audio_policy_device {
411 struct hw_device_t common;
412
413 int (*create_audio_policy)(const struct audio_policy_device *device,
414 struct audio_policy_service_ops *aps_ops,
415 void *service,
416 struct audio_policy **ap);
417
418 int (*destroy_audio_policy)(const struct audio_policy_device *device,
419 struct audio_policy *ap);
420 };
所以這裡open的425行*device = &dev->device.common賦值的雖然是結構體audio_policy_device的成員common的地址,但是common位於結構體首地址,也就是相當於返回了audio_policy_device結構體的地址。所以接著AudioPolicyService.cpp的83行調用的是audio_policy_device的create_audio_policy,它指向create_legacy_ap函數:
[cpp]
311 static int create_legacy_ap(const struct audio_policy_device *device,
312 struct audio_policy_service_ops *aps_ops,
313 void *service,
314 struct audio_policy **ap)
315 {
316 struct legacy_audio_policy *lap;
317 int ret;
318
319 if (!service || !aps_ops)
320 return -EINVAL;
321
322 lap = (struct legacy_audio_policy *)calloc(1, sizeof(*lap));
323 if (!lap)
324 return -ENOMEM;
325
326 lap->policy.set_device_connection_state = ap_set_device_connection_state;
327 lap->policy.get_device_connection_state = ap_get_device_connection_state;
328 lap->policy.set_phone_state = ap_set_phone_state;
329 lap->policy.set_ringer_mode = ap_set_ringer_mode;
330 lap->policy.set_force_use = ap_set_force_use;
331 lap->policy.get_force_use = ap_get_force_use;
332 lap->policy.set_can_mute_enforced_audible = ap_set_can_mute_enforced_audible;
334 lap->policy.init_check = ap_init_check;
335 lap->policy.get_output = ap_get_output;
336 lap->policy.start_output = ap_start_output;
337 lap->policy.stop_output = ap_stop_output;
338 lap->policy.release_output = ap_release_output;
339 lap->policy.get_input = ap_get_input;
340 lap->policy.start_input = ap_start_input;
341 lap->policy.stop_input = ap_stop_input;
342 lap->policy.release_input = ap_release_input;
343 lap->policy.init_stream_volume = ap_init_stream_volume;
344 lap->policy.set_stream_volume_index = ap_set_stream_volume_index;
345 lap->policy.get_stream_volume_index = ap_get_stream_volume_index;
346 lap->policy.set_stream_volume_index_for_device = ap_set_stream_volume_index_for_device;
347 lap->policy.get_stream_volume_index_for_device = ap_get_stream_volume_index_for_device;
348 lap->policy.get_strategy_for_stream = ap_get_strategy_for_stream;
349 lap->policy.get_devices_for_stream = ap_get_devices_for_stream;
350 lap->policy.get_output_for_effect = ap_get_output_for_effect;
351 lap->policy.register_effect = ap_register_effect;
352 lap->policy.unregister_effect = ap_unregister_effect;
353 lap->policy.set_effect_enabled = ap_set_effect_enabled;
354 lap->policy.is_stream_active = ap_is_stream_active;
355 lap->policy.dump = ap_dump;
356
357 lap->service = service;
358 lap->aps_ops = aps_ops;
359 lap->service_client =
360 new AudioPolicyCompatClient(aps_ops, service);
361 if (!lap->service_client) {
362 ret = -ENOMEM;
363 goto err_new_compat_client;
364 }
365
366 lap->apm = createAudioPolicyManager(lap->service_client);
367 if (!lap->apm) {
368 ret = -ENOMEM;
369 goto err_create_apm;
370 }
371
372 *ap = &lap->policy;
373 return 0;
374
375 err_create_apm:
376 delete lap->service_client;
377 err_new_compat_client:
378 free(lap);
379 *ap = NULL;
380 return ret;
381 }
372行可知,這樣mpAudioPolicy指針就指向了lap->policy方法。回到前面AudioPolicyService::setStreamVolumeIndex的394行調用audio_policy_hal.cpp方法:
[cpp]
232 static int ap_set_stream_volume_index_for_device(struct audio_policy *pol,
233 audio_stream_type_t stream,
234 int index,
235 audio_devices_t device)
236 {
237 struct legacy_audio_policy *lap = to_lap(pol);
238 return lap->apm->setStreamVolumeIndex((AudioSystem::stream_type)stream,
239 index,
240 device);
241 }
237行結構體legacy_audio_policy定義:
[cpp]
44 struct legacy_audio_policy {
45 struct audio_policy policy;//即為mpAudioPolicy
46
47 void *service;
48 struct audio_policy_service_ops *aps_ops;
49 AudioPolicyCompatClient *service_client;
50 AudioPolicyInterface *apm;
51 };
lap->apm的賦值在前面create_legacy_ap函數的366行,看createAudioPolicyManager,hardware/libhardware_legacy/audio/AudioPolicyManagerDefault.cpp中:
[cpp
24 extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
25 {
26 return new AudioPolicyManagerDefault(clientInterface);
27 }
----->hardware/libhardware_legacy/audio/AudioPolicyManagerDefault.h:
[cpp]
25 class AudioPolicyManagerDefault: public AudioPolicyManagerBase
26 {
28 public:
29 AudioPolicyManagerDefault(AudioPolicyClientInterface *clientInterface)
30 : AudioPolicyManagerBase(clientInterface) {}
31
32 virtual ~AudioPolicyManagerDefault() {}
33
34 };
看基類AudioPolicyManagerBase,hardware/libhardware_legacy/include/hardware_legacy/AudioPolicyManagerBase.h的定義,終於找到了setStreamVolumeIndex方法,
在AudioPolicyManagerBase.cpp中:
[cpp]
953 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index, audio_devices_t device)
956 {
958 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
959 return BAD_VALUE;
960 }
961 if (!audio_is_output_device(device)) {
962 return BAD_VALUE;
963 }
965 // Force max volume if stream cannot be muted
966 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
971 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
972 // clear all device specific values
973 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
974 mStreams[stream].mIndexCur.clear();
975 }
976 mStreams[stream].mIndexCur.add(device, index);
978 // compute and apply stream volume on all outputs according to connected device
979 status_t status = NO_ERROR;
980 for (size_t i = 0; i < mOutputs.size(); i++) {
981 audio_devices_t curDevice =
982 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
983 if (device == curDevice) {
984 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
985 if (volStatus != NO_ERROR) {
986 status = volStatus;
987 }
988 }
989 }
990 return status;
991 }
看984行checkAndSetVolume函數:
[cpp]
2683 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2684 int index,
2685 audio_io_handle_t output,
2686 audio_devices_t device,
2687 int delayMs,
2688 bool force)
2689 {
....................
2722 if (stream == AudioSystem::BLUETOOTH_SCO) {
2723 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2724 }
2725 }
2726
2727 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
...................
2747 }
這裡mpClientInterface是在AudioPolicyManagerBase構造函數中賦值的,就是create_legacy_ap函數360行AudioPolicyCompatClient,方法在AudioPolicyCompatClient.cpp:
[cpp]
120 status_t AudioPolicyCompatClient::setStreamVolume(
121 AudioSystem::stream_type stream,
122 float volume,
123 audio_io_handle_t output,
124 int delayMs)
125 {
126 return mServiceOps->set_stream_volume(mService, (audio_stream_type_t)stream,
127 volume, output, delayMs);
128 }
這裡是在構造函數中賦值的,看AudioPolicyCompatClient.h:
[cpp]
32 class AudioPolicyCompatClient : public AudioPolicyClientInterface {
33 public:
34 AudioPolicyCompatClient(struct audio_policy_service_ops *serviceOps,
35 void *service) :
36 mServiceOps(serviceOps) ,
mService(service) {}
從36行可知,構造時候就已經賦值了,所以調用的是create_legacy_ap函數312行傳進來的的型參aps_ops的set_stream_volume,它的賦值在frameworks/av/services/audioflinger/AudioPolicyService.cpp中:
[cpp]
1538 struct audio_policy_service_ops aps_ops = {
1539 open_output : aps_open_output,
1540 open_duplicate_output : aps_open_dup_output,
1541 close_output : aps_close_output,
1542 suspend_output : aps_suspend_output,
1543 restore_output : aps_restore_output,
1544 open_input : aps_open_input,
1545 close_input : aps_close_input,
1546 set_stream_volume : aps_set_stream_volume,
1547 set_stream_output : aps_set_stream_output,
1548 set_parameters : aps_set_parameters,
1549 get_parameters : aps_get_parameters,
1550 start_tone : aps_start_tone,
1551 stop_tone : aps_stop_tone,
1552 set_voice_volume : aps_set_voice_volume,
1553 move_effects : aps_move_effects,
1554 load_hw_module : aps_load_hw_module,
1555 open_output_on_module : aps_open_output_on_module,
1556 open_input_on_module : aps_open_input_on_module,
1557 };
------------>
[cpp]
1503 static int aps_set_stream_volume(void *service, audio_stream_type_t stream,
1504 float volume, audio_io_handle_t output,
1505 int delay_ms)
1506 {
1507 AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;
1508
1509 return audioPolicyService->setStreamVolume(stream, volume, output,
1510 delay_ms);
1511 }
這裡1507行的service即create_legacy_ap 360行傳進來的service,也就是AudioPolicyService.cpp構造函數中83行的this指針,饒了半天居然還是調用了AudioPolicyService.cpp的setStreamVolume,setStreamVolume的實現:
[cpp]
1006 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,
1007 float volume,
1008 audio_io_handle_t output,
1009 int delayMs)
1010 {
1011 return (int)mAudioCommandThread->volumeCommand(stream, volume,
1012 output, delayMs);
1013 }
一看就知道是個線程之類的東西了,AudioCommandThread繼承了Thread類,看看volumeCommand的實現:
[cpp]
800 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,
801 float volume,
802 audio_io_handle_t output,
803 int delayMs)
804 {
805 status_t status = NO_ERROR;
806
807 AudioCommand *command = new AudioCommand();
808 command->mCommand = SET_VOLUME;
809 VolumeData *data = new VolumeData();
810 data->mStream = stream;
811 data->mVolume = volume;
812 data->mIO = output;
813 command->mParam = data;
814 if (delayMs == 0) {
815 command->mWaitStatus = true;
816 } else {
817 command->mWaitStatus = false;
818 }
819 Mutex::Autolock _l(mLock);
820 insertCommand_l(command, delayMs);
821 ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",
822 stream, volume, output);
823 mWaitWorkCV.signal();
824 if (command->mWaitStatus) {
825 command->mCond.wait(mLock);
826 status = command->mStatus;
827 mWaitWorkCV.signal();
828 }
829 return status;
830 }
820行insertCommand_l,加入線程隊列中,看看線程的執行函數threadLoop:
[cpp]
bool AudioPolicyService::AudioCommandThread::threadLoop()
{
681 case SET_VOLUME: {
682 VolumeData *data = (VolumeData *)command->mParam;
683 ALOGV("AudioCommandThread() processing set volume stream %d, \
684 volume %f, output %d", data->mStream, data->mVolume, data->mIO);
685 command->mStatus = AudioSystem::setStreamVolume(data->mStream,
686 data->mVolume,
687 data->mIO);
688 if (command->mWaitStatus) {
689 command->mCond.signal();
690 mWaitWorkCV.wait(mLock);
691 }
692 delete data;
693 }break;
}
685行,我們又回到AudioSystem.cpp中來啦:
[cpp]
123 status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,
124 audio_io_handle_t output)
125 {
126 if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;
127 const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();
128 if (af == 0) return PERMISSION_DENIED;
129 af->setStreamVolume(stream, value, output);
130 return NO_ERROR;
131 }
129行,我們終於要進入AudioFlinger.cpp中啦,先看126行,get_audio_flinger:
[cpp]
49 const sp<IAudioFlinger>& AudioSystem::get_audio_flinger()
50 {
51 Mutex::Autolock _l(gLock);
52 if (gAudioFlinger == 0) {
53 sp<IServiceManager> sm = defaultServiceManager();
54 sp<IBinder> binder;
55 do {
56 binder = sm->getService(String16("media.audio_flinger"));
57 if (binder != 0)
58 break;
59 ALOGW("AudioFlinger not published, waiting...");
60 usleep(500000); // 0.5 s
61 } while (true);
62 if (gAudioFlingerClient == NULL) {
63 gAudioFlingerClient = new AudioFlingerClient();
64 } else {
65 if (gAudioErrorCallback) {
66 gAudioErrorCallback(NO_ERROR);
67 }
68 }
69 binder->linkToDeath(gAudioFlingerClient);
70 gAudioFlinger = interface_cast<IAudioFlinger>(binder);
71 gAudioFlinger->registerClient(gAudioFlingerClient);
72 }
73 ALOGE_IF(gAudioFlinger==0, "no AudioFlinger!?");
74
75 return gAudioFlinger;
76 }
分析完前面的binder通訊,再看這個函數的代碼,太簡單了!70行最終得到一個BpAudioFlinger代理,以便和BnAudioFlinger通訊,他們在IAudioFlinger.cpp中:
[cpp]
255 virtual status_t setStreamVolume(audio_stream_type_t stream, float value,
256 audio_io_handle_t output)
257 {
258 Parcel data, reply;
259 data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
260 data.writeInt32((int32_t) stream);
261 data.writeFloat(value);
262 data.writeInt32((int32_t) output);
263 remote()->transact(SET_STREAM_VOLUME, data, &reply);
264 return reply.readInt32();
265 }
263行,,類型為SET_STREAM_VOLUME,由於AudioFlinger繼承BnAudioFlinger,調用AudioFlinger的onTransact,但該函數還是回調BnAudioFlinger的onTransact,進入
BnAudioFlinger::onTransact函數:
[cpp]
780 case SET_STREAM_VOLUME: {
781 CHECK_INTERFACE(IAudioFlinger, data, reply);
782 int stream = data.readInt32();
783 float volume = data.readFloat();
784 audio_io_handle_t output = (audio_io_handle_t) data.readInt32();
785 reply->writeInt32( setStreamVolume((audio_stream_type_t) stream, volume, output) );
786 return NO_ERROR;
785行,進入AudioFlinger.cpp:
[cpp]
761 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
762 audio_io_handle_t output)
763 {
764 // check calling permissions
765 if (!settingsAllowed()) {
766 return PERMISSION_DENIED;
767 }
769 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {//定義在system/core/include/system/audio.h
771 return BAD_VALUE;
772 }
774 AutoMutex lock(mLock);
775 PlaybackThread *thread = NULL;
776 if (output) {
777 thread = checkPlaybackThread_l(output);
778 if (thread == NULL) {
779 return BAD_VALUE;
780 }
781 }
783 mStreamTypes[stream].volume = value;
785 if (thread == NULL) {
786 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
787 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
788 }
789 } else {
790 thread->setStreamVolume(stream, value);
791 }
793 return NO_ERROR;
794 }