必威体育Betway必威体育官网
当前位置:首页 > IT技术

SurfaceFlinger

时间:2019-10-18 09:14:31来源:IT技术作者:seo实验室小编阅读:75次「手机版」
 

surfaceflinger

surfaceflinger的消息处理机制

SurfaceFlinger类依赖于Android的异步消息处理机制,包含了一个messagequeue对象(消息队列)用于处理各种异步消息,在onFirstRef()中对消息队列进行了初始化:

mutable MessageQueue mEventQueue;//thread safe
SurfaceFlinger::onFirstRef()
{
    mEventQueue.init(this);
}

首先分析一下MessageQueue的实现,在MessageQueue.cpp文件中:

void MessageQueue::init(const sp<SurfaceFlinger>& flinger)
{
    mFlinger = flinger;//保存MessageQueue的拥有者SurfaceFlinger
    mLooper = new Looper(true);//创建Looper对象
    mhandler = new Handler(*this);//创建Handler对象
}

调用Handler::handleMessage()处理invalidate和REFRESH消息,并将其转发给SurfaceFlinger进行处理,调用onmessagereceived():

void MessageQueue::Handler::handleMessage(const Message& message) {
    switch (message.what) {
        case INVALIDATE:
            android_atomic_and(~eventMaskInvalidate, &mEventMask);
            mQueue.mFlinger->onMessageReceived(message.what);
            break;
        case REFRESH:
            android_atomic_and(~eventMaskRefresh, &mEventMask);
            mQueue.mFlinger->onMessageReceived(message.what);
            break;
    }   
}

接下来看一下SurfaceFlinger对消息的处理:

void SurfaceFlinger::onMessageReceived(int32_t what) {
    ATRACE_CALL();
    switch (what) {
        case MessageQueue::INVALIDATE: {
            bool refreshneeded = handleMessagetransaction();
            refreshNeeded |= handleMessageInvalidate();
            refreshNeeded |= mRepaintEverything;
            if (refreshNeeded) {
                // signal a refresh if a transaction modified the window state,
                // a new buffer was latched, or if HWC has requested a full
                // repaint
                signalRefresh();
            }
            break;
        }
        case MessageQueue::REFRESH: {
            handleMessageRefresh();
            break;
        }
    }    
}

SurfaceFlinger处理的消息分为两种:

1. INVALIDATE消息:用于处理Layer或者display属性的变化以及Layer对应buffer的更新;
    (1) Layer或者Display属性的更新通过调用handleMessageTransaction()处理;
    (2) buffer的更新通过调用handleMessageInvalidate()处理;
2. REFRESH消息:表示SurfaceFlinger需要进行一次合成操作(Refresh),通过handleMessageRefresh()实现;主要有三种情况,
    (1) Layer属性的变化导致window state发生变化;
    (2) Layer有新的buffer到来;
    (3) HWC请求进行一次repaint.
    如果这三种情况之一发生,则置refreshNeeded为true,调用signalRefresh()发出MessageQueue::REFRESH消息;
一、handleMessageTransaction()
bool SurfaceFlinger::handleMessageTransaction() {
    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
    if (transactionFlags) {
        handleTransaction(transactionFlags);
        return true;
    }    
    return false;
}

函数首先检测是否有transactionFlags被设置,如果是,则调用handleTransaction()来处理属性的变化:

void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
{
    ATRACE_CALL();

    // here we keep a copy of the drawing state (that is the state that's
    // going to be overwritten by handleTransactionLocked()) outside of
    // mStateLock so that the side-effects of the State assignment
    // don't hAPPen with mStateLock held (which can cause deadlocks).
    State drawingState(mDrawingState);

    mutex::Autolock _l(mStateLock);//加锁保证mCurrentState不会再变化,直到这次transaction结束.
    const nsecs_t now = systemTime();
    mDebugInTransaction = now; 

    transactionFlags = getTransactionFlags(eTransactionMask);
    handleTransactionLocked(transactionFlags);//mCurrentState-->mDrawingState

    mLastTransactionTime = systemTime() - now; 
    mDebugInTransaction = 0; 
    invalidateHwcGeometry();
    // here the transaction has been committed
}

下面重点分析handleTransactionLocked(),这是handleMessageTransaction()的核心,主要处理以下几个方面的transaction:

1. Layer属性的变化;
2. Layer的增加和减少;
3. Display属性的变化;
4. Display的增加和减少;

(1)Layer属性的变化

void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
{
    const Layervector& currentlayers(mCurrentState.layersSortedByZ);
    const size_t count = currentLayers.size();

    // Notify all layers of available frames
    for (size_t i = 0; i < count; ++i) {
        currentLayers[i]->notifyAvailableFrames();
    }    

    /*   
     * Traversal of the children
     * (perform the transaction for each of them if needed)
     */

    if (transactionFlags & eTraversalNeeded) {
        for (size_t i=0 ; i<count ; i++) {
            const sp<Layer>& layer(currentLayers[i]);
            //Layer如果被设置eTransactionNeeded标志位表示这个Layer的属性发生了变化,需要做transaction.
            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
            if (!trFlags) continue;

            const uint32_t flags = layer->doTransaction(0);//对Layer做Transaction.
            if (flags & Layer::eVisibleRegion)
                mVisibleRegionsDirty = true;
        }
    }

    ...//Other Code.
}

这部分代码主要用于处理Layer属性的变化,只要Layer设置了eTransactionNeeded标志位,则表示这个Layer需要做Transaction,那么就需要调用一次doTransaction(),另一方面,该函数的返回值用于判断这个Layer的visible Region是否发生变化,如果发生变化则设置eVisibleRegion,表示整个Display的mVisibleRegionsDirty=true. 分析一下Layer::doTransaction()方法:

uint32_t Layer::doTransaction(uint32_t flags) {
    ATRACE_CALL();

    pushPendingState();
    Layer::State c = getCurrentState();//Layer当前的State,可能包含了还没有生效的属性.
    if (!applyPendingStates(&c)) {
        return 0;
    }    

    const Layer::State& s(getDrawingState());//Layer上次绘图的State
    const bool sizeChanged = (c.requested.w != s.requested.w) || (c.requested.h != s.requested.h);

    if (sizeChanged) {
        ...//Log
        //设置Buffer为新的大小,从此处开始,如果客户端dequeueBuffer()就会得到新的大小的buffer.
        mSurfaceFlingerconsumer->setDefaultBufferSize(
                c.requested.w, c.requested.h);
    }    

    const bool resizePending = (c.requested.w != c.active.w) || (c.requested.h != c.active.h);
    if (!isFixedSize()) {
        if (resizePending && mSidebandStream == NULL) {
            //不是立即进行resize,而是等到dequeue出的buffer大小已经发生变化了再resize. 
            flags |= eDontUpdateGeometryState;
        }
    }

    //这段代码的核心意图在于修改mCurrentState.active=mCurrent.requested. 因为c是一份拷贝,所以也要修改.
    if (flags & eDontUpdateGeometryState)  {
    } else {
        Layer::State& editCurrentState(getCurrentState());
        if (mFreezePositionUpdates) {
            float tx = c.active.transform.tx();
            float ty = c.active.transform.ty();
            c.active = c.requested;
            c.active.transform.set(tx, ty);
            editCurrentState.active = c.active;
        } else {
            editCurrentState.active = editCurrentState.requested;
            c.active = c.requested;//修改active等于requested.
        }
    }

    //如果active区域发生变化说明Layer的可见区域发生变化,设置eVisibleRegion标志位.
    if (s.active != c.active) {
        // invalidate and recompute the visible regions if needed
        flags |= Layer::eVisibleRegion;
    }

    //sequence表示Layer属性变化的次数,如果不相等,说明Layer的属性又发生变化了,设置eVisibleRegion标志位.
    if (c.sequence != s.sequence) {
        // invalidate and recompute the visible regions if needed
        flags |= eVisibleRegion;
        this->contentDirty = true;

        // we may use linear filtering, if the matrix scales us
        const uint8_t type = c.active.transform.getType();
        mNeedsFiltering = (!c.active.transform.preserveRects() ||
                (type >= Transform::SCALE));
    }

    // If the layer is hidden, signal and clear out all local sync points so
    // that transactions for layers depending on this layer's frames becoming
    // visible are not blocked
    if (c.flags & layer_state_t::eLayerHidden) {
        Mutex::Autolock lock(mLocalSyncPointMutex);
        for (auto& point : mLocalSyncPoints) {
            point->setFrameAvailable();
        }
        mLocalSyncPoints.clear();
    }

    // Commit the transaction
    commitTransaction(c);//将mCurrentState赋值给mDrawingState,完成Layer属性变化的处理.
    return flags;
}

至此,handleTransactionLocked()就完成了Layer属性变化的处理。同时将Layer大小的变化同步到buffer中。

(2) Layer的增加和减少

/*   
 * Perform our own transaction if needed
 */
const LayerVector& layers(mDrawingState.layersSortedByZ);
if (currentLayers.size() > layers.size()) {
    // layers have been added
    mVisibleRegionsDirty = true; //Layer增加了,需要设置mVisibleRegionsDirty以重新计算各Layer的可见区域。
}    

// some layers might have been removed, so we need to update the regions they're exposing.
if (mLayersRemoved) {
    mLayersRemoved = false;
    mVisibleRegionsDirty = true;
    const size_t count = layers.size();
    for (size_t i=0 ; i<count ; i++) {
        const sp<Layer>& layer(layers[i]);
        if (currentLayers.indexof(layer) < 0) { 
            // this layer is not visible anymore
            // TODO: we could traverse the tree from front to back and
            //       compute the actual visible region
            // TODO: we could cache the transformed region
            const Layer::State& s(layer->getDrawingState());
            Region visibleReg = s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
            invalidateLayerStack(s.layerStack, visibleReg);
        }
    }
}    
二、handleMessageInvalidate()
bool SurfaceFlinger::handleMessageInvalidate() {
    ATRACE_CALL();
    return handlePageFlip();
}
三、handleMessageRefresh()
void SurfaceFlinger::handleMessageRefresh() {
    ATRACE_CALL();

    nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);

    precomposition();
    rebuildLayerStacks();
    setUpHWcomposer();
    doDebugFlashRegions();
    doComposition();
    postComposition(refreshStartTime);
}

3.1 preComposition()

void SurfaceFlinger::preComposition()
{
    bool needExtraInvalidate = false;
    const LayerVector& layers(mDrawingState.layersSortedByZ);//获取所有参与显示的Layer.
    const size_t count = layers.size();
    for (size_t i=0 ; i<count ; i++) { //循环处理所有的Layer,判断是否需要ExtralInvalidate.
        if (layers[i]->onPreComposition()) { 
            needExtraInvalidate = true;
        }
    }
    if (needExtraInvalidate) {
        signalLayerUpdate();
    }
}

下面简要介绍一下这部分代码的功能,主要包括两个方面:

1. 通过mDrawingState获取所有参与显示的Layer,这些Layer是按照z轴排序的,即layersSortedByZ。
2. 对所有的Layer调用其onPreComposition()检查是否需要ExtralInvalidate,如果需要就调用一次signalLayerUpdate().

首先分析一下mDrawingState变量:

(1) mDrawingState: 表示上一帧所使用的各个Layer的绘制状态,是已经生效了的。
(2) mCurrentState,表示还没有生效的状态。Layer::setXXX()方法中会修改mCurrentState,其中保存了App/客户端请求设置的属性;
(3) 在Layer::doTransaction()函数中会处理Layer的属性的变化,并将mCurrentState赋值给mDrawingState,完成commit的过程;
(4) 由于doTransaction()是在handleTransaction()中调用的,发生在preComposition()之前,因此此处的mDrawingState就是最新的Layer的状态。

在创建Layer的时候会将Layer放到mCurrentState的layersSortedByZ向量中:

status_t SurfaceFlinger::createLayer(
        const String8& name,
        const sp<Client>& client,
        uint32_t w, uint32_t h, Pixelformat format, uint32_t flags,
        sp<IBinder>* handle, sp<IGraphicBufferproducer>* gbp) 
{
    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
    if (int32_t(w|h) < 0) { 
        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
                int(w), int(h));
        return BAD_VALUE;
    }    

    status_t result = NO_ERROR;

    sp<Layer> layer;

    //1. 根据Surface的类型创建Normal layer或者Dim 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) {
        return result;
    }

    result = addClientLayer(client, *handle, *gbp, layer);//2. 将创建的Layer加入到mCurrentState中.
    if (result != NO_ERROR) {
        return result;
    }

    setTransactionFlags(eTransactionNeeded);//3. 表示需要处理Layer属性的变化.
    return result;
}

根据指定的name, w,h, format等属性创建了Layer以后会调用addClientLayer()将该Layer加入到mCurrentState中保存:

status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
        const sp<IBinder>& handle,
        const sp<IGraphicBufferProducer>& gbc,
        const sp<Layer>& lbc)
{
    // add this layer to the current state list
    {
        Mutex::Autolock _l(mStateLock);
        if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
            return NO_MEMORY;
        }
        mCurrentState.layersSortedByZ.add(lbc);//将Layer加入到list中保存.
        mGraphicBufferProducerList.add(IInterface::asBinder(gbc));//保存Layer对应的Producer.
    }

    // attach this layer to the client
    client->attachLayer(handle, lbc);//建立layer与client之间的关联.layer是服务器端的概念.

    return NO_ERROR;
}
  1. needExtraInvalidate的含义:

先来看一下Layer::onPreComposition():

bool Layer::onPreComposition() {
    mRefreshPending = false;
    return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
}

这个函数主要检查当前Layer是否还有QueuedFrames. 如果有,返回true. 再回到preComposition()中,该函数循环检查所有的Layer,如果有某个Layer还有QueuedFrames,那么就设置needExtraInvalidate等于true,紧接着进行一次signalLayerUpdate()操作。

void SurfaceFlinger::signalLayerUpdate() {
    mEventQueue.invalidate();//实际上是执行一次Invalidate操作.
}

前面已经分析过,signalLayerUpdate()实际上是让SurfaceFlinger检查并更新一次各个Layer的属性以及Buffer的内容。这样就在合成之前,保证各个Layer的属性和buffer的内容都是最新的。

3.2 rebuildLayerStacks()

void SurfaceFlinger::rebuildLayerStacks() {
    // rebuild the visible layer list per screen
    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
        ATRACE_CALL();
        mVisibleRegionsDirty = false;
        invalidateHwcGeometry();

        const LayerVector& layers(mDrawingState.layersSortedByZ);//获取当前参与合成的所有的Layer.
        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) { //对所有的display循环处理.
            Region opaqueRegion;
            Region dirtyRegion;
            Vector< sp<Layer> > layersSortedByZ;
            const sp<DisplayDevice>& hw(mDisplays[dpy]);
            const Transform& tr(hw->getTransform());//表示屏幕的旋转、翻转等坐标变换.是在屏幕坐标系的基础上进行的.
            const Rect bounds(hw->getBounds());
            if (hw->isDisplayOn()) {
                //1. 计算各个layer在当前display上的visible region.
                SurfaceFlinger::computeVisibleRegions(layers, hw->getLayerStack(), dirtyRegion, opaqueRegion);
                //2. 循环处理所有layer,判断layer是否是最终参与显示的.
                const size_t count = layers.size();
                for (size_t i=0 ; i<count ; i++) {
                    const sp<Layer>& layer(layers[i]);
                    const Layer::State& s(layer->getDrawingState());
                    if (s.layerStack == hw->getLayerStack()) { //每个display都有一个layerstack
                        //在屏幕上的绘制区域.
                        Region drawRegion(tr.transform(layer->visibleNonTransparentRegion));
                        drawRegion.andSelf(bounds);
                        if (!drawRegion.isempty()) {
                            layersSortedByZ.add(layer);//如果非空表示这个Layer要参与显示.
                        }
                    }
                }
            }
            //3. 设置各个display的layer list和脏区域等.
            hw->setVisibleLayersSortedByZ(layersSortedByZ);
            hw->undefinedRegion.set(bounds);
            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
            hw->dirtyRegion.orSelf(dirtyRegion);
        }
    }    
}

这段代码主要是在合成操作之前为每个display设置参与绘图的layer list以及计算各个layer的visible region等,为后续的合成操作做准备. 下面进行简要的解释:

  1. 坐标系:hw->getTrasform()获取的是屏幕的旋转、翻转等坐标变换,是在屏幕坐标系的基础上进行的。一般涉及到的坐标变换为:

    buffer坐标系(纹理坐标系)–>屏幕坐标系–>旋转变换等. 而visibleNonTransparentRegion是定义在屏幕坐标系下的(window manager space),所以需要跟随屏幕进行旋转等变换.

2.computeVisibleRegions(): 计算各个Layer在当前display上的可见区域和脏区域等. 这个函数是SF的核心:

void SurfaceFlinger::computeVisibleRegions(
        const LayerVector& currentLayers, uint32_t layerStack,
        Region& outDirtyRegion, Region& outOpaqueRegion)
{
    ATRACE_CALL();

    Region aboveOpaqueLayers;
    Region aboveCoveredLayers;
    Region dirty;

    outDirtyRegion.clear();

    size_t i = currentLayers.size();//对所有参与合成的Layer进行处理.
    while (i--) {
        const sp<Layer>& layer = currentLayers[i];

        // start with the whole surface at its current location
        const Layer::State& s(layer->getDrawingState());

        // only consider the layers on the given layer stack
        if (s.layerStack != layerStack) //只处理属于指定display的layers.根据layerstack进行标识.
            continue;

        Region opaqueRegion;//Layer的完全不透明的区域.
        Region visibleRegion;//Layer的可见区域,包含了半透明区域,等于Layer的大小减去覆盖在它上面的opaque region.
        Region coveredRegion;//Layer的被覆盖的区域,包含半透明的区域.
        Region transparentRegion;//Layer的完全透明区域.

        // handle hidden surfaces by setting the visible region to empty
        if (CC_LIKELY(layer->isVisible())) {
            const bool translucent = !layer->isOpaque(s);//是否是完全不透明的,即没有透明度
            Rect bounds(s.active.transform.transform(layer->computeBounds()));//变换到屏幕坐标系
            visibleRegion.set(bounds);
            if (!visibleRegion.isEmpty()) {
                // Remove the transparent area from the visible region
                if (translucent) { //标识整个Layer是包含透明度的
                    const Transform tr(s.active.transform);
                    if (tr.preserveRects()) {
                        //将active区域中的透明区域由buffer坐标系变换到屏幕坐标系.
                        transparentRegion = tr.transform(s.activeTransparentRegion);
                    } else {
                        // transformation too complex, can't do the
                        // transparent region optimization.
                        transparentRegion.clear();
                    }
                }

                // compute the opaque region
                const int32_t layerOrientation = s.active.transform.getOrientation();
                if (s.alpha==255 && !translucent &&
                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
                    // the opaque region is the layer's footprint
                    opaqueRegion = visibleRegion;
                }
            }
        }

        // Clip the covered region to the visible region
        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);

        // Update aboveCoveredLayers for next (lower) layer
        aboveCoveredLayers.orSelf(visibleRegion);//当前layer的可见区域是下一层layer的覆盖区域.

        // subtract the opaque region covered by the layers above us
        visibleRegion.subtractSelf(aboveOpaqueLayers);

        // compute this layer's dirty region
        if (layer->contentDirty) {
            // we need to invalidate the whole region
            dirty = visibleRegion;
            // as well, as the old visible region
            dirty.orSelf(layer->visibleRegion);
            layer->contentDirty = false;
        } else {
            /* compute the exposed region:
             *   the exposed region consists of two components:
             *   1) what's VISIBLE now and was COVERED before
             *   2) what's EXPOSED now less what was EXPOSED before
             *
             * note that (1) is conservative, we start with the whole
             * visible region but only keep what used to be covered by
             * something -- which mean it may have been exposed.
             *
             * (2) handles areas that were not covered by anything but got
             * exposed because of a resize.
             */
            const Region newExposed = visibleRegion - coveredRegion;
            const Region oldVisibleRegion = layer->visibleRegion;
            const Region oldCoveredRegion = layer->coveredRegion;
            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
        }
        dirty.subtractSelf(aboveOpaqueLayers);

        // accumulate to the screen dirty region
        outDirtyRegion.orSelf(dirty);

        // Update aboveOpaqueLayers for next (lower) layer
        aboveOpaqueLayers.orSelf(opaqueRegion);//当前layer的不透明区域是下一层layer的aboveOpaqueLayers.

        // Store the visible region in screen space
        layer->setVisibleRegion(visibleRegion);
        layer->setCoveredRegion(coveredRegion);
        layer->setVisibleNonTransparentRegion(visibleRegion.subtract(transparentRegion));
    }

    outOpaqueRegion = aboveOpaqueLayers;
}

3.3 setUpHWComposer()

3.4 doComposition()

3.5 postComposition()

void SurfaceFlinger::postFramebuffer()

{

ATRACE_CALL();

    const nsecs_t now = systemTime();//开始postFramebuffer的时间.
    mDebugInSwapBuffers = now;

    HWComposer& hwc(getHwComposer());
    if (hwc.initCheck() == NO_ERROR) {
        if (!hwc.supportsFramebufferTarget()) {
            // EGL spec says:
            //   "surface must be bound to the calling thread's current context,
            //    for the current rendering API."
            getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
        }
        hwc.commit();
    }

    // make the default display current because the virtualDisplayDevice code cannot
    // deal with dequeueBuffer() being called outside of the composition loop; however
    // the code below can call glFlush() which is allowed (and does in some case) call
    // dequeueBuffer().
    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);

    //设置release fence.
    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
        sp<const DisplayDevice> hw(mDisplays[dpy]);
        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
        //1. 对于GPU compose的layer.如果是pre-1.1版本的Hwc,包含了framebufferTarget,则需要设置framebufferTarget对应的release fence.
        hw->onSwapBuffersCompleted(hwc);
        //2. 对于overlay类型的layer,则需要设置各个Layer背后对应buffer的release fence.
        const size_t count = currentLayers.size();
        int32_t id = hw->getHwcDisplayId();
        if (id >=0 && hwc.initCheck() == NO_ERROR) {
            HWComposer::LayerListIterator cur = hwc.begin(id);
            const HWComposer::LayerListIterator end = hwc.end(id);
            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
                currentLayers[i]->onLayerDisplayed(hw, &*cur);
            }
        } else {
            for (size_t i = 0; i < count; i++) {
                currentLayers[i]->onLayerDisplayed(hw, NULL);
            }
        }
    }

    mLastSwapBufferTime = systemTime() - now;//swap buffer所花费的时间.
    mDebugInSwapBuffers = 0;

    //获取SurfaceFlinger合成的总次数,每隔一定的frame记录一次frame stats.
    uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
    if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
        logFrameStats();
    }
}

总的来说,postFramebuffer()主要完成了三件事情:

1. 调用hwc.commit()进行swap buffer,将合成好的buffer送显;
2. 分两种情况设置buffer的release fence
    2.1 对于OpenGL compose类型的Layer,如果采用pre-1.1版本的Hwc,则设置framebufferTarget的release fence. (第二个Producer-Consumer模型)
    2.2 对于overlay类型的Layer,直接设置对应current buffer的release fence. (第一个Producer-Consumer模型)
3. 根据SurfaceFlinger合成的总次数,每隔一定的frame记录一次frame stats.

onSwapBuffersCompleted()

void DisplayDevice::onSwapBuffersCompleted(HWComposer& hwc) const {
    if (hwc.initCheck() == NO_ERROR) {
        mDisplaySurface->onFrameCommitted();
    }   
}

其中,mDisplaySurface表示这个DisplayDevice用于显示的Surface,是FrameBufferSurface对象.继续看一下onFrameCommitted()函数:

void FramebufferSurface::onFrameCommitted() {
#ifdef USE_HWC2
    if (mHasPendingRelease) {
        sp<Fence> fence = mHwc.getRetireFence(mDisplayType);
        if (fence->isValid()) {
            status_t result = addReleaseFence(mPrevioUSBufferSlot,
                    mpreviousBuffer, fence);
            ALOGE_IF(result != NO_ERROR, "onFrameCommitted: failed to add the"
                    " fence: %s (%d)", strerror(-result), result);
        }
        status_t result = releaseBufferLocked(mPreviousBufferSlot,
                mPreviousBuffer, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
        ALOGE_IF(result != NO_ERROR, "onFrameCommitted: error releasing buffer:"
                " %s (%d)", strerror(-result), result);

        mPreviousBuffer.clear();
        mHasPendingRelease = false;
    }   
#else
    //获取release fence并将其设置到framebufferTarget的mCurrentBuffer对应的release fence.
    sp<Fence> fence = mHwc.getAndResetReleaseFence(mDisplayType);
    if (fence->isValid() &&
            mCurrentBufferSlot != BufferQueue::INVALID_BUFFER_SLOT) {
        status_t err = addReleaseFence(mCurrentBufferSlot,
                mCurrentBuffer, fence);
        ALOGE_IF(err, "setReleaseFenceFd: failed to add the fence: %s (%d)",
                strerror(-err), err);
    }   
#endif
}

首先通过getAndResetReleaseFence()从framebufferTarget(如果有的话)中拿到release fencefd,然后创建一个Fence对象并将其设置为mCurrentBuffer的release fence.

sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
    if (uint32_t(id)>31 || !mallocatedDisplayIDs.hasBit(id))
        return Fence::NO_FENCE;

    int fd = INVALID_OPERATION;
    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
        const DisplayData& disp(mDisplayData[id]);
        if (disp.framebufferTarget) {
            fd = disp.framebufferTarget->releaseFenceFd;//get relase fencefd.
            disp.framebufferTarget->acquireFenceFd = -1;
            disp.framebufferTarget->releaseFenceFd = -1;//reset release fencefd.
        }
    }    
    return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;//创建一个release fence.
}

onLayerDisplayed()

void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
        HWComposer::HWCLayerInterface* layer) {
    if (layer) {
        layer->onDisplayed();
        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
    }    
}

待续.

相关阅读

Android 8.0 SurfaceFlinger

一、SurfaceFlinger编译模块组成 码路径:frameworks/native/services/surfaceflingerSurfaceFlinger二进制分成surfaceflinger(main

浅谈Android之SurfaceFlinger相关介绍(一)

SurfaceFlinger是GUI的核心,以系统服务的形式存在,负责将所有App的图形数据按照Z Order顺序混合并输出到FrameBuffer。根据图中描述

SurfaceFlinger原理(一):SurfaceFlinger的初始化

  SurfaceFlinger是Android的一个native进程,负责将图层进行合成,图层叠加起来就构成了我们看到的界面。合成的方式分为在线合成

分享到:

栏目导航

推荐阅读

热门阅读