android Audio设置音量流程及其binder通讯原理

来源:互联网 发布:lol淘宝半价点券封号 编辑:程序博客网 时间:2024/05/15 01:36

Audio java部分代码流程(4.1.2 version):

    在frameworks/base/media/java/android/media中:
    IAudioService.aidl提供了所有对外的接口函数,如下:
[cpp] view plaincopy
  1. interface IAudioService {  
  2.       
  3.     void adjustVolume(int direction, int flags);  
  4.   
  5.     void adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags);  
  6.       
  7.     void adjustStreamVolume(int streamType, int direction, int flags);  
  8.       
  9.     void setStreamVolume(int streamType, int index, int flags);  
  10.       
  11.     void setStreamSolo(int streamType, boolean state, IBinder cb);  
  12.          
  13.     void setStreamMute(int streamType, boolean state, IBinder cb);  
  14.   
  15.     boolean isStreamMute(int streamType);  
  16.   
  17.     int getStreamVolume(int streamType);  
  18.       
  19.     int getStreamMaxVolume(int streamType);  
  20.       
  21.     int getLastAudibleStreamVolume(int streamType);  
  22.   
  23.     void setRingerMode(int ringerMode);  
  24.     .......................  
  25. }  
这些函数的实现在服务AudioService.java中:
[cpp] view plaincopy
  1. public class AudioService extends IAudioService.Stub {  
  2.         ........  
  3. }  
该服务在services/java/com/android/server/SystemServer.java中注册进servicemanager中:
[cpp] view plaincopy
  1. 492             try {  
  2. 493                 Slog.i(TAG, "Audio Service");  
  3. 494                 ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));                                 
  4. 495             } catch (Throwable e) {  
  5. 496                 reportWtf("starting Audio Service", e);  
  6. 497             }  
    这样在frameworks中可以通过ServiceManager.getService(Context.AUDIO_SERVICE)来获得该服务。
    而AudioManager.java则实现这些函数了对外应用的接口,比如:
[cpp] view plaincopy
  1. 496     public void adjustVolume(int direction, int flags) {  
  2. 497         IAudioService service = getService(); //  
  3. 498         try {  
  4. 499             service.adjustVolume(direction, flags);  
  5. 500         } catch (RemoteException e) {  
  6. 501             Log.e(TAG, "Dead object in adjustVolume", e);  
  7. 502         }  
  8. 503     }  
    这里的getService()获得的是前面的AudioService,如下:
[cpp] view plaincopy
  1. 365     private static IAudioService getService()                                                                                
  2. 366     {  
  3. 367         if (sService != null) {  
  4. 368             return sService;  
  5. 369         }  
  6. 370         IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);  
  7. 371         sService = IAudioService.Stub.asInterface(b);  
  8. 372         return sService;  
  9. 373     }  
    要把AudioManager.java中的对外公开,则要在 core/java/android/app/ContextImpl.java中注册:
[cpp] view plaincopy
  1. 281         registerService(AUDIO_SERVICE, new ServiceFetcher() {                                                     
  2. 282                 public Object createService(ContextImpl ctx) {  
  3. 283                     return new AudioManager(ctx);  
  4. 284                 }});  
    而且,还要把这些函数变量等在api/current.txt中声明:
[cpp] view plaincopy
  1. 10353   public class AudioManager {  
  2. 10354     method public int abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener);  
  3. 10355     method public void adjustStreamVolume(intintint);                                             
  4. 10356     method public void adjustSuggestedStreamVolume(intintint);  
  5. 10357     method public void adjustVolume(intint);  
  6. 10358     method public int getMode();  
  7. 10359     method public java.lang.String getParameters(java.lang.String);  
  8. 10360     method public int getRingerMode();  
  9. 10361     method public deprecated int getRouting(int);  
  10. 10362     method public int getStreamMaxVolume(int);  
  11. 10363     method public int getStreamVolume(int);  
  12. 10364     method public int getVibrateSetting(int);  
  13. 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){},在该函数中调用
 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] view plaincopy
  1. 2940         @Override  
  2. 2941         public void handleMessage(Message msg) {  
  3. 2942  
  4. 2943             switch (msg.what) {  
  5. 2944   
  6. 2945                 case MSG_SET_DEVICE_VOLUME:  
  7. 2946                     setDeviceVolume((VolumeStreamState) msg.obj, msg.arg1);  
  8. 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] view plaincopy
  1. 178 static int  
  2. 179 android_media_AudioSystem_setStreamVolumeIndex(JNIEnv *env,                                                                   
  3. 180                                                jobject thiz,  
  4. 181                                                jint stream,  
  5. 182                                                jint index,  
  6. 183                                                jint device)  
  7. 184 {  
  8. 185     return check_AudioSystem_Command(  
  9. 186             AudioSystem::setStreamVolumeIndex(static_cast <audio_stream_type_t>(stream),  
  10. 187                                               index,  
  11. 188                                               (audio_devices_t)device));  
  12. 189 }  
AudioSystem类在av/media/libmedia/AudioSystem.cpp中--------->
[cpp] view plaincopy
  1. 666 status_t AudioSystem::setStreamVolumeIndex(audio_stream_type_t stream,  
  2. 667                                            int index,  
  3. 668                                            audio_devices_t device)  
  4. 669 {  
  5. 670     const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();  
  6. 671     if (aps == 0) return PERMISSION_DENIED;  
  7. 672     return aps->setStreamVolumeIndex(stream, index, device);  
  8. 673 }  
到这里就要涉及到进程间通讯binder的使用了,我们看AudioSystem::get_audio_policy_service()的实现:
[cpp] view plaincopy
  1. 514 const sp<IAudioPolicyService>& AudioSystem::get_audio_policy_service()  
  2. 515 {  
  3. 516     gLock.lock();  
  4. 517     if (gAudioPolicyService == 0) {  
  5. 518         sp<IServiceManager> sm = defaultServiceManager();//取得BpServiceManager,通过这个代理可以调用BnServiceManager::onTransact,最后和ServiceManager通讯  
  6. 519         sp<IBinder> binder;  
  7. 520         do {  
  8. 521             binder = sm->getService(String16("media.audio_policy"));//从ServiceManager获得远程AudioPolicyService的句柄  
  9. 522             if (binder != 0)  
  10. 523                 break;  
  11. 524             ALOGW("AudioPolicyService not published, waiting...");  
  12. 525             usleep(500000); // 0.5 s  
  13. 526         } while (true);  
  14. 527         if (gAudioPolicyServiceClient == NULL) {  
  15. 528             gAudioPolicyServiceClient = new AudioPolicyServiceClient();  
  16. 529         }  
  17. 530         binder->linkToDeath(gAudioPolicyServiceClient);  
  18. 531         gAudioPolicyService = interface_cast<IAudioPolicyService>(binder);                 
  19. 532         gLock.unlock();  
  20. 533     } else {  
  21. 534         gLock.unlock();  
  22. 535     }  
  23. 536     return gAudioPolicyService;  
  24. 537 }  
上面531行interface_cast<IAudioPolicyService>(binder),interface_cast是一个模版,在frameworks/native/include/binder/IInterface.h中定义如下:
[cpp] view plaincopy
  1. 42 inline sp<INTERFACE> interface_cast(const sp<IBinder>&obj)                 
  2. 43 {  
  3. 44     return INTERFACE::asInterface(obj);  
  4. 45 }  
展开后是IAudioPolicyService::asInterface(obj);而IAudioPolicyService::asInterface的实现在frameworks/av/include/media/IAudioPolicyService.h中,通过宏
[cpp] view plaincopy
  1. DECLARE_META_INTERFACE(AudioPolicyService)展开后得到的,DECLARE_META_INTERFACE定义在IInterface.h中:  
  2.      74 #define DECLARE_META_INTERFACE(INTERFACE)                               \  
  3.      75     static const android::String16 descriptor;                          \  
  4.      76     static android::sp<I##INTERFACE> asInterface(                       \  
  5.      77             const android::sp<android::IBinder>& obj);                  \  
  6.      78     virtual const android::String16& getInterfaceDescriptor() const;    \  
  7.      79     I##INTERFACE();                                                     \  
  8.      80     virtual ~I##INTERFACE();  
76行展开即可得到IAudioPolicyService::asInterface的定义,而这个定义的实现也是在IInterface.h,通过宏来定义的:
[cpp] view plaincopy
  1. #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)  
  2.     ........................  
  3.  89     android::sp<I##INTERFACE> I##INTERFACE::asInterface(                \  
  4.  90             const android::sp<android::IBinder>& obj)                   \  
  5.  91     {                                                                   \  
  6.  92         android::sp<I##INTERFACE> intr;                                 \  
  7.  93         if (obj != NULL) {                                              \  
  8.  94             intr = static_cast<I##INTERFACE*>(                          \  
  9.  95                 obj->queryLocalInterface(                               \  
  10.  96                         I##INTERFACE::descriptor).get());               \  
  11.  97             if (intr == NULL) {                                         \  
  12.  98                 intr = new Bp##INTERFACE(obj);                          \  
  13.  99             }                                                           \  
  14. 100         }                                                               \  
  15. 101         return intr;                                                    \  
  16. 102     }  

展开后最终是生成调用new BpAudioPolicyService(new BpBinder(handle)),这里的handle是一个句柄;这样我们最终得到了AudioPolicyService的代理BpAudioPolicyService,通过它就可以和AudioPolicyService的本地接口BnAudioPolicyService通讯了。
回到前面的AudioSystem.cpp,取得代理BpAudioPolicyService后调用aps->setStreamVolumeIndex,所以进入IAudioPolicyService.cpp:
class BpAudioPolicyService : public BpInterface<IAudioPolicyService>:
[cpp] view plaincopy
  1. 233     virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,                                                             
  2. 234                                           int index,  
  3. 235                                           audio_devices_t device)  
  4. 236     {  
  5. 237         Parcel data, reply;  
  6. 238         data.writeInterfaceToken(IAudioPolicyService::getInterfaceDescriptor());  
  7. 239         data.writeInt32(static_cast <uint32_t>(stream));  
  8. 240         data.writeInt32(index);  
  9. 241         data.writeInt32(static_cast <uint32_t>(device));  
  10. 242         remote()->transact(SET_STREAM_VOLUME, data, &reply);  
  11. 243         return static_cast <status_t> (reply.readInt32());  
  12. 244     }  
242行的remote是通过继承关系BpAudioPolicyService -> BpInterface -> BpRefBase,在类BpRefBase中定义的:
[cpp] view plaincopy
  1. inline  IBinder*        remote()                { return mRemote; }  
  2.  IBinder* const          mRemote;  
这里mRemote声明为const,可见它是静态不变,只赋值一次,它是在前面获取远程服务AudioPolicyService时候创建的BpBinder对象(主要是打开了binder驱动,获得FD描述符,并且内存映射了空间),所以调用BpBinder.cpp的transact函数:
[cpp] view plaincopy
  1. 159 status_t BpBinder::transact(  
  2. 160     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. 161 {  
  4. 162     // Once a binder has died, it will never come back to life.  
  5. 163     if (mAlive) {  
  6. 164         status_t status = IPCThreadState::self()->transact(  
  7. 165             mHandle, code, data, reply, flags);  
  8. 166         if (status == DEAD_OBJECT) mAlive = 0;  
  9. 167         return status;  
  10. 168     }  
  11. 169   
  12. 170     return DEAD_OBJECT;  
  13. 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] view plaincopy
  1. 34 int main(int argc, char** argv)  
  2. 35 {  
  3. 36     sp<ProcessState> proc(ProcessState::self());  
  4. 37     sp<IServiceManager> sm = defaultServiceManager();  
  5. 38     ALOGI("ServiceManager: %p", sm.get());  
  6. 39     AudioFlinger::instantiate();  
  7. 40     MediaPlayerService::instantiate();  
  8. 41     CameraService::instantiate();  
  9. 42     AudioPolicyService::instantiate();                                                                                          
  10. 43     ProcessState::self()->startThreadPool();  
  11. 44     IPCThreadState::self()->joinThreadPool();  
  12. 45 }   
36行,由于main_mediaserver.cpp是编译成一个可执行文件,就是它的启动是作为服务在一个独立的进程中运行了,Main_MediaServer主函数由init.rc在启动时调用,先明白这点,然后看:
frameworks/native/libs/binder/ProcessState.cpp:
[cpp] view plaincopy
  1. 74 sp<ProcessState> ProcessState::self()  
  2. 75 {  
  3. 76     Mutex::Autolock _l(gProcessMutex);  
  4. 77     if (gProcess != NULL) {  
  5. 78         return gProcess;  
  6. 79     }  
  7. 80     gProcess = new ProcessState;  
  8. 81     return gProcess;  
  9. 82 }  
从77行可知,这是一个单例模式,在这个进程中以后再调用这个函数的话,就直接返回78行,这里我们第一次进来,所以跑到80行,进入ProcessState构造函数:
[cpp] view plaincopy
  1. 335 ProcessState::ProcessState()  
  2. 336     : mDriverFD(open_driver())  
  3. 337     , mVMStart(MAP_FAILED)  
  4. 338     , mManagesContexts(false)  
  5. 339     , mBinderContextCheckFunc(NULL)  
  6. 340     , mBinderContextUserData(NULL)  
  7. 341     , mThreadPoolStarted(false)  
  8. 342     , mThreadPoolSeq(1)  
  9. 343 {     
  10. 344     if (mDriverFD >= 0) {  
  11. 345         // XXX Ideally, there should be a specific define for whether we  
  12. 346         // have mmap (or whether we could possibly have the kernel module  
  13. 347         // availabla).  
  14. 348 #if !defined(HAVE_WIN32_IPC)  
  15. 349         // mmap the binder, providing a chunk of virtual address space to receive transactions.  
  16. 350         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);  
  17. .................................  
  18. }  
336行打开Binder设备文件/dev/binder,并将打开设备文件描述符保存在成员变量mDriverFD中;350行mmap来把设备文件/dev/binder映射到内存中,这样我们就有了一块共享内存。
回到main_mediaserver.cpp,37行defaultServiceManager(),在frameworks/native/libs/binder/IServiceManager.cpp中:
[cpp] view plaincopy
  1. 34 sp<IServiceManager> defaultServiceManager()                                                                            
  2. 35 {     
  3. 36     if (gDefaultServiceManager != NULL) return gDefaultServiceManager;  
  4. 37       
  5. 38     {  
  6. 39         AutoMutex _l(gDefaultServiceManagerLock);  
  7. 40         if (gDefaultServiceManager == NULL) {  
  8. 41             gDefaultServiceManager = interface_cast<IServiceManager>(  
  9. 42                 ProcessState::self()->getContextObject(NULL));  
  10. 43         }  
  11. 44     }  
  12. 45   
  13. 46     return gDefaultServiceManager;  
  14. 47 }  
和前面一样,也是一个单例模式,第一次进来肯定为NULL,所以进入41行,ProcessState::self()前面已经运行过一次,直接调用getContextObject(NULL),注意传进来的是NULL参数,表示和ServiceManager通讯:
[cpp] view plaincopy
  1. 89 sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)  
  2. 90 {  
  3. 91     return getStrongProxyForHandle(0);                                                                                                
  4. 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] view plaincopy
  1. 37 class AudioPolicyService :  
  2. 38     public BinderService<AudioPolicyService>,                                                                               
  3. 39     public BnAudioPolicyService,  
  4. 40 //    public AudioPolicyClientInterface,  
  5. 41     public IBinder::DeathRecipient  
AudioPolicyService并没有实现instantiate方法,而是继承BinderService得到的,该类在frameworks/native/include/binder/BinderService.h中:
[cpp] view plaincopy
  1. 33 template<typename SERVICE>  
  2. 34 class BinderService                                                                                                              
  3. 35 {  
  4. 36 public:  
  5. 37     static status_t publish(bool allowIsolated = false) {  
  6. 38         sp<IServiceManager> sm(defaultServiceManager());  
  7. 39         return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);  
  8. 40     }  
  9. 41   
  10. 42     static void publishAndJoinThreadPool(bool allowIsolated = false) {  
  11. 43         sp<IServiceManager> sm(defaultServiceManager());  
  12. 44         sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);  
  13. 45         ProcessState::self()->startThreadPool();  
  14. 46         IPCThreadState::self()->joinThreadPool();  
  15. 47     }  
  16. 48       
  17. 49     static void instantiate() { publish(); }  
  18. 50       
  19. 51     static status_t shutdown() {  
  20. 52         return NO_ERROR;  
  21. 53     }  
  22. 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] view plaincopy
  1. 154     virtual status_t addService(const String16& name, const sp<IBinder>&service, bool allowIsolated)  
  2. 156     {  
  3. 157         Parcel data, reply;  
  4. 158         data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  5. 159         data.writeString16(name);  
  6. 160         data.writeStrongBinder(service);  
  7. 161         data.writeInt32(allowIsolated ? 1 : 0);  
  8. 162         status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  9. 163         return err == NO_ERROR ? reply.readExceptionCode() : err;  
  10. 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] view plaincopy
  1. 136 void ProcessState::startThreadPool()  
  2. 137 {  
  3. 138     AutoMutex _l(mLock);  
  4. 139     if (!mThreadPoolStarted) {  
  5. 140         mThreadPoolStarted = true;  
  6. 141         spawnPooledThread(true);                                                                                                               
  7. 142     }  
  8. 143 }  
看141行:
[cpp] view plaincopy
  1. 286 void ProcessState::spawnPooledThread(bool isMain)                                                                          
  2. 287 {  
  3. 288     if (mThreadPoolStarted) {  
  4. 289         int32_t s = android_atomic_add(1, &mThreadPoolSeq);  
  5. 290         char buf[16];  
  6. 291         snprintf(buf, sizeof(buf), "Binder_%X", s);  
  7. 292         ALOGV("Spawning new pooled thread, name=%s\n", buf);  
  8. 293         sp<Thread> t = new PoolThread(isMain);  
  9. 294         t->run(buf);  
  10. 295     }  
  11. 296 }  
293行创建了线程,PoolThread类继承列thread类,ProcessState.cpp中::
[cpp] view plaincopy
  1. 56 class PoolThread : public Thread  
  2. 57 {  
  3. 58 public:  
  4. 59     PoolThread(bool isMain)  
  5. 60         : mIsMain(isMain)  
  6. 61     {  
  7. 62     }  
  8. 63   
  9. 64 protected:  
  10. 65     virtual bool threadLoop()                                                                                                      
  11. 66     {  
  12. 67         IPCThreadState::self()->joinThreadPool(mIsMain);  
  13. 68         return false;  
  14. 69     }  
  15. 70   
  16. 71     const bool mIsMain;  
  17. 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] view plaincopy
  1.  97 status_t BBinder::transact(  
  2.  98     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3.  99 {  
  4. 100     data.setDataPosition(0);  
  5. 101   
  6. 102     status_t err = NO_ERROR;  
  7. 103     switch (code) {  
  8. 104         case PING_TRANSACTION:                                                                                                
  9. 105             reply->writeInt32(pingBinder());  
  10. 106             break;  
  11. 107         default:  
  12. 108             err = onTransact(code, data, reply, flags);  
  13. 109             break;  
  14. 110     }  
  15. 111   
  16. 112     if (reply != NULL) {  
  17. 113         reply->setDataPosition(0);  
  18. 114     }  
  19. 115   
  20. 116     return err;  
  21. 117 }  
108行,调用onTransact方法,由于这里的继承关系,在前面分析main_mediaserver.cpp的42行AudioPolicyService::instantiate()就知道,这里创建的是AudioPolicyService类,这样由于虚函数onTransact的继承关系,最终调用了AudioPolicyService的onTransact方法,AudioPolicyService.cpp中:
[cpp] view plaincopy
  1. 610 status_t AudioPolicyService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  2. 612 {  
  3. 613     return BnAudioPolicyService::onTransact(code, data, reply, flags);  
  4. 614 }  
613行调用的还是基类BnAudioPolicyService的方法.
到这里BpAudioPolicyService和BnAudioPolicyService的binder通讯关系就完成了,回到前面IAudioPolicyService.cpp中的242行remote()->transact(SET_STREAM_VOLUME, data, &reply);这里传进来的是SET_STREAM_VOLUME,所以调用BnAudioPolicyService::onTransact:
[cpp] view plaincopy
  1. 512         case SET_STREAM_VOLUME:{                                                                                           
  2. 513             CHECK_INTERFACE(IAudioPolicyService, data, reply);  
  3. 514             audio_stream_type_t stream =  
  4. 515                     static_cast <audio_stream_type_t>(data.readInt32());  
  5. 516             int index = data.readInt32();  
  6. 517             audio_devices_t device = static_cast <audio_devices_t>(data.readInt32());  
  7. 518             reply->writeInt32(static_cast <uint32_t>(setStreamVolumeIndex(stream,  
  8. 519                                                                           index,  
  9. 520                                                                           device)));  
  10. 521             return NO_ERROR;  
  11. 522         } break;  
518行AudioPolicyService覆盖了BpAudioPolicyService的setStreamVolumeIndex方法,所以最终调用了AudioPolicyService.cpp的setStreamVolumeIndex方法:
[cpp] view plaincopy
  1. 380 status_t AudioPolicyService::setStreamVolumeIndex(audio_stream_type_t stream,  
  2. 381                                                   int index,  
  3. 382                                                   audio_devices_t device)  
  4. 383 {  
  5. 384     if (mpAudioPolicy == NULL) {  
  6. 385         return NO_INIT;  
  7. 386     }  
  8. 387     if (!settingsAllowed()) {  
  9. 388         return PERMISSION_DENIED;  
  10. 389     }  
  11. 390     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {  
  12. 391         return BAD_VALUE;  
  13. 392     }  
  14. 393   
  15. 394     if (mpAudioPolicy->set_stream_volume_index_for_device) {                                                             
  16. 395         return mpAudioPolicy->set_stream_volume_index_for_device(mpAudioPolicy,  
  17. 396                                                                 stream,  
  18. 397                                                                 index,  
  19. 398                                                                 device);  
  20. 399     } else {  
  21. 400         return mpAudioPolicy->set_stream_volume_index(mpAudioPolicy, stream, index);  
  22. 401     }  
  23. 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] view plaincopy
  1. 58 AudioPolicyService::AudioPolicyService()  
  2. 59     : BnAudioPolicyService() , mpAudioPolicyDev(NULL) , mpAudioPolicy(NULL)  
  3. 60 {  
  4. 61     char value[PROPERTY_VALUE_MAX];  
  5. 62     const struct hw_module_t *module;  
  6. 63     int forced_val;  
  7. 64     int rc;  
  8. 65   
  9. 66     Mutex::Autolock _l(mLock);  
  10. 67   
  11. 68     // start tone playback thread  
  12. 69     mTonePlaybackThread = new AudioCommandThread(String8(""));  
  13. 70     // start audio commands thread  
  14. 71     mAudioCommandThread = new AudioCommandThread(String8("ApmCommand"));  
  15. 72   
  16. 73     /* instantiate the audio policy manager */  
  17. 74     rc = hw_get_module(AUDIO_POLICY_HARDWARE_MODULE_ID, &module);  
  18. 75     if(rc)                                                                                                             
  19. 76         return;  
  20. 77   
  21. 78     rc = audio_policy_dev_open(module, &mpAudioPolicyDev);  
  22. 79     ALOGE_IF(rc, "couldn't open audio policy device (%s)", strerror(-rc));  
  23. 80     if (rc)  
  24. 81         return;  
  25. 82   
  26. 83     rc = mpAudioPolicyDev->create_audio_policy(mpAudioPolicyDev, &aps_ops, this,  
  27. 84                                                &mpAudioPolicy);  
  28. 85     ALOGE_IF(rc, "couldn't create audio policy (%s)", strerror(-rc));  
  29. 86     if (rc)  
  30. 87         return;  
  31. 88   
  32. 89     rc = mpAudioPolicy->init_check(mpAudioPolicy);  
  33. 90     ALOGE_IF(rc, "couldn't init_check the audio policy (%s)", strerror(-rc));  
  34. 91     if (rc)  
  35. 92         return;  
  36.   .......................  
  37.   }  
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] view plaincopy
  1. 424 static inline int audio_policy_dev_open(const hw_module_t* module,  
  2. 425                                     struct audio_policy_device** device)  
  3. 426 {  
  4. 427     return module->methods->open(module, AUDIO_POLICY_INTERFACE,  
  5. 428                                  (hw_device_t**)device);  
  6. 429 }  
这样就调用了hardware/libhardware_legacy/audio/audio_policy_hal.cpp的open方法:
[cpp] view plaincopy
  1. 406 static int legacy_ap_dev_open(const hw_module_t* module, const char* name, hw_device_t** device)  
  2. 408 {  
  3. 409     struct legacy_ap_device *dev;  
  4. 411     if (strcmp(name, AUDIO_POLICY_INTERFACE) != 0)  
  5. 412         return -EINVAL;  
  6. 414     dev = (struct legacy_ap_device *)calloc(1, sizeof(*dev));                                                      
  7. 415     if (!dev)  
  8. 416         return -ENOMEM;  
  9. 418     dev->device.common.tag = HARDWARE_DEVICE_TAG;  
  10. 419     dev->device.common.version = 0;  
  11. 420     dev->device.common.module = const_cast<hw_module_t*>(module);  
  12. 421     dev->device.common.close = legacy_ap_dev_close;  
  13. 422     dev->device.create_audio_policy = create_legacy_ap;  
  14. 423     dev->device.destroy_audio_policy = destroy_legacy_ap;  
  15. 425     *device = &dev->device.common;  
  16. 427     return 0;  
  17. 428 }  
结构体legacy_ap_device定义:
[cpp] view plaincopy
  1. 40 struct legacy_ap_device {                                                                                                                       
  2. 41     struct audio_policy_device device;  
  3. 42 };  
结构体audio_policy_device定义:
[cpp] view plaincopy
  1. 410 struct audio_policy_device {                                                                                                    
  2. 411     struct hw_device_t common;  
  3. 412   
  4. 413     int (*create_audio_policy)(const struct audio_policy_device *device,  
  5. 414                                struct audio_policy_service_ops *aps_ops,  
  6. 415                                void *service,  
  7. 416                                struct audio_policy **ap);  
  8. 417   
  9. 418     int (*destroy_audio_policy)(const struct audio_policy_device *device,  
  10. 419                                 struct audio_policy *ap);  
  11. 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] view plaincopy
  1. 311 static int create_legacy_ap(const struct audio_policy_device *device,  
  2. 312                             struct audio_policy_service_ops *aps_ops,  
  3. 313                             void *service,  
  4. 314                             struct audio_policy **ap)  
  5. 315 {  
  6. 316     struct legacy_audio_policy *lap;  
  7. 317     int ret;  
  8. 318   
  9. 319     if (!service || !aps_ops)  
  10. 320         return -EINVAL;  
  11. 321   
  12. 322     lap = (struct legacy_audio_policy *)calloc(1, sizeof(*lap));  
  13. 323     if (!lap)  
  14. 324         return -ENOMEM;  
  15. 325   
  16. 326     lap->policy.set_device_connection_state = ap_set_device_connection_state;  
  17. 327     lap->policy.get_device_connection_state = ap_get_device_connection_state;  
  18. 328     lap->policy.set_phone_state = ap_set_phone_state;  
  19. 329     lap->policy.set_ringer_mode = ap_set_ringer_mode;  
  20. 330     lap->policy.set_force_use = ap_set_force_use;  
  21. 331     lap->policy.get_force_use = ap_get_force_use;  
  22. 332     lap->policy.set_can_mute_enforced_audible = ap_set_can_mute_enforced_audible;  
  23. 334     lap->policy.init_check = ap_init_check;  
  24. 335     lap->policy.get_output = ap_get_output;  
  25. 336     lap->policy.start_output = ap_start_output;  
  26. 337     lap->policy.stop_output = ap_stop_output;  
  27. 338     lap->policy.release_output = ap_release_output;  
  28. 339     lap->policy.get_input = ap_get_input;  
  29. 340     lap->policy.start_input = ap_start_input;  
  30. 341     lap->policy.stop_input = ap_stop_input;  
  31. 342     lap->policy.release_input = ap_release_input;  
  32. 343     lap->policy.init_stream_volume = ap_init_stream_volume;  
  33. 344     lap->policy.set_stream_volume_index = ap_set_stream_volume_index;  
  34. 345     lap->policy.get_stream_volume_index = ap_get_stream_volume_index;                                                                    
  35. 346     lap->policy.set_stream_volume_index_for_device = ap_set_stream_volume_index_for_device;  
  36. 347     lap->policy.get_stream_volume_index_for_device = ap_get_stream_volume_index_for_device;  
  37. 348     lap->policy.get_strategy_for_stream = ap_get_strategy_for_stream;  
  38. 349     lap->policy.get_devices_for_stream = ap_get_devices_for_stream;  
  39. 350     lap->policy.get_output_for_effect = ap_get_output_for_effect;  
  40. 351     lap->policy.register_effect = ap_register_effect;  
  41. 352     lap->policy.unregister_effect = ap_unregister_effect;  
  42. 353     lap->policy.set_effect_enabled = ap_set_effect_enabled;  
  43. 354     lap->policy.is_stream_active = ap_is_stream_active;  
  44. 355     lap->policy.dump = ap_dump;  
  45. 356   
  46. 357     lap->service = service;  
  47. 358     lap->aps_ops = aps_ops;  
  48. 359     lap->service_client =  
  49. 360         new AudioPolicyCompatClient(aps_ops, service);  
  50. 361     if (!lap->service_client) {  
  51. 362         ret = -ENOMEM;  
  52. 363         goto err_new_compat_client;  
  53. 364     }  
  54. 365   
  55. 366     lap->apm = createAudioPolicyManager(lap->service_client);  
  56. 367     if (!lap->apm) {  
  57. 368         ret = -ENOMEM;  
  58. 369         goto err_create_apm;  
  59. 370     }  
  60. 371   
  61. 372     *ap = &lap->policy;  
  62. 373     return 0;  
  63. 374   
  64. 375 err_create_apm:  
  65. 376     delete lap->service_client;  
  66. 377 err_new_compat_client:  
  67. 378     free(lap);  
  68. 379     *ap = NULL;  
  69. 380     return ret;  
  70. 381 }  
372行可知,这样mpAudioPolicy指针就指向了lap->policy方法。回到前面AudioPolicyService::setStreamVolumeIndex的394行调用audio_policy_hal.cpp方法:
[cpp] view plaincopy
  1. 232 static int ap_set_stream_volume_index_for_device(struct audio_policy *pol,                                                     
  2. 233                                       audio_stream_type_t stream,  
  3. 234                                       int index,  
  4. 235                                       audio_devices_t device)  
  5. 236 {  
  6. 237     struct legacy_audio_policy *lap = to_lap(pol);  
  7. 238     return lap->apm->setStreamVolumeIndex((AudioSystem::stream_type)stream,  
  8. 239                                           index,  
  9. 240                                           device);  
  10. 241 }  
237行结构体legacy_audio_policy定义:
[cpp] view plaincopy
  1. 44 struct legacy_audio_policy {                                                                                                    
  2. 45     struct audio_policy policy;//即为mpAudioPolicy  
  3. 46   
  4. 47     void *service;  
  5. 48     struct audio_policy_service_ops *aps_ops;  
  6. 49     AudioPolicyCompatClient *service_client;  
  7. 50     AudioPolicyInterface *apm;  
  8. 51 };  
lap->apm的赋值在前面create_legacy_ap函数的366行,看createAudioPolicyManager,hardware/libhardware_legacy/audio/AudioPolicyManagerDefault.cpp中:
[cpp] view plaincopy
  1. 24 extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)  
  2. 25 {  
  3. 26     return new AudioPolicyManagerDefault(clientInterface);                                                                             
  4. 27 }  
----->hardware/libhardware_legacy/audio/AudioPolicyManagerDefault.h:
[cpp] view plaincopy
  1. 25 class AudioPolicyManagerDefault: public AudioPolicyManagerBase  
  2. 26 {  
  3. 28 public:  
  4. 29                 AudioPolicyManagerDefault(AudioPolicyClientInterface *clientInterface)                                             
  5. 30                 : AudioPolicyManagerBase(clientInterface) {}  
  6. 31   
  7. 32         virtual ~AudioPolicyManagerDefault() {}  
  8. 33   
  9. 34 };  
看基类AudioPolicyManagerBase,hardware/libhardware_legacy/include/hardware_legacy/AudioPolicyManagerBase.h的定义,终于找到了setStreamVolumeIndex方法,
在AudioPolicyManagerBase.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] view plaincopy
  1. 2683 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,  
  2. 2684                                                    int index,  
  3. 2685                                                    audio_io_handle_t output,  
  4. 2686                                                    audio_devices_t device,  
  5. 2687                                                    int delayMs,  
  6. 2688                                                    bool force)  
  7. 2689 {  
  8.          ....................  
  9. 2722             if (stream == AudioSystem::BLUETOOTH_SCO) {  
  10. 2723                 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);  
  11. 2724             }  
  12. 2725         }  
  13. 2726   
  14. 2727         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);  
  15.         ...................  
  16. 2747 }  
这里mpClientInterface是在AudioPolicyManagerBase构造函数中赋值的,就是create_legacy_ap函数360行AudioPolicyCompatClient,方法在AudioPolicyCompatClient.cpp:
[cpp] view plaincopy
  1. 120 status_t AudioPolicyCompatClient::setStreamVolume(                                                                                   
  2. 121                                              AudioSystem::stream_type stream,  
  3. 122                                              float volume,  
  4. 123                                              audio_io_handle_t output,  
  5. 124                                              int delayMs)  
  6. 125 {  
  7. 126     return mServiceOps->set_stream_volume(mService, (audio_stream_type_t)stream,  
  8. 127                                           volume, output, delayMs);  
  9. 128 }  
这里是在构造函数中赋值的,看AudioPolicyCompatClient.h:
[cpp] view plaincopy
  1. 32 class AudioPolicyCompatClient : public AudioPolicyClientInterface {  
  2. 33 public:  
  3. 34     AudioPolicyCompatClient(struct audio_policy_service_ops *serviceOps,                                                                            
  4. 35                             void *service) :  
  5. 36             mServiceOps(serviceOps) ,   
  6.        mService(service) {}  
从36行可知,构造时候就已经赋值了,所以调用的是create_legacy_ap函数312行传进来的的型参aps_ops的set_stream_volume,它的赋值在frameworks/av/services/audioflinger/AudioPolicyService.cpp中:
[cpp] view plaincopy
  1. 1538     struct audio_policy_service_ops aps_ops = {  
  2. 1539         open_output           : aps_open_output,  
  3. 1540         open_duplicate_output : aps_open_dup_output,  
  4. 1541         close_output          : aps_close_output,  
  5. 1542         suspend_output        : aps_suspend_output,  
  6. 1543         restore_output        : aps_restore_output,  
  7. 1544         open_input            : aps_open_input,  
  8. 1545         close_input           : aps_close_input,  
  9. 1546         set_stream_volume     : aps_set_stream_volume,                                                                   
  10. 1547         set_stream_output     : aps_set_stream_output,  
  11. 1548         set_parameters        : aps_set_parameters,  
  12. 1549         get_parameters        : aps_get_parameters,  
  13. 1550         start_tone            : aps_start_tone,  
  14. 1551         stop_tone             : aps_stop_tone,  
  15. 1552         set_voice_volume      : aps_set_voice_volume,  
  16. 1553         move_effects          : aps_move_effects,  
  17. 1554         load_hw_module        : aps_load_hw_module,  
  18. 1555         open_output_on_module : aps_open_output_on_module,  
  19. 1556         open_input_on_module  : aps_open_input_on_module,  
  20. 1557     };  
------------>
[cpp] view plaincopy
  1. 1503 static int aps_set_stream_volume(void *service, audio_stream_type_t stream,                                                        
  2. 1504                                      float volume, audio_io_handle_t output,  
  3. 1505                                      int delay_ms)  
  4. 1506 {  
  5. 1507     AudioPolicyService *audioPolicyService = (AudioPolicyService *)service;  
  6. 1508   
  7. 1509     return audioPolicyService->setStreamVolume(stream, volume, output,  
  8. 1510                                                delay_ms);  
  9. 1511 }  
这里1507行的service即create_legacy_ap 360行传进来的service,也就是AudioPolicyService.cpp构造函数中83行的this指针,饶了半天居然还是调用了AudioPolicyService.cpp的setStreamVolume,setStreamVolume的实现:
[cpp] view plaincopy
  1. 1006 int AudioPolicyService::setStreamVolume(audio_stream_type_t stream,                               
  2. 1007                                         float volume,  
  3. 1008                                         audio_io_handle_t output,  
  4. 1009                                         int delayMs)  
  5. 1010 {  
  6. 1011     return (int)mAudioCommandThread->volumeCommand(stream, volume,  
  7. 1012                                                    output, delayMs);  
  8. 1013 }  
一看就知道是个线程之类的东西了,AudioCommandThread继承了Thread类,看看volumeCommand的实现:
[cpp] view plaincopy
  1. 800 status_t AudioPolicyService::AudioCommandThread::volumeCommand(audio_stream_type_t stream,                                
  2. 801                                                                float volume,  
  3. 802                                                                audio_io_handle_t output,  
  4. 803                                                                int delayMs)  
  5. 804 {  
  6. 805     status_t status = NO_ERROR;  
  7. 806   
  8. 807     AudioCommand *command = new AudioCommand();  
  9. 808     command->mCommand = SET_VOLUME;  
  10. 809     VolumeData *data = new VolumeData();  
  11. 810     data->mStream = stream;  
  12. 811     data->mVolume = volume;  
  13. 812     data->mIO = output;  
  14. 813     command->mParam = data;  
  15. 814     if (delayMs == 0) {  
  16. 815         command->mWaitStatus = true;  
  17. 816     } else {  
  18. 817         command->mWaitStatus = false;  
  19. 818     }  
  20. 819     Mutex::Autolock _l(mLock);  
  21. 820     insertCommand_l(command, delayMs);  
  22. 821     ALOGV("AudioCommandThread() adding set volume stream %d, volume %f, output %d",  
  23. 822             stream, volume, output);  
  24. 823     mWaitWorkCV.signal();  
  25. 824     if (command->mWaitStatus) {  
  26. 825         command->mCond.wait(mLock);  
  27. 826         status =  command->mStatus;  
  28. 827         mWaitWorkCV.signal();  
  29. 828     }  
  30. 829     return status;  
  31. 830 }  
820行insertCommand_l,加入线程队列中,看看线程的执行函数threadLoop:
[cpp] view plaincopy
  1. bool AudioPolicyService::AudioCommandThread::threadLoop()  
  2. {  
  3.      681                 case SET_VOLUME: {  
  4.      682                     VolumeData *data = (VolumeData *)command->mParam;  
  5.      683                     ALOGV("AudioCommandThread() processing set volume stream %d, \  
  6.      684                             volume %f, output %d", data->mStream, data->mVolume, data->mIO);  
  7.      685                     command->mStatus = AudioSystem::setStreamVolume(data->mStream,  
  8.      686                                                                     data->mVolume,  
  9.      687                                                                     data->mIO);  
  10.      688                     if (command->mWaitStatus) {  
  11.      689                         command->mCond.signal();  
  12.      690                         mWaitWorkCV.wait(mLock);  
  13.      691                     }  
  14.      692                     delete data;  
  15.      693                     }break;  
  16.   
  17. }  
685行,我们又回到AudioSystem.cpp中来啦:
[cpp] view plaincopy
  1. 123 status_t AudioSystem::setStreamVolume(audio_stream_type_t stream, float value,                                          
  2. 124         audio_io_handle_t output)  
  3. 125 {  
  4. 126     if (uint32_t(stream) >= AUDIO_STREAM_CNT) return BAD_VALUE;  
  5. 127     const sp<IAudioFlinger>& af = AudioSystem::get_audio_flinger();  
  6. 128     if (af == 0) return PERMISSION_DENIED;  
  7. 129     af->setStreamVolume(stream, value, output);  
  8. 130     return NO_ERROR;  
  9. 131 }  
129行,我们终于要进入AudioFlinger.cpp中啦,先看126行,get_audio_flinger:
[cpp] view plaincopy
  1. 49 const sp<IAudioFlinger>& AudioSystem::get_audio_flinger()  
  2. 50 {  
  3. 51     Mutex::Autolock _l(gLock);  
  4. 52     if (gAudioFlinger == 0) {  
  5. 53         sp<IServiceManager> sm = defaultServiceManager();  
  6. 54         sp<IBinder> binder;                                                                                                        
  7. 55         do {  
  8. 56             binder = sm->getService(String16("media.audio_flinger"));  
  9. 57             if (binder != 0)  
  10. 58                 break;  
  11. 59             ALOGW("AudioFlinger not published, waiting...");  
  12. 60             usleep(500000); // 0.5 s  
  13. 61         } while (true);  
  14. 62         if (gAudioFlingerClient == NULL) {  
  15. 63             gAudioFlingerClient = new AudioFlingerClient();  
  16. 64         } else {  
  17. 65             if (gAudioErrorCallback) {  
  18. 66                 gAudioErrorCallback(NO_ERROR);  
  19. 67             }  
  20. 68         }  
  21. 69         binder->linkToDeath(gAudioFlingerClient);  
  22. 70         gAudioFlinger = interface_cast<IAudioFlinger>(binder);  
  23. 71         gAudioFlinger->registerClient(gAudioFlingerClient);  
  24. 72     }  
  25. 73     ALOGE_IF(gAudioFlinger==0, "no AudioFlinger!?");  
  26. 74   
  27. 75     return gAudioFlinger;  
  28. 76 }  
分析完前面的binder通讯,再看这个函数的代码,太简单了!70行最终得到一个BpAudioFlinger代理,以便和BnAudioFlinger通讯,他们在IAudioFlinger.cpp中:
[cpp] view plaincopy
  1. 255     virtual status_t setStreamVolume(audio_stream_type_t stream, float value,                              
  2. 256             audio_io_handle_t output)  
  3. 257     {  
  4. 258         Parcel data, reply;  
  5. 259         data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());  
  6. 260         data.writeInt32((int32_t) stream);  
  7. 261         data.writeFloat(value);  
  8. 262         data.writeInt32((int32_t) output);  
  9. 263         remote()->transact(SET_STREAM_VOLUME, data, &reply);  
  10. 264         return reply.readInt32();  
  11. 265     }  
263行,,类型为SET_STREAM_VOLUME,由于AudioFlinger继承BnAudioFlinger,调用AudioFlinger的onTransact,但该函数还是回调BnAudioFlinger的onTransact,进入
BnAudioFlinger::onTransact函数:
[cpp] view plaincopy
  1. 780         case SET_STREAM_VOLUME: {                                                                                   
  2. 781             CHECK_INTERFACE(IAudioFlinger, data, reply);  
  3. 782             int stream = data.readInt32();  
  4. 783             float volume = data.readFloat();  
  5. 784             audio_io_handle_t output = (audio_io_handle_t) data.readInt32();  
  6. 785             reply->writeInt32( setStreamVolume((audio_stream_type_t) stream, volume, output) );  
  7. 786             return NO_ERROR;  
785行,进入AudioFlinger.cpp:
[cpp] view plaincopy
  1. 761 status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,  
  2. 762         audio_io_handle_t output)  
  3. 763 {  
  4. 764     // check calling permissions  
  5. 765     if (!settingsAllowed()) {  
  6. 766         return PERMISSION_DENIED;  
  7. 767     }  
  8. 769     if (uint32_t(stream) >= AUDIO_STREAM_CNT) {//定义在system/core/include/system/audio.h                          
  9. 771         return BAD_VALUE;  
  10. 772     }  
  11. 774     AutoMutex lock(mLock);  
  12. 775     PlaybackThread *thread = NULL;  
  13. 776     if (output) {  
  14. 777         thread = checkPlaybackThread_l(output);  
  15. 778         if (thread == NULL) {  
  16. 779             return BAD_VALUE;  
  17. 780         }  
  18. 781     }  
  19. 783     mStreamTypes[stream].volume = value;  
  20. 785     if (thread == NULL) {  
  21. 786         for (size_t i = 0; i < mPlaybackThreads.size(); i++) {  
  22. 787             mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);  
  23. 788         }  
  24. 789     } else {  
  25. 790         thread->setStreamVolume(stream, value);  
  26. 791     }  
  27. 793     return NO_ERROR;  
  28. 794 }  
audioflinger的原理看另外一篇文章。