初探MeidaPlayer底层实现(三)

前一章提到的native_setup函数中有这么一句

sp<MediaPlayer> mp = new MediaPlayer();

MediaPlayer类的定义在frameworks\av\include\media\mediaplayer.h文件中

MediaPlayer类的实现在frameworks\av\media\libmedia\mediaplayer.cpp文件中

构造函数如下:

MediaPlayer::MediaPlayer()
{
    ALOGV("constructor");
    mListener = NULL;//sp<MediaPlayerListener>
    mCookie = NULL;//void*
    mStreamType = AUDIO_STREAM_MUSIC;//audio_stream_type_t
    mAudioAttributesParcel = NULL;//Parcel*
    mCurrentPosition = -1;//int
    mSeekPosition = -1;//int 
    mCurrentState = MEDIA_PLAYER_IDLE;//media_player_states
    mPrepareSync =false;//bool
    mPrepareStatus = NO_ERROR;//status_t
    mLoop =false;//bool
    mLeftVolume = mRightVolume = 1.0;//float
    mVideoWidth = mVideoHeight = 0;//int
    mLockThreadId = 0;//thread_id_t
    mAudioSessionId = AudioSystem::newAudioUniqueId();//int
    AudioSystem::acquireAudioSessionId(mAudioSessionId, -1);//
    mSendLevel = 0;//float
    mRetransmitEndpointValid =false;//bool
}

再看下前一章提到的setDataSourceAndHeaders函数的一句代码

status_t opStatus =
    mp->setDataSource(
            httpService,
            pathStr,
            headersVector.size() > 0? &headersVector : NULL);
实则调用MediaPlayer.h中的函数,如下

status_t        setDataSource(
        const sp<IMediaHTTPService> &httpService,
        const char *url,
        const KeyedVector<String8, String8> *headers);
实现如下:

httpService:
url:视频网络地址
headers:这里传入的是NULL
status_t MediaPlayer::setDataSource(
        const sp<IMediaHTTPService> &httpService,
        const char *url, const KeyedVector<String8, String8> *headers)
{
    ALOGV("setDataSource(%s)", url);
    status_t err = BAD_VALUE;
    if (url != NULL) {
        const sp<IMediaPlayerService>& service(getMediaPlayerService());
        if (service != 0) {
            sp<IMediaPlayer> player(service->create(this, mAudioSessionId));
            if ((NO_ERROR != doSetRetransmitEndpoint(player)) ||
                (NO_ERROR != player->setDataSource(httpService, url, headers))) {
                player.clear();
            }
            err = attachNewPlayer(player);
        }
    }
    return err;
}

一句一句看

 const sp<IMediaPlayerService>& service(getMediaPlayerService());
上句代码,定义了一个IMediaPlayerService类型的强指针,用getMediaPlayerService返回值进行赋值。getMediaPlayerService()是什么样的函数???

getMediaPlayerService是IMediaDeathNotifier类中的静态函数,如下

注:IMediaDeathNotifier.h在frameworks\av\include\media\IMediaDeathNotifier.h

IMediaDeathNotifier.cpp在frameworks\av\media\libmedia\IMediaDeathNotifier.cpp

class IMediaDeathNotifier: virtual public RefBase
{
	。。。
	static const sp<IMediaPlayerService>& getMediaPlayerService();
	。。。
}

// establish binder interface to MediaPlayerService
/*static*/const sp<IMediaPlayerService>&
IMediaDeathNotifier::getMediaPlayerService()
{
    ALOGV("getMediaPlayerService");
    Mutex::Autolock _l(sServiceLock);
//sMediaPlayerService的定义
//static  sp<IMediaPlayerService>  sMediaPlayerService; 
    if (sMediaPlayerService == 0) {//初值为0,进入
        sp<IServiceManager> sm = defaultServiceManager();//下面分析
        sp<IBinder> binder;
        do {
            binder = sm->getService(String16("media.player"));
            if (binder != 0) {
                break;
            }
            ALOGW("Media player service not published, waiting...");
            usleep(500000); // 0.5 s
        } while (true);

        if (sDeathNotifier == NULL) {
            sDeathNotifier = new DeathNotifier();
        }
        binder->linkToDeath(sDeathNotifier);
        sMediaPlayerService = interface_cast<IMediaPlayerService>(binder);
    }
    ALOGE_IF(sMediaPlayerService == 0, "no media player service!?");
    return sMediaPlayerService;
}

sp<IServiceManager> sm = defaultServiceManager();

注:IServiceManager.h在frameworks\native\include\binder\IServiceManager.h

IServiceManager.cpp在frameworks\native\libs\binder\IServiceManager.cpp

defaultServiceManager函数的定义在IServiceManager类中。

sp<IServiceManager> defaultServiceManager();
sp<IServiceManager> defaultServiceManager()
{
    if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
    
    {//gDefaultServiceManager 初值为NULL
        AutoMutex _l(gDefaultServiceManagerLock);//同步锁
        while (gDefaultServiceManager == NULL) {
            gDefaultServiceManager = interface_cast<IServiceManager>(
                ProcessState::self()->getContextObject(NULL));
            if (gDefaultServiceManager == NULL)
                sleep(1);
        }
    }
    
    return gDefaultServiceManager;
}
gDefaultServiceManager = interface_cast<IServiceManager>(
                ProcessState::self()->getContextObject(NULL));

要理解上面一句代码,先看下IServiceManager类中的内容,类定义如下

class IServiceManager : public IInterface
{
public:
    DECLARE_META_INTERFACE(ServiceManager);
	。。。
}
IServiceManager.cpp中的
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");

注:IIterface.h在frameworks\native\include\binder\IInterface.h

IInterface.cpp在frameworks\native\libs\binder\IInterface.cpp

父类IInterface中有如下模板函数

template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
    return INTERFACE::asInterface(obj);
}
将上面的IServiceManager替换INTERFACE,则返回的是IServiceManager::asInterface(obj);  asInterface函数的定义又在哪里???

发现IServiceManager类有两个宏DECLARE_META_INTERFACE和IMPLEMENT_META_INTERFACE,它们的定义都在父类IIterface类中。

#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) {                                              \
             /*queryLocalInterface返回null*/                             \
            intr = static_cast<I##INTERFACE*>(                          \
                obj->queryLocalInterface(                               \
                        I##INTERFACE::descriptor).get());               \
            if (intr == NULL) {                                         \
                 /*此时INTERFACE为IServiceManager
                 这里应该是创建
                 intr=new BpServiceManager(obj);
                 */
                intr = new Bp##INTERFACE(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    I##INTERFACE::I##INTERFACE() { }                                    \
    I##INTERFACE::~I##INTERFACE() { }                                   \

现在再来看IServiceManager中的

DECLARE_META_INTERFACE(ServiceManager);
将ServiceManager替换上述宏中的INTERFACE

#define DECLARE_META_INTERFACE(ServiceManager)			         \
    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();                                          \
接着是
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
将ServiceManager替换上述宏中的INTERFACE
#define IMPLEMENT_META_INTERFACE(ServiceManager, NAME)                       
    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) {                                              \
             /*queryLocalInterface返回null*/                             \
            intr = static_cast<IServiceManager*>(                          \
                obj->queryLocalInterface(                               \
                        IServiceManager::descriptor).get());               \
            if (intr == NULL) {                                         \
                 /*此时INTERFACE为IServiceManager
                 这里应该是创建
                 intr=new BpServiceManager(obj);
                 */
                intr = new BpServiceManager(obj);                          \
            }                                                           \
        }                                                               \
        return intr;                                                    \
    }                                                                   \
    IServiceManager::IServiceManager() { }          			\
    IServiceManager::~IServiceManager() { }                       	\       
这里就找到了上面的IServiceManager::asInterface(obj);然后再看下asInterface返回什么东西???这里首先得弄明白obj的值,需要看前面调用的地方
gDefaultServiceManager = interface_cast<IServiceManager>(
                ProcessState::self()->getContextObject(NULL));
发现obj就是
ProcessState::self()->getContextObject(NULL)
的返回值,这里需要看下ProcessState类。
注:ProcessState.h在frameworks\native\include\binder\ProcessState.h
    ProcessState.cpp在frameworks\native\libs\binder\ProcessState.cpp
class ProcessState : public virtual RefBase
{
public:
    static  sp<ProcessState>    self();
	...
}
先看self的实现
sp<ProcessState> ProcessState::self()
{
    Mutex::Autolock _l(gProcessMutex);//同步锁
    if (gProcess != NULL) {//初始为null
        return gProcess;
    }
    gProcess = new ProcessState;
    return gProcess;
}
很简单就是单例模式,创建了一个ProcessState对象。
然后再看getContextObject
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
    return getStrongProxyForHandle(0);
}
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)//handle=0
{
    sp<IBinder> result;

    AutoMutex _l(mLock);

    handle_entry* e = lookupHandleLocked(handle);

    if (e != NULL) {
        // We need to create a new BpBinder if there isn't currently one, OR we
        // are unable to acquire a weak reference on this current one.  See comment
        // in getWeakProxyForHandle() for more info about this.
        IBinder* b = e->binder;
        if (b == NULL || !e->refs->attemptIncWeak(this)) {
            if (handle == 0) {
                // Special case for context manager...
                // The context manager is the only object for which we create
                // a BpBinder proxy without already holding a reference.
                // Perform a dummy transaction to ensure the context manager
                // is registered before we create the first local reference
                // to it (which will occur when creating the BpBinder).
                // If a local reference is created for the BpBinder when the
                // context manager is not present, the driver will fail to
                // provide a reference to the context manager, but the
                // driver API does not return status.
                //
                // Note that this is not race-free if the context manager
                // dies while this code runs.
                //
                // TODO: add a driver API to wait for context manager, or
                // stop special casing handle 0 for context manager and add
                // a driver API to get a handle to the context manager with
                // proper reference counting.

                Parcel data;
                status_t status = IPCThreadState::self()->transact(
                        0, IBinder::PING_TRANSACTION, data, NULL, 0);
                if (status == DEAD_OBJECT)
                   return NULL;
            }

            b = new BpBinder(handle); 
            e->binder = b;
            if (b) e->refs = b->getWeakRefs();
            result = b;
        } else {
            // This little bit of nastyness is to allow us to add a primary
            // reference to the remote proxy when this team doesn't have one
            // but another team is sending the handle to us.
            result.force_set(b);
            e->refs->decWeak(this);
        }
    }

    return result;
}
一句一句分析 
handle_entry* e = lookupHandleLocked(handle);
handle_entry的定义如下
struct handle_entry {
    IBinder* binder;
    RefBase::weakref_type* refs;
};
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle)
{
    const size_t N=mHandleToObject.size();
    if (N <= (size_t)handle) {
        handle_entry e;
        e.binder = NULL;
        e.refs = NULL;
        status_t err = mHandleToObject.insertAt(e, N, handle+1-N);
        if (err < NO_ERROR) return NULL;
    }
    return &mHandleToObject.editItemAt(handle);
}
未完待续。。。
 
 
 
 
 
 
 
 
 
 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值