Android多媒体之MediaPlayer框架分析

在android系统中,MediaPlayer提供播放音视频的功能,本文打算先简要分析一下MediaPlayer框架。

图一

如图一所示,java framework提供了MediaPlayer类供上层应用使用,java层的MediaPlayer对象对应一个native层的MediaPlayer对象,同时对应一个mediaserver进程中的Client对象,native层的MediaPlayer对象通过IMediaPlayer binder接口调用到mediaserver进程中的Client对象。MediaPlayer的核心功能都是在mediaserver进程中完成的,在应用程序这一端,只是提供接口,逻辑比较简单,就不细说了,IMediaPlayer接口定义如下,主要就是提供设置数据源、设置输出Surface和启停等控制接口。

class IMediaPlayer: public IInterface
{
public:
    DECLARE_META_INTERFACE(MediaPlayer);

    virtual void            disconnect() = 0;

    virtual status_t        setDataSource(const char *url,
                                    const KeyedVector<String8, String8>* headers) = 0;
    virtual status_t        setDataSource(int fd, int64_t offset, int64_t length) = 0;
    virtual status_t        setDataSource(const sp<IStreamSource>& source) = 0;
    virtual status_t        setVideoSurfaceTexture(
                                    const sp<IGraphicBufferProducer>& bufferProducer) = 0;
    virtual status_t        prepareAsync() = 0;
    virtual status_t        start() = 0;
    virtual status_t        stop() = 0;
    virtual status_t        pause() = 0;
    virtual status_t        isPlaying(bool* state) = 0;
    virtual status_t        seekTo(int msec) = 0;
    virtual status_t        getCurrentPosition(int* msec) = 0;
    virtual status_t        getDuration(int* msec) = 0;
    virtual status_t        reset() = 0;
    virtual status_t        setAudioStreamType(audio_stream_type_t type) = 0;
    virtual status_t        setLooping(int loop) = 0;
    virtual status_t        setVolume(float leftVolume, float rightVolume) = 0;
    virtual status_t        setAuxEffectSendLevel(float level) = 0;
    virtual status_t        attachAuxEffect(int effectId) = 0;
    virtual status_t        setParameter(int key, const Parcel& request) = 0;
    virtual status_t        getParameter(int key, Parcel* reply) = 0;
    virtual status_t        setRetransmitEndpoint(const struct sockaddr_in* endpoint) = 0;
    virtual status_t        getRetransmitEndpoint(struct sockaddr_in* endpoint) = 0;
    virtual status_t        setNextPlayer(const sp<IMediaPlayer>& next) = 0;

    // Invoke a generic method on the player by using opaque parcels
    // for the request and reply.
    // @param request Parcel that must start with the media player
    // interface token.
    // @param[out] reply Parcel to hold the reply data. Cannot be null.
    // @return OK if the invocation was made successfully.
    virtual status_t        invoke(const Parcel& request, Parcel *reply) = 0;

    // Set a new metadata filter.
    // @param filter A set of allow and drop rules serialized in a Parcel.
    // @return OK if the invocation was made successfully.
    virtual status_t        setMetadataFilter(const Parcel& filter) = 0;

    // Retrieve a set of metadata.
    // @param update_only Include only the metadata that have changed
    //                    since the last invocation of getMetadata.
    //                    The set is built using the unfiltered
    //                    notifications the native player sent to the
    //                    MediaPlayerService during that period of
    //                    time. If false, all the metadatas are considered.
    // @param apply_filter If true, once the metadata set has been built based
    //                     on the value update_only, the current filter is
    //                     applied.
    // @param[out] metadata On exit contains a set (possibly empty) of metadata.
    //                      Valid only if the call returned OK.
    // @return OK if the invocation was made successfully.
    virtual status_t        getMetadata(bool update_only,
                                        bool apply_filter,
                                        Parcel *metadata) = 0;
};

在mediaserver进程这一端,Client对象会创建一个实现了MediaPlayerInterface接口的播放器对象,这个对象在不同的android版本上有所不同,比如

2.2版本定义如下播放器类型

enum player_type {
    PV_PLAYER = 1,
    SONIVOX_PLAYER = 2,
    VORBIS_PLAYER = 3,
    STAGEFRIGHT_PLAYER = 4,
    TEST_PLAYER = 5,
    APE_PLAYER = 6,
    FLAC_PLAYER = 7
};

具体使用那种播放器类型,是由数据源类型决定的,映射关系如下所示

extmap FILE_EXTS [] =  {
        {".mid", SONIVOX_PLAYER},
        {".midi", SONIVOX_PLAYER},
        {".smf", SONIVOX_PLAYER},
        {".xmf", SONIVOX_PLAYER},
        {".imy", SONIVOX_PLAYER},
        {".rtttl", SONIVOX_PLAYER},
        {".rtx", SONIVOX_PLAYER},
        {".ota", SONIVOX_PLAYER},
        {".ogg", VORBIS_PLAYER},
        {".oga", VORBIS_PLAYER},
        {".ape", APE_PLAYER},
        {".flac", FLAC_PLAYER},
};

每种类型对应的实现如下所示:

switch (playerType) {
#ifndef NO_OPENCORE
        case PV_PLAYER:
            LOGV(" create PVPlayer");
            p = new PVPlayer();
            break;
#endif
        case SONIVOX_PLAYER:
            LOGV(" create MidiFile");
            p = new MidiFile();
            break;
        case VORBIS_PLAYER:
            LOGV(" create VorbisPlayer");
            p = new VorbisPlayer();
            break;
        case APE_PLAYER:
            LOGV(" create ApePlayer");
            p = new ApePlayer();
            break;
        case FLAC_PLAYER:
            LOGV(" create FlacPlayer");
            p = new FlacPlayer();
            break;
#if BUILD_WITH_FULL_STAGEFRIGHT
        case STAGEFRIGHT_PLAYER:
            LOGV(" create StagefrightPlayer");
            p = new StagefrightPlayer;
            break;
#endif
        case TEST_PLAYER:
            LOGV("Create Test Player stub");
            p = new TestPlayerStub();
            break;
    }

4.4版本定义如下播放器类型:

enum player_type {
    PV_PLAYER = 1,
    SONIVOX_PLAYER = 2,
    STAGEFRIGHT_PLAYER = 3,
    NU_PLAYER = 4,
    TEST_PLAYER = 5
}

具体使用那种播放器类型,也是由数据源类型决定的,不过不是采用简单的映射关系,而是采用一种数据源匹配评分机制,如下所示:

#define GET_PLAYER_TYPE_IMPL(a...)                      \
    Mutex::Autolock lock_(&sLock);                      \
                                                        \
    player_type ret = STAGEFRIGHT_PLAYER;               \
    float bestScore = 0.0;                              \
                                                        \
    for (size_t i = 0; i < sFactoryMap.size(); ++i) {   \
                                                        \
        IFactory* v = sFactoryMap.valueAt(i);           \
        float thisScore;                                \
        CHECK(v != NULL);                               \
        thisScore = v->scoreFactory(a, bestScore);      \
        if (thisScore > bestScore) {                    \
            ret = sFactoryMap.keyAt(i);                 \
            bestScore = thisScore;                      \
        }                                               \
    }                                                   \
                                                        \
    if (0.0 == bestScore) {                             \
        ret = getDefaultPlayerType();                   \
    }                                                   \
                                                        \
    return ret;

每种类型提供了一个MediaPlayerFactory对象,实现了scoreFactory方法和createPlayer方法,每种类型对应的MediaPlayerFactory如下所示:

    registerFactory_l(new StagefrightPlayerFactory(), STAGEFRIGHT_PLAYER);
    registerFactory_l(new NuPlayerFactory(), NU_PLAYER);
    registerFactory_l(new SonivoxPlayerFactory(), SONIVOX_PLAYER);
    registerFactory_l(new TestPlayerFactory(), TEST_PLAYER);

以StagefrightPlayerFactory为例,createPlayer创建的是一个StagefrightPlayer对象。

    virtual sp<MediaPlayerBase> createPlayer() {
        ALOGV(" create StagefrightPlayer");
        return new StagefrightPlayer();
    }

6.0版本定义如下播放器类型,虽然保留了数据源匹配评分机制,但是基本上都是使用NU_PLAYER了。

enum player_type {
    NU_PLAYER = 4,
    // Test players are available only in the 'test' and 'eng' builds.
    // The shared library with the test player is passed passed as an
    // argument to the 'test:' url in the setDataSource call.
    TEST_PLAYER = 5,
    DASH_PLAYER = 6,
};

有些芯片厂商也可能提供自己的实现,比如我之前接触过的海思平台的方案,就自己搞了一个HiMediaPlayerManage。

如图一所示,实现了MediaPlayerInterface接口的播放器对象其实只是个简单的代理对象,核心功能都是委托给具体的播放器对象来实现,比如StagefrightPlayer就是委托AwesomePlayer来处理,NuPlayerDriver就是委托NuPlayer来处理。因此要分析实际的播放器流程,主要就是分析AwesomePlayer和NuPlayer业务流程。主要类的关系如下所示,可以看出,就是一个比较典型的代理模式。

图二

扯了这么多,总结起来就是MediaPlayer核心功能是由mediaserver进程中具体的播放器引擎完成的,而播放器引擎在不同的android版本上有很大的变化,从早期的OpenCore到StagefrightPlayer再到最新的NuPlayer,中间也长时间存在共存的情况,比如播放本地文件采用StagefrightPlayer,而播放流媒体则采用NuPlayer,不过最后都统一为NuPlayer了。

好了今天先写到这了,比较简单,没啥实质性内容,后续再抽时间写一下AwesomePlayer和NuPlayer相关内容。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 137,975评论 20赞 590
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 86,968评论 14赞 122
  • 国家电网企业企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 4,682评论 4赞 7
  • 每天三点一线,平平淡淡的生活倒也怡然自得。就像火山爆发前的平静,也是在积聚岩浆喷薄时的力量。现在是在冲刺,尽管没有...
    丹青笔阅读 198评论 0赞 1
  • 咪咪成长记-女妖精变身 早上在送咪咪上学的路上,我试探性的叫;“女妖精”,坐在车后座的咪咪用轻松清脆的声音回答...
    刘慧烨阅读 240评论 0赞 1