Android源碼分析--MediaServer源碼分析(一)

來源:互聯網
上載者:User

標籤:源碼   android   

MediaServer中包括了系統中的許多重要的Server:

  • AudioFlinger:音頻系統中的核心服務
  • AudioPolicyService:音頻系統中關於音頻策略的重要服務
  • MediaPlayerService:多媒體系統中的重要服務
  • CameraService:有關照相和攝像的重要服務

同時,分析MediaServer對於理解Android中的IPC機制能夠提供較好的協助。Android系統基本上可以看做是一個基於Binder機制的C/S架構,對於Binder機制的理解相對比較複雜,如果能夠通過具體的例子入手會比較容易理解。

Android的通訊體制架構

Android的通訊機制基本上可以看做是Client、Server和ServiceManager三者之間的互動:

  1. Server首先要註冊一些Service到ServiceManager,在這裡Server是ServiceManager的用戶端;
  2. 如果某個Client要使用Service,則首先到ServiceManager中獲得該Service的相關資訊,所有Client是ServiceManager的用戶端;
  3. Client得到Service資訊,然後和該Service所在的Server進程建立通訊之後使用Service,在這裡Client是Server的用戶端。
    在這些互動的過程中,Android系統都是使用的Binder來進行通訊。
MediaServer入口函數

MS是一個可執行程式,它的入口函數是main函數,所在檔案位置:frameworks\base\media\mediaserver\main_mediaserver.cpp
代碼如下:

int main(int argc, char** argv){    sp<ProcessState> proc(ProcessState::self());    sp<IServiceManager> sm = defaultServiceManager();    ALOGI("ServiceManager: %p", sm.get());    AudioFlinger::instantiate();    MediaPlayerService::instantiate();    CameraService::instantiate();    AudioPolicyService::instantiate();    ProcessState::self()->startThreadPool();    IPCThreadState::self()->joinThreadPool();}

可以看到,在main函數中,

  1. 我們首先獲得了一個ProcessState的執行個體,由self方法我們可以猜得到該類使用了單例模式;
  2. 接下來我們調用了defaultServiceManager方法獲得IServiceManager執行個體;
  3. 接下來進行了幾個重要服務的初始化工作;
  4. 調用startThreadPool方法和joinThreadPool方法。
ProcessState類的分析

檔案位置:frameworks\base\libs\binder\ProcessState.cpp
self方法:在main函數中,我們調用了self方法得到了一個ProcessState執行個體,下面我們來看看這個方法

sp<ProcessState> ProcessState::self(){    if (gProcess != NULL) return gProcess;    //提供原子操作    AutoMutex _l(gProcessMutex);    if (gProcess == NULL) gProcess = new ProcessState;    return gProcess;}

可以看到,不出所料,ProcessState使用的就是單例模式。
接下來我們來看一看ProcessState的建構函式:

ProcessState::ProcessState()    : mDriverFD(open_driver())    , mVMStart(MAP_FAILED)    , mManagesContexts(false)    , mBinderContextCheckFunc(NULL)    , mBinderContextUserData(NULL)    , mThreadPoolStarted(false)    , mThreadPoolSeq(1){    if (mDriverFD >= 0) {        // XXX Ideally, there should be a specific define for whether we        // have mmap (or whether we could possibly have the kernel module        // availabla).#if !defined(HAVE_WIN32_IPC)        // mmap the binder, 提供一個虛擬放入地址記憶體空間塊去接收事務        mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);        if (mVMStart == MAP_FAILED) {            // *sigh*            ALOGE("Using /dev/binder failed: unable to mmap transaction memory.\n");            close(mDriverFD);            mDriverFD = -1;        }#else        mDriverFD = -1;#endif    }    LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver could not be opened.  Terminating.");}

可以看到,在建構函式中首先調用了open_driver函數並將傳回值賦給了mDriverFD,讓我們來看看這個函數:

static int open_driver(){    int fd = open("/dev/binder", O_RDWR);    if (fd >= 0) {        fcntl(fd, F_SETFD, FD_CLOEXEC);        int vers;        status_t result = ioctl(fd, BINDER_VERSION, &vers);        if (result == -1) {            ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));            close(fd);            fd = -1;        }        if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {            ALOGE("Binder driver protocol does not match user space protocol!");            close(fd);            fd = -1;        }        size_t maxThreads = 15;        result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);        if (result == -1) {            ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));        }    } else {        ALOGW("Opening ‘/dev/binder‘ failed: %s\n", strerror(errno));    }    return fd;}

可以看到open_driver函數主要是開啟了/dev/binder這個裝置並返回了這個裝置的fd。

接下來我繼續回到建構函式中,在mDriverFD中儲存了這個裝置的fd,接著我們又對其他的成員變數做了一些初始化,然後調用mmap函數為Binder裝置開闢一塊記憶體由於接收資料。

總結一下,我們的ProcessState類的任務:

  1. 開啟了Binder裝置,並儲存了裝置的fd;
  2. 利用儲存的fd為Binder裝置開闢一塊記憶體用於接收資料;
  3. 因為ProcessState採用了單例模式,因此每個進程只能開啟一次Binder裝置。
defaultServiceManager函數分析

檔案位置:frameworks\base\libs\binder\IServiceManager.cpp

sp<IServiceManager> defaultServiceManager(){    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;    {        AutoMutex _l(gDefaultServiceManagerLock);        if (gDefaultServiceManager == NULL) {            gDefaultServiceManager = interface_cast<IServiceManager>(                ProcessState::self()->getContextObject(NULL));        }    }    return gDefaultServiceManager;}

可以看到gDefaultServiceManager函數主要是對gDefaultServiceManager 進行賦值,首先我們來看看這個函數的傳入參數: ProcessState::self()->getContextObject(NULL)

sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller){    return getStrongProxyForHandle(0);}sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle){    sp<IBinder> result;    AutoMutex _l(mLock);    handle_entry* e = lookupHandleLocked(handle);    if (e != NULL) {        // 如果現在不存在或者我們不能得到它的引用時,我們需要建立一個新的BpBinder,         IBinder* b = e->binder;        if (b == NULL || !e->refs->attemptIncWeak(this)) {            b = new BpBinder(handle);             e->binder = b;            if (b) e->refs = b->getWeakRefs();            result = b;        } else {            result.force_set(b);            e->refs->decWeak(this);        }    }    return result;}

可以看到其實我們返回了一個BpBinder(handle);handle的值為0。

interface_cast看起來像一個強制類型轉換,其實是一個模板函數,下面我們來看看它的廬山真面目:

template<typename INTERFACE>inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj){    return INTERFACE::asInterface(obj);}

我們傳入的模板是IServiceManager,則實際上調用的就是IServiceManager的asInterface方法。
asInterface方法的聲明和實現實際上是通過兩個宏定義實現的,位於IInterface.h檔案中:

#define DECLARE_META_INTERFACE(INTERFACE)                               \    static const android::String16 descriptor;                              static android::sp<I##INTERFACE> asInterface(                       \            const android::sp<android::IBinder>& obj);                      virtual const android::String16& getInterfaceDescriptor() const;        I##INTERFACE();                                                     \    virtual ~I##INTERFACE();                                            \#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \    const android::String16 I##INTERFACE::descriptor(NAME);             \    const android::String16&                                                        I##INTERFACE::getInterfaceDescriptor() const {              \        return I##INTERFACE::descriptor;                                \    }                                                                       android::sp<I##INTERFACE> I##INTERFACE::asInterface(                \            const android::sp<android::IBinder>& obj)                       {                                                                           android::sp<I##INTERFACE> intr;                                 \        if (obj != NULL) {                                                          intr = static_cast<I##INTERFACE*>(                          \                obj->queryLocalInterface(                                                       I##INTERFACE::descriptor).get());               \            if (intr == NULL) {                                                         intr = new Bp##INTERFACE(obj);                          \            }                                                                   }                                                                       return intr;                                                        }                                                                       I##INTERFACE::I##INTERFACE() { }                                    \    I##INTERFACE::~I##INTERFACE() { }                                   \

將INTERFACE替換為IServiceManager後可以得到:

static const android::String16 descriptor;                              static android::sp<IServiceManager> asInterface(                                   const android::sp<android::IBinder>& obj);                      virtual const android::String16& getInterfaceDescriptor() const;        IServiceManager();                                                     virtual ~IServiceManager();                          const android::String16 IServiceManager::descriptor(NAME);                const android::String16&                                                        IServiceManager::getInterfaceDescriptor() const {                      return IServiceManager::descriptor;                                    }                                                                       android::sp<IServiceManager> IServiceManager::asInterface(                            const android::sp<android::IBinder>& obj)                       {                                                                           android::sp<IServiceManager> intr;                                         if (obj != NULL) {                                                          intr = static_cast<IServiceManager*>(                                          obj->queryLocalInterface(                                                       IServiceManager::descriptor).get());                           if (intr == NULL) {                                                         intr = new BpServiceManager(obj);                                      }                                                                   }                                                                       return intr;                                                        }                                                                   IServiceManager::IServiceManager() { }                                    IServiceManager::~IServiceManager() { } 

可以看到asInterface方法最終實際上返回了一個BpServiceManager對象。
總結一下defaultServiceManager方法的工作:

  1. 建立了一個BpBinder對象,用來負責用戶端Binder通訊(之後會講到),因為對於ServiceManager來說我們是用戶端,所以在這裡我們建立了Binder的用戶端;
  2. 建立了一個BpServiceManager對象,主要負責IServiceManager的業務函數,在他的內部持有一個BpBinder對象mRemote。
類別關係總結

看到這裡,已經有點眼花繚亂了,又是IBinder,又是IServiceManager,又是BpBinder,又是BpServiceManager,是時候來總結一下這些類的關係了,翻了一下這些類,下面用一個不標準的UML圖來說明一下:

需要注意的是:

  1. RefBase是Android中所有類的祖先,相當於Java中Object;
  2. BpBinder和BBinder都是Android中Binder通訊的代表類,其中BpBinder是用戶端用來與Server互動的代理類,p代表的就是proxy,而BBinder則是互動的目的端;
  3. BpBinder和BBinder是相互對應的,Binder系統會通過handle來標識對應的BBinder;
  4. BnServiceManager中n代表的是native,與Bn相對應的應該是BpServiceManager,表示ServiceManager的業務代理類。

Android源碼分析--MediaServer源碼分析(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.