美文网首页framework学习笔记
framework 学习笔记5. Media服务的添加过程

framework 学习笔记5. Media服务的添加过程

作者: 加个标志位 | 来源:发表于2020-12-08 17:19 被阅读0次

一. media进程是init进程解析init.rc开启的,MediaServer启动后fork了一个子进程,在子进程将各种多媒体进行注册,其中就包括MediaPlayerService。frameworks\av\media\mediaserver\ Main_mediaserver.cpp

int main(int argc __unused, char** argv)
{
    signal(SIGPIPE, SIG_IGN);
    char value[PROPERTY_VALUE_MAX];
    bool doLog = (property_get("ro.test_harness", value, "0") > 0) && (atoi(value) == 1);
    pid_t childPid;
    //主进程
    if (doLog && (childPid = fork()) != 0) {
        strcpy(argv[0], "media.log");
        //单例创建ProcessState实例,同时打开Binder驱动
        sp<ProcessState> proc(ProcessState::self());
        MediaLogService::instantiate();
        ProcessState::self()->startThreadPool();
        for (;;) {
            siginfo_t info;
            //等子进程结束
            int ret = waitid(P_PID, childPid, &info, WEXITED | WSTOPPED | WCONTINUED);
            if (ret == EINTR) {
                continue;
            }
            if (ret < 0) {
                break;
            }
            //省略部分代码 
            ...                        
            sp<IServiceManager> sm = defaultServiceManager();
            sp<IBinder> binder = sm->getService(String16("media.log"));          
     //子进程
    } else { 
         //单例创建ProcessState实例,同时打开Binder驱动     
        sp<ProcessState> proc(ProcessState::self());
         //获取ServiceManger
        sp<IServiceManager> sm = defaultServiceManager();
        ALOGI("ServiceManager: %p", sm.get());
        //初始化各种媒体服务
        AudioFlinger::instantiate();
        //初始化MediaPlayerService
        MediaPlayerService::instantiate();
        CameraService::instantiate();
        AudioPolicyService::instantiate();
        SoundTriggerHwService::instantiate();
        registerExtensions();
        //新建子线程读写
        ProcessState::self()->startThreadPool();
        //启动线程读写
        IPCThreadState::self()->joinThreadPool();
    }
}

1.1 每个进程只有一个ProcessState,self()是一个单例函数,ProcessState构建同时打开了Binder驱动。

sp<ProcessState> ProcessState::self()
{
    Mutex::Autolock _l(gProcessMutex); //注释1
    //创建保存为全局变量     
    if (gProcess != NULL) {
        return gProcess;
    }
    //创建保存为全局变量
    gProcess = new ProcessState;
    return gProcess;
}

注释1:智能锁,定义一个Mutex 对象mLock,在代码中对全局变量访问时,先要获取mLock,例如上面在执行if操作时,先通过Mutex::Autolock _l(mLock);获取这把锁,加了大括号是限制这个锁的作用域,离开这个作用域之后,这把锁会自动释放。

1.2 分析ProcessState

ProcessState::ProcessState()
    : mDriverFD(open_driver())  //打开binder驱动  见注释2
    , mVMStart(MAP_FAILED)
    , mManagesContexts(false)
    , mBinderContextCheckFunc(NULL)
    , mBinderContextUserData(NULL)
    , mThreadPoolStarted(false)
    , mThreadPoolSeq(1)
{
    if (mDriverFD >= 0) {     
        // mmap the binder, providing a chunk of virtual address space to receive transactions.
        //映射内存(虚拟内存),调用的时调用的时binder_mmap()方法;这块内存开辟时时私有的,可读不可写;
        //#define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2)),大小为1M-8k
        mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
    }

}

注释2:打开binder驱动

static int open_driver()
{
    int fd = open("/dev/binder", O_RDWR);
    if (fd >= 0) {              
        //设置驱动层的最大线程数;调用的时binder_ioctl()方法;
        size_t maxThreads = 15;
        result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
    } else {
        ALOGW("Opening '/dev/binder' failed: %s\n", strerror(errno));
    }
    return fd;
}

2 分析:IServiceManager.cpp中的defaultServiceManager()方法:

sp<IServiceManager> defaultServiceManager(){
    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;    
    {
        AutoMutex _l(gDefaultServiceManagerLock);
        while (gDefaultServiceManager == NULL) {
            gDefaultServiceManager = interface_cast<IServiceManager>(//见2.2
                ProcessState::self()->getContextObject(NULL));//见2.1
            if (gDefaultServiceManager == NULL)
                //虽然ServiceManager是比MediaServer服务先开启,但是在此时sleep(1)是等待确保ServiceManager成功启动
                sleep(1); 
        }
    }    
    return gDefaultServiceManager;
}

(1) ProcessState中getContextObject(NULL) ==>
ProcessState中getStrongProxyForHandle(0) //注意这里传入的值为0 ==>
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
(2) gDefaultServiceManager = interface_cast<IServiceManager>()方法

2.1ProcessState::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
    handle_entry* e = lookupHandleLocked(handle);
    if (e != NULL) {
        //如果是第一次执行时, 通过创建的e来获取到的binder是为空的;
        IBinder* b = e->binder;
        if (b == NULL || !e->refs->attemptIncWeak(this)) {
            if (handle == 0) {             
                Parcel data;
                //ping一下ServiceManager,检查一下是不是能工作
                status_t status = IPCThreadState::self()->transact(
                        0, IBinder::PING_TRANSACTION, data, NULL, 0);
                if (status == DEAD_OBJECT)
                   return NULL;
            }
            //这里传入的handle的值为0 ==> b = new BpBinder(0);
            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;
}

2.2 gDefaultServiceManager = interface_cast<IServiceManager>

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)  { //obj也就是2.1中的 b = new BpBinder(0);
    //这里的INTERFACE,也就是IServiceManager,但是在IServiceManager中找不到asInterface(obj)方法,所以去
    //IServiceManager的父类IInterface中找到asInterface(obj)方法;详情见2.3
    return INTERFACE::asInterface(obj); 
}

2.3
"#define DECLARE_META_INTERFACE(INTERFACE)"和
"#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)"
都是宏定义,如果定义了这个宏,那么就会动态的去加载;我们在IServiceManager中可以找到这个的定义
==>IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");

//方法的声明
#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) {                                         \
                // 下面的等同于new BpServiceManager(new BpBinder(handle));
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    I##INTERFACE::I##INTERFACE() { }                                    \
    I##INTERFACE::~I##INTERFACE() { }    

所以最终defaultServiceManager() = new BpServiceManager(new BpBinder(handle));

  1. 从各种服务中选出一个MediaPlayerService::instantiate()分析下:
void MediaPlayerService::instantiate() {
    defaultServiceManager()->addService(
            String16("media.player"), new MediaPlayerService());
}

由上文我们知道defaultServiceManager()最终得到的是BpServiceManager ==> 在BpServiceManager中找到addService()方法
3.1 添加服务: addService()

  virtual status_t addService(const String16& name, const sp<IBinder>& service, bool allowIsolated){
        Parcel data, reply;
        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
        data.writeString16(name);
        data.writeStrongBinder(service);//见3.2
        data.writeInt32(allowIsolated ? 1 : 0);
        //从BpServiceManager的父类               [注意点: new BpServiceManager(new BpBinder(handle));]
        //BpInterface(const sp<IBinder>& remote)  == > 中可以得知:
        //remote()最终返回的是new BpBinder(0)
        status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);   // transact()方法见3.3
        return err == NO_ERROR ? reply.readExceptionCode() : err;
    }

getInterfaceDescriptor() ==> 从宏定义(“#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)”)中获取到 ==>
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager"),即"android.os.IServiceManager";
data.writeString16(name):name是传入的服务的名字,及media.player;
data.writeStrongBinder(service):写入对象,这里是new MediaPlayerService();

3.2 Parce.writeStrongBinder(new MediaPlayerService())

status_t Parcel::writeStrongBinder(const sp<IBinder>& val){
    return flatten_binder(ProcessState::self(), val, this);
}

//调用flatten_binder(ProcessState::self(), val, this);
status_t flatten_binder(const sp<ProcessState>& /*proc*/, const sp<IBinder>& binder, Parcel* out)
{
    flat_binder_object obj;
    obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
    if (binder != NULL) {  //传入的new MediaPlayerService(),肯定不位空
        /***  localBinder() 需要注意一下,首先这里binder是MediaPlayerService是BnMediaPlayerService的子类,
        class MediaPlayerService : public BnMediaPlayerService ==>
        class BnMediaPlayerService: public BnInterface<IMediaPlayerService> ==>
        class BnInterface : public INTERFACE, public BBinder ==>
        所以在BBinder类中找到localBinder() 方法 ==>
        BBinder* BBinder::localBinder(){
            return this;
        }
        最终 IBinder *local = binder->localBinder()也就是我们new的MediaPlayerService();
         ***/
        IBinder *local = binder->localBinder();
        if (!local) { 
            BpBinder *proxy = binder->remoteBinder();
            if (proxy == NULL) {
                ALOGE("null proxy");
            }
            const int32_t handle = proxy ? proxy->handle() : 0;
            obj.type = BINDER_TYPE_HANDLE;
            obj.binder = 0; 
            obj.handle = handle;
            obj.cookie = 0;
        } else {  走的是这个分支,obj这个对象很重要,其中的obj.binder 是弱应用,obj.cookie 是强引用
            obj.type = BINDER_TYPE_BINDER;
            obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
            obj.cookie = reinterpret_cast<uintptr_t>(local);
        }
    } else {
        obj.type = BINDER_TYPE_BINDER;
        obj.binder = 0;
        obj.cookie = 0;
    }
    return finish_flatten_binder(binder, obj, out);
}

3.3 BpBinder.cpp中transact()方法:

status_t BpBinder::transact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    // Once a binder has died, it will never come back to life.
    if (mAlive) {
         // 调用了IPCThreadState的transact()方法;见3.5
        status_t status = IPCThreadState::self()->transact(  //3.4
            mHandle, code, data, reply, flags);
        if (status == DEAD_OBJECT) mAlive = 0;
        return status;
    }

    return DEAD_OBJECT;
}

3.4 IPCThreadState::self()

IPCThreadState* IPCThreadState::self()
{
    if (gHaveTLS) {  //第一次进入是gHaveTLS是false;
restart:
        const pthread_key_t k = gTLS;   // 每个线程只要一个 pthread_key_t = gTLS 对象,类似于ThreadLocal;
        IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
        if (st) return st;
        return new IPCThreadState;
    }    
    if (gShutdown) return NULL; 
    pthread_mutex_lock(&gTLSMutex); 
    if (!gHaveTLS) {
        if (pthread_key_create(&gTLS, threadDestructor) != 0) {
            pthread_mutex_unlock(&gTLSMutex);
            return NULL;
        }
        gHaveTLS = true;
    }
    pthread_mutex_unlock(&gTLSMutex);
    goto restart;
}

3.5 IPCThreadState的transact(mHandle, code, data, reply, flags)方法

//关键性代码
status_t IPCThreadState::transact(int32_t handle, uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags){

    if (err == NO_ERROR) {
        LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
            (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
        err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);  //见3.6
    }
      
    if ((flags & TF_ONE_WAY) == 0) {
        if (reply) {
            err = waitForResponse(reply);
        } else {    //进入的是这个分支
            Parcel fakeReply;
            err = waitForResponse(&fakeReply); //见3.7
        }    
    return err;
}

3.6 IPCThreadState::writeTransactionData():把数据写入out中,具体写入的数据就是3.1中的内容。
data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
data.writeString16(name);
data.writeStrongBinder(service); //这里的service是BBinder
data.writeInt32(allowIsolated ? 1 : 0);

status_t IPCThreadState::writeTransactionData(int32_t cmd, uint32_t binderFlags,
    int32_t handle, uint32_t code, const Parcel& data, status_t* statusBuffer){
    binder_transaction_data tr;

    tr.target.ptr = 0; /* Don't pass uninitialized stack data to a remote process */
    tr.target.handle = handle;  //handle的值是0  
    tr.code = code;//code的值是3.1中传入的ADD_SERVICE_TRANSACTION  
    tr.flags = binderFlags;
    tr.cookie = 0;
    tr.sender_pid = 0;
    tr.sender_euid = 0;
    
    const status_t err = data.errorCheck();
    if (err == NO_ERROR) {  //进入此分支  
        //data的大小
        tr.data_size = data.ipcDataSize();  
        //data数据
        tr.data.ptr.buffer = data.ipcData();   
        tr.offsets_size = data.ipcObjectsCount()*sizeof(binder_size_t);
        tr.data.ptr.offsets = data.ipcObjects();
    } else if (statusBuffer) {
       //...不进入此分支
    } else {
        return (mLastError = err);
    }
    //把数据写入out中,其中cmd是3.5中传入的BC_TRANSACTION
    mOut.writeInt32(cmd);
    mOut.write(&tr, sizeof(tr));
    
    return NO_ERROR;
}

3.7 IPCThreadState中:

status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult){
    int32_t cmd;
    int32_t err;
    while (1) {
        if ((err=talkWithDriver()) < NO_ERROR) break;      
        cmd = mIn.readInt32();        
        switch (cmd) {
        //...                 
        }
    }
    return err;
}

(1) IPCThreadState中d talkWithDriver()方法:精简代码

status_t IPCThreadState::talkWithDriver(bool doReceive)
{
    binder_write_read bwr;
    const bool needRead = mIn.dataPosition() >= mIn.dataSize();
    const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;
    
    bwr.write_size = outAvail;
    bwr.write_buffer = (uintptr_t)mOut.data();

    //接受数据缓冲区填充,如果以后收到的数据,就直接在mIn中
    if (doReceive && needRead) {
        bwr.read_size = mIn.dataCapacity(); //256
        bwr.read_buffer = (uintptr_t)mIn.data();  //mIn.data
    } else {
        bwr.read_size = 0;
        bwr.read_buffer = 0;
    }
       
    // Return immediately if there is nothing to do.
    if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;

    bwr.write_consumed = 0;
    bwr.read_consumed = 0;
    status_t err;
    do {
        //调用驱动层的binder_ioctl()方法
        if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
            err = NO_ERROR;
        else
            err = -errno;      
    } while (err == -EINTR);                
    return err;
}
最终调用了binder_ioctl(),交给驱动去处理。
Media服务的添加.png

相关文章

网友评论

    本文标题:framework 学习笔记5. Media服务的添加过程

    本文链接:https://www.haomeiwen.com/subject/lvhliktx.html