深入了解MediaServer-1

来源:互联网 发布:飞天怎么样知乎 编辑:程序博客网 时间:2024/05/20 05:58

1.mediaserver位于main_mediaserver.cpp,其源码如下:

[html] view plaincopy
  1. int main(int argc, char** argv)  
  2. {  
  3.     sp<ProcessState> proc(ProcessState::self());  
  4.     sp<IServiceManager> sm = defaultServiceManager();  
  5.     LOGI("ServiceManager: %p", sm.get());  
  6.     AudioFlinger::instantiate();     //音频系统的mixer and resampler  
  7.     MediaPlayerService::instantiate();  //创建一个player,并进行AV播放  
  8.     CameraService::instantiate();     // 摄像和照相的服务  
  9.     AudioPolicyService::instantiate();  //音频策略的服务  
  10.     ProcessState::self()->startThreadPool();  
  11.     IPCThreadState::self()->joinThreadPool();  
  12. }  

此程序的进程名为:/system/bin/mediaserver

[html] view plaincopy
  1. void AudioFlinger::instantiate() {  
  2.     defaultServiceManager()->addService(  
  3.             String16("media.audio_flinger"), new AudioFlinger());  
  4. }  
  5.   
  6. void MediaPlayerService::instantiate() {  
  7.     defaultServiceManager()->addService(  
  8.             String16("media.player"), new MediaPlayerService());  
  9. }  
  10.   
  11. void CameraService::instantiate() {  
  12.     defaultServiceManager()->addService(  
  13.             String16("media.camera"), new CameraService());  
  14. }  
  15.   
  16. void AudioPolicyService::instantiate() {  
  17.     defaultServiceManager()->addService(  
  18.             String16("media.audio_policy"), new AudioPolicyService());  
  19. }  

查看系统已经注册的media类Service,其结果如下:

# service list | busybox grep media
5 audio: [android.media.IAudioService]
63 media.audio_policy: [android.media.IAudioPolicyService]
64 media.camera: [android.hardware.ICameraService]
65 media.player: [android.media.IMediaPlayerService]
66 media.audio_flinger: [android.media.IAudioFlinger]

 

2. 独一无二的ProcessState

ProcessState是一个单实例,每个进程只有一个实例。ProcessState::self()功能为打开/dev/binder设备,设置线程池中最大线程数,通过mmap把Binder Driver为其分配的内在映射到用户空间,以便把发送方的数据从发送方的用户空间直接copy到接收方的mmap空间。

[html] view plaincopy
  1. ProcessState::ProcessState()  
  2.     : mDriverFD(open_driver())  
  3.     , mVMStart(MAP_FAILED)  
  4.     , mManagesContexts(false)  
  5.     , mBinderContextCheckFunc(NULL)  
  6.     , mBinderContextUserData(NULL)  
  7.     , mThreadPoolStarted(false)  
  8.     , mThreadPoolSeq(1)  
  9. {  
  10.     if (mDriverFD >= 0) {  
  11.         // XXX Ideally, there should be a specific define for whether we  
  12.         // have mmap (or whether we could possibly have the kernel module  
  13.         // availabla).  
  14. #if !defined(HAVE_WIN32_IPC)  
  15.         // mmap the binder, providing a chunk of virtual address space to receive transactions.  
  16.         mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);  
  17.         if (mVMStart == MAP_FAILED) {  
  18.             // *sigh*  
  19.             LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");  
  20.             close(mDriverFD);  
  21.             mDriverFD = -1;  
  22.         }  
  23. #else  
  24.         mDriverFD = -1;  
  25. #endif  
  26.     }  
  27.     if (mDriverFD < 0) {  
  28.         // Need to run without the driver, starting our own thread pool.  
  29.     }  
  30. }  

3. 神奇的 defaultServiceManager

defaultServiceManager在IServiceManager.cpp中实现,其功能是获得一个IServiceManager对象。通过这个对象,就可以与进程/system/bin/servicemanager进行通信。

(defaultServiceManager实际返回的是BpServiceManager,它的remote对象是BpBinder,传入的那个handle参数是0。)

[html] view plaincopy
  1. sp<IServiceManager> defaultServiceManager()  
  2. {  
  3.     if (gDefaultServiceManager != NULL) return gDefaultServiceManager;  
  4.       
  5.     {  
  6.         AutoMutex _l(gDefaultServiceManagerLock);  
  7.         if (gDefaultServiceManager == NULL) {  
  8.             gDefaultServiceManager = <span style="color:#ff0000;">interface_cast</span><IServiceManager>(  
  9.                 ProcessState::self()->getContextObject(NULL));  
  10.         }  
  11.     }  
  12.       
  13.     return gDefaultServiceManager;  
  14. }  

ProcessState::self()->getContextObject(NULL)->  getStrongProxyForHandle(0)-> new BpBinder(handle) // handle值为0, 0在binder系统中代表ServiceManger所对应的BBinder.

 

即:gDefaultServiceManager = interface_cast<IServiceManager>(new BpBinder(0))

它创建了两个关键对象:

1)BpBinder对象,其handle为0

2)BpServiceManager对象,其mRemote值为1)中创建的BpBinder对象。

BpServiceManager实现了IServiceManager中定义的业务逻辑,又有一个成员BpBinder作为其通信代理。

3.1 如何把BpBinder转换为IServiceManager呢?

[html] view plaincopy
  1. template<typename INTERFACE>  
  2. inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)  
  3. {  
  4.     return INTERFACE::asInterface(obj);  
  5. }  
[html] view plaincopy
  1. 即:  
  2. inline sp<IServiceManager> interface_cast(const sp<IBinder>& obj)  
  3. {  
  4.     <span style="color:#3333ff;">return IServiceManager::asInterface(obj);  
  5. </span>}  


3.2 ServiceManager所提供的服务

[html] view plaincopy
  1. //IServiceManager.h  
  2. class IServiceManager : public IInterface  
  3. {  
  4. public:  
  5.     <span style="color:#3333ff;">DECLARE_META_INTERFACE(ServiceManager);  
  6. </span>  
  7.     /**  
  8.      * Retrieve an existing service, blocking for a few seconds  
  9.      * if it doesn't yet exist.  
  10.      */  
  11.     virtual sp<IBinder>         getService( const String16& name) const = 0;  
  12.   
  13.     /**  
  14.      * Retrieve an existing service, non-blocking.  
  15.      */  
  16.     virtual sp<IBinder>         checkService( const String16& name) const = 0;  
  17.   
  18.     /**  
  19.      * Register a service.  
  20.      */  
  21.     virtual status_t            addService( const String16& name,  
  22.                                             const sp<IBinder>& service) = 0;  
  23.   
  24.     /**  
  25.      * Return list of all existing services.  
  26.      */  
  27.     virtual Vector<String16>    listServices() = 0;  
  28.   
  29.     enum {  
  30.         GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,  
  31.         CHECK_SERVICE_TRANSACTION,  
  32.         ADD_SERVICE_TRANSACTION,  
  33.         LIST_SERVICES_TRANSACTION,  
  34.     };  
  35. }  

3.3 如何把业务与Binder通信连接起来

[html] view plaincopy
  1. //IInterface.h  
  2. #define DECLARE_META_INTERFACE(INTERFACE)                               \  
  3.     static const String16 descriptor;                                   \  
  4.     static sp<I##INTERFACE> asInterface(const sp<IBinder>& obj);        \  
  5.     virtual const String16& getInterfaceDescriptor() const;             \  
  6.     I##INTERFACE();                                                     \  
  7.     virtual ~I##INTERFACE();                                            \  

替换后得到:

[html] view plaincopy
  1. static const String16 descriptor;                                    
  2. static sp<IServiceManager> <span style="color:#3333ff;">asInterface</span>(const sp<IBinder>& obj);     
  3. virtual const String16& getInterfaceDescriptor() const;               
  4. IServiceManager();                                                    
  5. virtual ~IServiceManager();     


asInterface是如何实现的?

[html] view plaincopy
  1. // IServiceManager.cpp  
  2. IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");  
  3.   
  4. //IInterface.h  
  5. #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \  
  6.     const String16 I##INTERFACE::descriptor(NAME);                      \  
  7.     const String16& I##INTERFACE::getInterfaceDescriptor() const {      \  
  8.         return I##INTERFACE::descriptor;                                \  
  9.     }                                                                   \  
  10.     sp<I##INTERFACE> I##INTERFACE::asInterface(const sp<IBinder>& obj)  \  
  11.     {                                                                   \  
  12.         sp<I##INTERFACE> intr;                                          \  
  13.         if (obj != NULL) {                                              \  
  14.             intr = static_cast<I##INTERFACE*>(                          \  
  15.                 obj->queryLocalInterface(                               \  
  16.                         I##INTERFACE::descriptor).get());               \  
  17.             if (intr == NULL) {                                         \  
  18.                 intr = new Bp##INTERFACE(obj);                          \  
  19.             }                                                           \  
  20.         }                                                               \  
  21.         return intr;                                                    \  
  22.     }                                                                   \  
  23.     I##INTERFACE::I##INTERFACE() { }                                    \  
  24.     I##INTERFACE::~I##INTERFACE() { }                                   \  


替换后为:

[html] view plaincopy
  1. const String16 IServiceManager::descriptor("android.os.IServiceManager");                        
  2. const String16& IServiceManagerE::getInterfaceDescriptor() const {        
  3.     return IServiceManager::descriptor;                                  
  4. }                                                                     
  5. sp<IServiceManager> IServiceManager::<span style="color:#ff0000;">asInterface</span>(const sp<IBinder>& obj)    
  6. {                                                                     
  7.     sp<IServiceManager> intr;                                            
  8.     if (obj != NULL) {                                                
  9.         intr = static_cast<IServiceManager*>(                            
  10.             obj->queryLocalInterface(                                 
  11.                     IServiceManager::descriptor).get());                 
  12.         if (intr == NULL) {                                           
  13.             <span style="color:#3333ff;">intr = new BpServiceManager(obj);</span>                            
  14.         }                                                             
  15.     }                                                                 
  16.     return intr;                                                      
  17. }                                                                     
  18. IServiceManager::IServiceManager() { }                                      
  19. IServiceManager::~IServiceManager() { }            


如何把BpBinder转换为IServiceManager的答案为:intr = new BpServiceManager(obj);

其原理为:interface_cast并不是一个指针转换,而是把BpBinder做为一个参数,创建了一个新的BpServiceManager.

 

3.3.1 IServiceManager家族图谱

转自:http://book.51cto.com/art/201109/293428.htm

1)IServiceManager,BpServiceManager和BnServiceManager都与业务逻辑相关。

2)class BnServiceManager : public BnInterface<IServiceManager>
     BnServiceManager同时从IServiceManager和BBinder派生,表示它可以直接参与Binder通信。

3)class BpServiceManager : public BpInterface<IServiceManager>
     BpServiceManager同时从IServiceManager和BpRefBase派生。
     BpRefBase中有一个成员变量:IBinder* const   mRemote;

     注:以上关系较复杂,但ServiceManger并没有使用以上派生关系,而是直接打开Binder设备并与之交互。

4)BpRefBase的成员变量mRemote的值就是传进去的BpBinder,使用它就可以与BBinder进行通信了

5)intr = new BpServiceManager(obj);详细过程如下:

[html] view plaincopy
  1. BpServiceManager(const sp<IBinder>& impl)  
  2.    : BpInterface<IServiceManager>(impl)  
  3. {  
  4. }  
  5. template<typename INTERFACE>  
  6. inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)  
  7.     : BpRefBase(remote)  
  8. {  
  9. }  
  10. BpRefBase::BpRefBase(const sp<IBinder>& o)  
  11.     : <span style="color:#ff0000;">mRemote(o.get()), </span>mRefs(NULL), mState(0)  
  12. {  
  13.     extendObjectLifetime(OBJECT_LIFETIME_WEAK);  
  14.   
  15.     if (mRemote) {  
  16.         mRemote->incStrong(this);           // Removed on first IncStrong().  
  17.         mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.  
  18.     }  
  19. }  

 o.get(),这个是sp类的获取实际数据指针的一个方法,它返回的是sp<xxxx>中xxx* 类型的指针。

 

3.4 ProcessState & IPCThreadState

      ProcessState负责打开BinderDriver,准备好与Binder Driver通信;而IPCThreadState负责通过Binder Driver而进行跨进程的实际数据的读写。例如,client进程的程序调用BpBinder的IBinder中的transact()函数,此transact()函数则调用IPCThreadState中的transact()函数调用Binder Driver的ioctl()函数进行数据的传输。

IPCThreadState::transact->IPCThreadState::waitForResponse-> IPCThreadState::talkWithDriver->ioctl

[html] view plaincopy
  1. status_t BpBinder::transact(  
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  3. {  
  4.     // Once a binder has died, it will never come back to life.  
  5.     if (mAlive) {  
  6.         status_t status = IPCThreadState::self()->transact(  
  7.             mHandle, code, data, reply, flags);  
  8.         if (status == DEAD_OBJECT) mAlive = 0;  
  9.         return status;  
  10.     }  
  11.   
  12.     return DEAD_OBJECT;  
  13. }  


 4. 注册一个Service

以MediaPlayerService为例分析注册过程。 

[html] view plaincopy
  1. void MediaPlayerService::instantiate() {  
  2.     defaultServiceManager()->addService(  
  3.             String16("media.player"), new MediaPlayerService());  
  4. }  
  5. MediaPlayerService::MediaPlayerService()  
  6. {  
  7.     LOGV("MediaPlayerService created");  
  8.     mNextConnId = 1;  
  9.     mRatio = -1;  
  10.     mCrvs = -1;  
  11.     mLeft = -1;  
  12.     mTop =-1;  
  13.     mWidth =-1;  
  14.     mHeight =-1;  
  15. }  
  16. virtual status_t addService(const String16& name, const sp<IBinder>& service)  
  17. {  
  18.     Parcel data, reply;  
  19.     data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  20.     data.writeString16(name);  
  21.     data.writeStrongBinder(service);  
  22.     status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  23.     return err == NO_ERROR ? reply.readInt32() : err;  
  24. }  

remote()返回的就是BpServiceManager中保存的BpBinder。

MediaPlayerService 从BnMediaPlayerService派生,其家族关系如下:

[html] view plaincopy
  1. class MediaPlayerService : public BnMediaPlayerService //业务逻辑和通信  
  2. class BnMediaPlayerService: public BnInterface<IMediaPlayerService>  
  3. class BnInterface : public IMediaPlayerService, public BBinder  
  4. //IMediaPlayerService:负责业务逻辑  
  5. //BBinder:负责通信  
[html] view plaincopy
  1. class MediaPlayerService : public BnMediaPlayerService  
  2. {  
  3.     class Client;  
  4.     class MediaConfigClient;  
  5.   
  6.     class AudioOutput : public MediaPlayerBase::AudioSink  
  7.     {  
  8.      ...  
  9.     };  
  10.   
  11.     class AudioCache : public MediaPlayerBase::AudioSink  
  12.     {  
  13.      ...  
  14.     };  
  15.   
  16. public:  
  17.     static  void                instantiate();  
  18.   
  19.     // IMediaPlayerService interface  
  20.     virtual sp<IMediaRecorder>  createMediaRecorder(pid_t pid);  
  21.     void    removeMediaRecorderClient(wp<MediaRecorderClient> client);  
  22.     virtual sp<IMediaMetadataRetriever> createMetadataRetriever(pid_t pid);  
  23.   
  24.     // House keeping for media player clients  
  25.     virtual sp<IMediaPlayer>    create(  
  26.             pid_t pid, const sp<IMediaPlayerClient>& client, const char* url,  
  27.             const KeyedVector<String8, String8> *headers);  
  28.   
  29.     virtual sp<IMediaPlayer>    create(pid_t pid, const sp<IMediaPlayerClient>& client, int fd, int64_t offset, int64_t length);  
  30.     virtual sp<IMediaConfig>   createMediaConfig(pid_t pid);  
  31.     virtual sp<IMemory>         decode(const char* url, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);  
  32.     virtual sp<IMemory>         decode(int fd, int64_t offset, int64_t length, uint32_t *pSampleRate, int* pNumChannels, int* pFormat);  
  33.     virtual sp<IMemory>         snoop();  
  34.     virtual sp<IOMX>            getOMX();  
  35. private:  
  36.   
  37.     class Client : public BnMediaPlayer {  
  38.         virtual status_t        prepareAsync();  
  39.         virtual status_t        start();  
  40.         virtual status_t        stop();  
  41.         virtual status_t        pause();  
  42.         virtual status_t        isPlaying(bool* state);  
  43.         virtual status_t        seekTo(int msec);  
  44.         virtual status_t        getCurrentPosition(int* msec);  
  45.         virtual status_t        getDuration(int* msec);  
  46.         virtual status_t        reset();  
  47.         virtual status_t        setAudioStreamType(int type);  
  48.         virtual status_t        setLooping(int loop);  
  49.         virtual status_t        setVolume(float leftVolume, float rightVolume);  
  50.         virtual status_t        invoke(const Parcel& request, Parcel *reply);  
  51.         virtual status_t        setMetadataFilter(const Parcel& filter);  
  52.         virtual status_t        getMetadata(bool update_only,  
  53.                                             bool apply_filter,  
  54.                                             Parcel *reply);  
  55.   
  56.         sp<MediaPlayerBase>     createPlayer(player_type playerType);  
  57.   
  58.                 status_t        setDataSource(  
  59.                                 const char *url,  
  60.                                 const KeyedVector<String8, String8> *headers);  
  61.   
  62.                 status_t        setDataSource(int fd, int64_t offset, int64_t length);  
  63.         static  void            notify(void* cookie, int msg, int ext1, int ext2);  
  64.   
  65.     private:  
  66.         friend class MediaPlayerService;  
  67.         sp<MediaPlayerBase>     getPlayer() const { Mutex::Autolock lock(mLock); return mPlayer; }  
  68.     };  
  69.   
  70.   
  71.     class MediaConfigClient: public BnMediaConfig  
  72.     {  
  73.        ...  
  74.     };  
  75.   
  76. // ----------------------------------------------------------------------------  
  77.   
  78.                             MediaPlayerService();  
  79.     virtual                 ~MediaPlayerService();  
  80.   
  81.     mutable     Mutex                       mLock;  
  82.                 SortedVector< wp<Client> >  mClients;  
  83.                 SortedVector< wp<MediaRecorderClient> > mMediaRecorderClients;  
  84.                 int32_t                     mNextConnId;  
  85.                 sp<IOMX>                    mOMX;  
  86.     int32_t mRatio;  
  87.     int32_t mCrvs;  
  88.     int32_t mLeft;  
  89.     int32_t mTop;  
  90.     int32_t mWidth;  
  91.     int32_t mHeight;  
  92. }  

 

4.1 addService

[html] view plaincopy
  1. void MediaPlayerService::instantiate() {  
  2.     defaultServiceManager()->addService(  
  3.             String16("media.player"), new MediaPlayerService());  
  4. }  

创建一个新的Service—BnMediaPlayerService,想把它告诉ServiceManager。然后调用BpServiceManger的addService来向ServiceManager中增加一个Service.其它进程可通过字符串"media.player"来向ServiceManger查询到此服务。

addService是调用的BpServiceManager的函数。

[html] view plaincopy
  1. virtual status_t addService(const String16& name, const sp<IBinder>& service)  
  2.   
  3.     {  
  4.   
  5.         Parcel data, reply;  
  6.   
  7.         //data是发送到BnServiceManager的命令包  
  8.   
  9.         //看见没?先把Interface名字写进去,也就是什么android.os.IServiceManager  
  10.   
  11.         data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  12.   
  13.         //再把新service的名字写进去 叫media.player  
  14.   
  15.         data.writeString16(name);  
  16.   
  17.         //把新服务service—>就是MediaPlayerService写到命令中  
  18.   
  19.         data.writeStrongBinder(service); <span style="color:#ff0000;">//把MediaPlayerService写入flat_binder_object中  
  20.   
  21. </span>        //调用remote的transact函数  
  22.   
  23.         status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  24.   
  25.         return err == NO_ERROR ? reply.readInt32() : err;  
  26.   
  27. }  

remote()返回的是前面创建的BpBinder(0).

[html] view plaincopy
  1. status_t BpBinder::transact(  
  2.   
  3.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  
  4.   
  5. {  
  6.         //注意啊,这里的mHandle为0,code是ADD_SERVICE_TRANSACTION,data是命令包  
  7.          //reply是回复包,flags=0  
  8.         status_t status = IPCThreadState::self()->transact(  
  9.             mHandle, code, data, reply, flags);  
  10.         if (status == DEAD_OBJECT) mAlive = 0;  
  11.            return status;  
  12.     }  
  13. ...  
  14. }  
[html] view plaincopy
  1. status_t IPCThreadState::transact(int32_t handle,  
  2.                                   uint32_t code, const Parcel& data,  
  3.                                   Parcel* reply, uint32_t flags)  
  4. {  
  5.     status_t err = data.errorCheck();  
  6.   
  7.     flags |= TF_ACCEPT_FDS;  
  8.   
  9.     IF_LOG_TRANSACTIONS() {  
  10.         TextOutput::Bundle _b(alog);  
  11.         alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "  
  12.             << handle << " / code " << TypeCode(code) << ": "  
  13.             << indent << data << dedent << endl;  
  14.     }  
  15.       
  16.     if (err == NO_ERROR) {  
  17.         LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),  
  18.             (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");  
  19.         err = <span style="color:#ff0000;">writeTransactionData</span>(BC_TRANSACTION, flags, handle, code, data, NULL);//把要发送的数据写入binder_transaction_data中  
  20.     }  
  21.       
  22.     if (err != NO_ERROR) {  
  23.         if (reply) reply->setError(err);  
  24.         return (mLastError = err);  
  25.     }  
  26.       
  27.     if ((flags & TF_ONE_WAY) == 0) {  
  28.         if (reply) {  
  29.             err = waitForResponse(reply);  
  30.         } else {  
  31.             Parcel fakeReply;  
  32.             err = <span style="color:#ff0000;">waitForResponse</span>(&fakeReply);  
  33.         }  
  34.           
  35.         IF_LOG_TRANSACTIONS() {  
  36.             TextOutput::Bundle _b(alog);  
  37.             alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "  
  38.                 << handle << ": ";  
  39.             if (reply) alog << indent << *reply << dedent << endl;  
  40.             else alog << "(none requested)" << endl;  
  41.         }  
  42.     } else {  
  43.         err = waitForResponse(NULL, NULL);  
  44.     }  
  45.       
  46.     return err;  
  47. }  

 

[html] view plaincopy
  1. status_t IPCThreadState::<span style="color:#ff0000;">writeTransactionData</span>(int32_t cmd, uint32_t binderFlags,  
  2.     int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer)  
  3. {  
  4.     binder_transaction_data tr;  
  5.   
  6.     tr.target.handle = handle;  
  7.     tr.code = code;  
  8.     tr.flags = binderFlags;  
  9.       
  10.     const status_t err = data.errorCheck();  
  11.     if (err == NO_ERROR) {  
  12.         tr.data_size = data.ipcDataSize();  
  13.         tr.data.ptr.buffer = data.ipcData();  
  14.         tr.offsets_size = data.ipcObjectsCount()*sizeof(size_t);  
  15.         tr.data.ptr.offsets = data.ipcObjects();  
  16.     } else if (statusBuffer) {  
  17.         tr.flags |= TF_STATUS_CODE;  
  18.         *statusBuffer = err;  
  19.         tr.data_size = sizeof(status_t);  
  20.         tr.data.ptr.buffer = statusBuffer;  
  21.         tr.offsets_size = 0;  
  22.         tr.data.ptr.offsets = NULL;  
  23.     } else {  
  24.         return (mLastError = err);  
  25.     }  
  26.       
  27.     mOut.writeInt32(cmd);  
  28.     mOut.write(&tr, sizeof(tr));  
  29.       
  30.     return NO_ERROR;  
  31. }  

上面的代码把数据封装成binder_transaction_data,然后写到mOut中。mOut是一个命令buffer,也是一个Parcel.

[html] view plaincopy
  1. status_t IPCThreadState::<span style="color:#ff0000;">waitForResponse</span>(Parcel *reply, status_t *acquireResult)  
  2. {  
  3.     int32_t cmd;  
  4.     int32_t err;  
  5.   
  6.     while (1) {  
  7.         if ((err=<span style="color:#ff0000;">talkWithDriver</span>()) < NO_ERROR) break; //发送数据到ServiceManager  
  8.         err = mIn.errorCheck();  
  9.         if (err < NO_ERROR) break;  
  10.         if (mIn.dataAvail() == 0) continue;  
  11.           
  12.         cmd = mIn.readInt32();  
  13.           
  14.         IF_LOG_COMMANDS() {  
  15.             alog << "Processing waitForResponse Command: "  
  16.                 << getReturnString(cmd) << endl;  
  17.         }  
  18.   
  19.         switch (cmd) {  
  20.         case BR_TRANSACTION_COMPLETE:  
  21.             if (!reply && !acquireResult) goto finish;  
  22.             break;  
  23.           
  24.         case BR_DEAD_REPLY:  
  25.             err = DEAD_OBJECT;  
  26.             goto finish;  
  27.   
  28.         case BR_FAILED_REPLY:  
  29.             err = FAILED_TRANSACTION;  
  30.             goto finish;  
  31.           
  32.         case BR_ACQUIRE_RESULT:  
  33.             {  
  34.                 LOG_ASSERT(acquireResult != NULL, "Unexpected brACQUIRE_RESULT");  
  35.                 const int32_t result = mIn.readInt32();  
  36.                 if (!acquireResult) continue;  
  37.                 *acquireResult = result ? NO_ERROR : INVALID_OPERATION;  
  38.             }  
  39.             goto finish;  
  40.           
  41.         case BR_REPLY:  
  42.             {  
  43.                 binder_transaction_data tr;  
  44.                 err = mIn.read(&tr, sizeof(tr));  
  45.                 LOG_ASSERT(err == NO_ERROR, "Not enough command data for brREPLY");  
  46.                 if (err != NO_ERROR) goto finish;  
  47.   
  48.                 if (reply) {  
  49.                     if ((tr.flags & TF_STATUS_CODE) == 0) {  
  50.                         reply->ipcSetDataReference(  
  51.                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  52.                             tr.data_size,  
  53.                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  54.                             tr.offsets_size/sizeof(size_t),  
  55.                             freeBuffer, this);  
  56.                     } else {  
  57.                         err = *static_cast<const status_t*>(tr.data.ptr.buffer);  
  58.                         freeBuffer(NULL,  
  59.                             reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  60.                             tr.data_size,  
  61.                             reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  62.                             tr.offsets_size/sizeof(size_t), this);  
  63.                     }  
  64.                 } else {  
  65.                     freeBuffer(NULL,  
  66.                         reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),  
  67.                         tr.data_size,  
  68.                         reinterpret_cast<const size_t*>(tr.data.ptr.offsets),  
  69.                         tr.offsets_size/sizeof(size_t), this);  
  70.                     continue;  
  71.                 }  
  72.             }  
  73.             goto finish;  
  74.   
  75.         default:  
  76.             err = executeCommand(cmd);  
  77.             if (err != NO_ERROR) goto finish;  
  78.             break;  
  79.         }  
  80.     }  
  81.   
  82. finish:  
  83.     if (err != NO_ERROR) {  
  84.         if (acquireResult) *acquireResult = err;  
  85.         if (reply) reply->setError(err);  
  86.         mLastError = err;  
  87.     }  
  88.       
  89.     return err;  
  90. }  

 

[html] view plaincopy
  1. status_t IPCThreadState::talkWithDriver(bool doReceive)  
  2. {  
  3.     LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");  
  4.       
  5.     <span style="color:#ff0000;">binder_write_read bwr;  
  6. </span>      
  7.     // Is the read buffer empty?  
  8.     const bool needRead = mIn.dataPosition() >= mIn.dataSize();  
  9.       
  10.     // We don't want to write anything if we are still reading  
  11.     // from data left in the input buffer and the caller  
  12.     // has requested to read the next data.  
  13.     const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;  
  14.       
  15. <span style="color:#3333ff;">    bwr.write_size = outAvail;  
  16.     bwr.write_buffer = (long unsigned int)mOut.data();</span>  
  17.   
  18.     // This is what we'll read.  
  19.     if (doReceive && needRead) {  
  20.  <span style="color:#3333ff;">       bwr.read_size = mIn.dataCapacity();  
  21.         bwr.read_buffer = (long unsigned int)mIn.data();  
  22. </span>    } else {  
  23.         bwr.read_size = 0;  
  24.     }  
  25.       
  26.     IF_LOG_COMMANDS() {  
  27.         TextOutput::Bundle _b(alog);  
  28.         if (outAvail != 0) {  
  29.             alog << "Sending commands to driver: " << indent;  
  30.             const void* cmds = (const void*)bwr.write_buffer;  
  31.             const void* end = ((const uint8_t*)cmds)+bwr.write_size;  
  32.             alog << HexDump(cmds, bwr.write_size) << endl;  
  33.             while (cmds < endcmds = printCommand(alog, cmds);  
  34.             alog << dedent;  
  35.         }  
  36.         alog << "Size of receive buffer: " << bwr.read_size  
  37.             << ", needRead: " << needRead << ", doReceive: " << doReceive << endl;  
  38.     }  
  39.       
  40.     // Return immediately if there is nothing to do.  
  41.     if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;  
  42.       
  43.     bwr.write_consumed = 0;  
  44.     bwr.read_consumed = 0;  
  45.     status_t err;  
  46.     do { //<span style="color:red;">中间东西太复杂了,就是把<span lang="EN-US">mOut发送</span>数据和<span lang="EN-US">mIn</span>接收数据的处理后赋值给<span lang="EN-US">bwr</span></span>  
  47.         IF_LOG_COMMANDS() {  
  48.             alog << "About to read/write, write size = " << mOut.dataSize() << endl;  
  49.         }  
  50. #if defined(HAVE_ANDROID_OS)  
  51.        <span style="color:#ff0000;"> <span style="font-size:13px;"><strong>if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)</strong>  
  52. </span></span>            err = NO_ERROR;  
  53.         else  
  54.             err = -errno;  
  55. #else  
  56.         err = INVALID_OPERATION;  
  57. #endif  
  58.         IF_LOG_COMMANDS() {  
  59.             alog << "Finished read/write, write size = " << mOut.dataSize() << endl;  
  60.         }  
  61.     } while (err == -EINTR);  
  62.     <span style="color:red;">//</span><span style="color:red;">到这里,回复数据就在<span lang="EN-US">bwr</span>中了,<span lang="EN-US">bwr</span>接收回复数据的<span lang="EN-US">buffer</span>就是<span lang="EN-US">mIn</span>提供的<span lang="EN-US"><o:p></o:p></span></span>  
  63.     IF_LOG_COMMANDS() {  
  64.         alog << "Our err: " << (void*)err << ", write consumed: "  
  65.             << bwr.write_consumed << " (of " << mOut.dataSize()  
  66.             << "), read consumed: " << bwr.read_consumed << endl;  
  67.     }  
  68.   
  69.     if (err >= NO_ERROR) {  
  70.         if (bwr.write_consumed > 0) {  
  71.             if (bwr.write_consumed < (ssize_t)mOut.dataSize())  
  72.                 mOut.remove(0, bwr.write_consumed);  
  73.             else  
  74.                 mOut.setDataSize(0);  
  75.         }  
  76.         if (bwr.read_consumed > 0) {  
  77.             mIn.setDataSize(bwr.read_consumed);  
  78.             mIn.setDataPosition(0);  
  79.         }  
  80.         IF_LOG_COMMANDS() {  
  81.             TextOutput::Bundle _b(alog);  
  82.             alog << "Remaining data size: " << mOut.dataSize() << endl;  
  83.             alog << "Received commands from driver: " << indent;  
  84.             const void* cmds = mIn.data();  
  85.             const void* end = mIn.data() + mIn.dataSize();  
  86.             alog << HexDump(cmds, mIn.dataSize()) << endl;  
  87.             while (cmds < endcmds = printReturnCommand(alog, cmds);  
  88.             alog << dedent;  
  89.         }  
  90.         return NO_ERROR;  
  91.     }  
  92.       
  93.     return err;  
  94. }  

       至此发送addService到ServiceManager就已经结束了。BpServiceManager发送了一个addService命令到BnServiceManager,然后收到回复。

 

       问题:MediaPlayerService是一个BnMediaPlayerService,那么它是不是应该等着

BpMediaPlayerService来和他交互呢?但是我们没看见MediaPlayerService有打开binder设备的操作啊!

0 0
原创粉丝点击