Android GUI系统之SurfaceFlinger(02)应用端分析1-获取Surface

该系列文章总纲链接:Android GUI系统之SurfaceFlinger 系列文章目录


本章关键点总结 & 说明:

Android GUI系统之SurfaceFlinger(02)应用端分析1-获取Surface_第1张图片

本章节思维导图如上。主要讲述了surafce测试程序 demo的 2步,获取SurfaceFlinger的客户端,进而获取 SurfaceControl,再获得Surface的过程。


关键源码说明

该部分代码是在上一章节中 Surface测试程序源码的精简版,保存了最关键的流程,如下所示:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace android;

int main(int argc, char** argv)
{
    //...
    //1 创建surfaceflinger的客户端
    sp client = new SurfaceComposerClient();
    
    //2 获取surface
    sp surfaceControl = client->createSurface(String8("resize"),
            160, 240, PIXEL_FORMAT_RGB_565, 0);
    sp surface = surfaceControl->getSurface();

    //设置layer,layer值越大,显示层越靠前
    SurfaceComposerClient::openGlobalTransaction();
    surfaceControl->setLayer(100000);
    SurfaceComposerClient::closeGlobalTransaction();

    //3 获取buffer->锁定buffer->写入buffer->解锁并提交buffer 
    //这里主要关注:申请Buff 和 提交Buff
    ANativeWindow_Buffer outBuffer;
    surface->lock(&outBuffer, NULL);
    ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
    android_memset16((uint16_t*)outBuffer.bits, 0xF800, bpr*outBuffer.height);
    surface->unlockAndPost();
    //...
    
    return 0;
}

主要的步骤为:

  1. 获取SurfaceFlinger(后简称SF)的客户端,通过SF的客户端 获取 SurfaceControl,进而获得Surface
  2. 通过SurfaceControl 设置 Layer层数值(忽略),通过Surface获取Buffer,锁定Buffer并写入Buffer
  3. 最后提交Buffer

本章节主要关注 第1步和第2步, 获取SF的客户端,进而获取 SurfaceControl,再获得Surface的过程。

1 获取SF客户端

我们从下面源码 开始分析:

sp client = new SurfaceComposerClient();

分析SurafceComposerClient,代码如下:

SurfaceComposerClient::SurfaceComposerClient()
    : mStatus(NO_INIT), mComposer(Composer::getInstance())
{
}

主要是初始化了mStatus和mComposer,同时留意下关键的onFirstRef函数,代码如下:

void SurfaceComposerClient::onFirstRef() {
    //获取SF 服务的客户端
    sp sm(ComposerService::getComposerService());
    if (sm != 0) {
        //通过 SF服务的createConnection得到
        //一个client对象(ISurfaceComposerClient类型)
        sp conn = sm->createConnection();
        if (conn != 0) {
            mClient = conn;
            mStatus = NO_ERROR;
        }
    }
}

这里首先获取SF服务,通过访问 SF服务的createConnection方法 获得 client(ISurfaceComposerClient类型,实际上是对应一个APP)对象。代码如下:

sp SurfaceFlinger::createConnection()
{
    sp bclient;
    sp client(new Client(this));
    status_t err = client->initCheck();
    if (err == NO_ERROR) {
        bclient = client;
    }
    return bclient;
}

这里主要是创建了一个client并返回给上一层的conn。(这里整个分析过程中 忽略了 Binder通信部分的分析,Binder通信部分详见系列文章链接:专题分纲目录 android 系统核心机制 binder,这里最后给出一张 该部分的Binder通信架构的UML图,如下所示:

Android GUI系统之SurfaceFlinger(02)应用端分析1-获取Surface_第2张图片

2 获取Surface

我们首先是通过获取SF的客户端,进而获取 SurfaceControl,通过SurfaceControl再获得Surface,所以我们先分析 获取 SurfaceControl的流程,之后分析 获取Surface的流程。关键代码如下:

    sp surfaceControl = client->createSurface(String8("resize"),
            160, 240, PIXEL_FORMAT_RGB_565, 0);
    sp surface = surfaceControl->getSurface();

2.1 获取 SurfaceControl

这里关注 上面代码中的第一句,createSurface的实现代码如下:

sp SurfaceComposerClient::createSurface(
        const String8& name,
        uint32_t w,
        uint32_t h,
        PixelFormat format,
        uint32_t flags)
{
    sp sur;
    if (mStatus == NO_ERROR) {
        sp handle;
        sp gbp;
        status_t err = mClient->createSurface(name, w, h, format, flags,
                &handle, &gbp);
        ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
        if (err == NO_ERROR) {
            sur = new SurfaceControl(this, handle, gbp);
        }
    }
    return sur;
}

这里的mClient->createSurface方法 最后调用了Client类的createSurface(这个分析过程中 忽略了 Binder通信部分的分析,Binder通信部分详见系列文章链接:专题分纲目录 android 系统核心机制 binder,相关代码如下:

status_t Client::createSurface(
        const String8& name,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp* handle,
        sp* gbp)
{
    class MessageCreateLayer : public MessageBase {
        SurfaceFlinger* flinger;
        Client* client;
        sp* handle;
        sp* gbp;
        status_t result;
        const String8& name;
        uint32_t w, h;
        PixelFormat format;
        uint32_t flags;
    public:
        MessageCreateLayer(SurfaceFlinger* flinger,
                const String8& name, Client* client,
                uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
                sp* handle,
                sp* gbp)
            : flinger(flinger), client(client),
              handle(handle), gbp(gbp),
              name(name), w(w), h(h), format(format), flags(flags) {
        }
        status_t getResult() const { return result; }
        virtual bool handler() {
            //通过SF 创建Layer
            result = flinger->createLayer(name, client, w, h, format, flags,
                    handle, gbp);
            return true;
        }
    };

    sp msg = new MessageCreateLayer(mFlinger.get(),
            name, this, w, h, format, flags, handle, gbp);
    mFlinger->postMessageSync(msg);
    return static_cast( msg.get() )->getResult();
}

这里主要是 通过handler Message机制发送消息,最后通过 SF 创建了一个Layer,createLayer的代码如下:

status_t SurfaceFlinger::createLayer(
        const String8& name,
        const sp& client,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp* handle, sp* gbp)
{
    if (int32_t(w|h) < 0) {
        return BAD_VALUE;
    }
    status_t result = NO_ERROR;
    sp layer;

    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
        case ISurfaceComposerClient::eFXSurfaceNormal:
            result = createNormalLayer(client,
                    name, w, h, flags, format,
                    handle, gbp, &layer);
            break;
        case ISurfaceComposerClient::eFXSurfaceDim:
            result = createDimLayer(client,
                    name, w, h, flags,
                    handle, gbp, &layer);
            break;
        default:
            result = BAD_VALUE;
            break;
    }

    if (result == NO_ERROR) {
        addClientLayer(client, *handle, *gbp, layer);
        setTransactionFlags(eTransactionNeeded);
    }
    return result;
}

同时创建Layer时会有两个分支,是用 createNormalLayer 创建一般的Layer 还是用createDimLayer创建一个DimLayer,最终都会对handle 和 gbp进行赋值,两段代码如下:

status_t SurfaceFlinger::createNormalLayer(const sp& client,
        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
        sp* handle, sp* gbp, sp* outLayer)
{
    // initialize the surfaces
    switch (format) {
    case PIXEL_FORMAT_TRANSPARENT:
    case PIXEL_FORMAT_TRANSLUCENT:
        format = PIXEL_FORMAT_RGBA_8888;
        break;
    case PIXEL_FORMAT_OPAQUE:
        format = PIXEL_FORMAT_RGBX_8888;
        break;
    }

    *outLayer = new Layer(this, client, name, w, h, flags);
    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
    if (err == NO_ERROR) {
        *handle = (*outLayer)->getHandle();
        *gbp = (*outLayer)->getProducer();
    }

    return err;
}

status_t SurfaceFlinger::createDimLayer(const sp& client,
        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
        sp* handle, sp* gbp, sp* outLayer)
{
    *outLayer = new LayerDim(this, client, name, w, h, flags);
    *handle = (*outLayer)->getHandle();
    *gbp = (*outLayer)->getProducer();
    return NO_ERROR;
}

两者都有 这段代码:

    *handle = (*outLayer)->getHandle();
    *gbp = (*outLayer)->getProducer();

即 对 handle 和gbp(后面会详细分析)进行赋值,最后 把这两个值传递给 新创建的SurfaceControl,之后返回。即 每一个Client(对应APP)的SurfaceControl 都对应一个Layer。同时 上面的代码中 LayerDim也是继承Layer的,因此 创建Layer到底做什么?我们要详细分析下Layer才知道。

2.2 创建的Layer分析

Layer类的构造函数如下:

Layer::Layer(SurfaceFlinger* flinger, const sp& client,
        const String8& name, uint32_t w, uint32_t h, uint32_t flags)
    :   contentDirty(false),
        //...
        mClientRef(client),
        mPotentialCursor(false)
{
    mCurrentCrop.makeInvalid();
    mFlinger->getRenderEngine().genTextures(1, &mTextureName);
    mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);

    uint32_t layerFlags = 0;
    if (flags & ISurfaceComposerClient::eHidden)
        layerFlags |= layer_state_t::eLayerHidden;
    if (flags & ISurfaceComposerClient::eOpaque)
        layerFlags |= layer_state_t::eLayerOpaque;

    if (flags & ISurfaceComposerClient::eNonPremultiplied)
        mPremultipliedAlpha = false;

    mName = name;

    mCurrentState.active.w = w;
    //...
    mCurrentState.requested = mCurrentState.active;

    // drawing state & current state are identical
    mDrawingState = mCurrentState;

    nsecs_t displayPeriod =
            flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
    mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
}

可以看到 以上主要是 对 一些变量的 初始化,暂且忽略,再接着看关键方法onFirstRef,代码如下:

void Layer::onFirstRef() {
    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
    sp producer;
    sp consumer;
    BufferQueue::createBufferQueue(&producer, &consumer);
    mProducer = new MonitoredProducer(producer, mFlinger);
    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
    mSurfaceFlingerConsumer->setContentsChangedListener(this);
    mSurfaceFlingerConsumer->setName(mName);

#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
#warning "disabling triple buffering"
    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
#else
    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
#endif

    const sp hw(mFlinger->getDefaultDisplayDevice());
    updateTransformHint(hw);
}

2.2.1 createBufferQueue方法

这里关注BufferQueue的createBufferQueue方法,代码如下:

void BufferQueue::createBufferQueue(sp* outProducer,
        sp* outConsumer,
        const sp& allocator) {
    sp core(new BufferQueueCore(allocator));
    sp producer(new BufferQueueProducer(core));
    sp consumer(new BufferQueueConsumer(core));
    *outProducer = producer;
    *outConsumer = consumer;
}

可以看到,每一个Layer都有一个生产者producer 和消费者consumer并指向同一个BufferQueueCore,BufferQueueCore中有一个关键的成员变量 BufferQueueDefs::SlotsType mSlots;SlotsType类型是一个数量为64的数组。即 生产者producer 和消费者consumer最终指向的同一个核心数组 mSlots(一个64元素的数组)。

2.2.2 MonitoredProducer类分析

MonitoredProducer(producer, mFlinger)中 producer 和SF的关系 主要是在析构时 SF 将producer从mGraphicBufferProducerList (gbp链表)中移除,对应代码如下:

//构造函数
MonitoredProducer::MonitoredProducer(const sp& producer,
        const sp& flinger) :
    mProducer(producer),
    mFlinger(flinger) {}
//析构函数
MonitoredProducer::~MonitoredProducer() {
    class MessageCleanUpList : public MessageBase {
    public:
        MessageCleanUpList(const sp& flinger,
                const wp& producer)
            : mFlinger(flinger), mProducer(producer) {}
        virtual ~MessageCleanUpList() {}
        virtual bool handler() {
            Mutex::Autolock _l(mFlinger->mStateLock);
            mFlinger->mGraphicBufferProducerList.remove(mProducer);
            return true;
        }
    private:
        sp mFlinger;
        wp mProducer;
    };

    mFlinger->postMessageAsync(new MessageCleanUpList(mFlinger, asBinder()));
}

2.3 获取Surface

这里关注 上面代码中的第二句,surfaceControl->getSurface()的实现代码如下:

sp SurfaceControl::getSurface() const
{
    Mutex::Autolock _l(mLock);
    if (mSurfaceData == 0) {
        // This surface is always consumed by SurfaceFlinger, so the
        // producerControlledByApp value doesn't matter; using false.
        //这里的mGraphicBufferProducer就是之前传递进来的gbp
        mSurfaceData = new Surface(mGraphicBufferProducer, false);
    }
    return mSurfaceData;
}

这里创建了一个新的Surface并把gbp参数传递给Surface,最后返回。

2.4 总结

APP对应一个client,一个SurfaceControl对应一个Layer,gbp(BpGraphicBufferProducer)对应 Layer中的mProducer(BnGraphicBufferProducer),它们均遵守同一个接口IGraphicBufferProducer,相关类的关系如下所示:

Android GUI系统之SurfaceFlinger(02)应用端分析1-获取Surface_第3张图片

 

 

 

 

 

 

 

你可能感兴趣的:(显示子系统,android)