Layer visibleRegion的计算过程

涉及到的文件:

frameworks/native/services/surfaceflinger/layer.h

frameworks/native/services/surfaceflinger/layer.cpp

frameworks/native/libs/ui/Transform.cpp

frameworks/native/libs/ui/Transform.h

Layer::State的设置流程

SurfaceControl.setPosition
 -> android_view_SurfaceControl: setPosition
 -> SurfaceComposerClient: nativeSetPosition
 -> SurfaceComposerClient:setPosition
入口为SurfaceControl.Transaction的setPosition
SurfaceControl.java

/**
 * Sets the SurfaceControl to the specified position relative to the parent
 * SurfaceControl
 *
 * @param sc The SurfaceControl to change position
 * @param x the X position
 * @param y the Y position
 * @return this transaction
 */
@NonNull
public Transaction setPosition(@NonNull SurfaceControl sc, float x, float y) {
    checkPreconditions(sc);
    if (sc.toString().contains("com.tencent.qqlive")){
        Slog.d("jinyanmeilayer","setPosition  sc:"+ sc);
        Slog.d("jinyanmeilayer","setPosition  x:" + x + " y: "+ y, new RuntimeException("jinyanmeilayer"));
    }
    nativeSetPosition(mNativeObject, sc.mNativeObject, x, y);
    return this;
}
/missi_t_mtk/frameworks/base/core/jni/android_view_SurfaceControl.cpp
static void nativeSetPosition(JNIEnv* env, jclass clazz, jlong transactionObj,
        jlong nativeObject, jfloat x, jfloat y) {
    auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
 
    SurfaceControl* const ctrl = reinterpret_cast<SurfaceControl *>(nativeObject);
    transaction->setPosition(ctrl, x, y);
}

每一层layer的属性暂存到layer_state_t中

frameworks/native/libs/gui/SurfaceComposerClient.cpp
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setPosition(
        const sp<SurfaceControl>& sc, float x, float y) {
    layer_state_t* s = getLayerState(sc);
    if (!s) {
        mStatus = BAD_INDEX;
        return *this;
    }
    s->what |= layer_state_t::ePositionChanged;
    s->x = x;
    s->y = y;
 
    registerSurfaceControlForCallback(sc);
    return *this;
}
std::unordered_map<sp<IBinder>, ComposerState, IBinderHash> mComposerStates;
struct ComposerState {
    layer_state_t state;
    status_t write(Parcel& output) const;
    status_t read(const Parcel& input);
};
frameworks/native/libs/gui/SurfaceComposerClient.cpp

1133layer_state_t* SurfaceComposerClient::Transaction::getLayerState(const sp<SurfaceControl>& sc) {
1134    auto handle = sc->getLayerStateHandle();
1135
1136    if (mComposerStates.count(handle) == 0) {
1137        // we don't have it, add an initialized layer_state to our list
1138        ComposerState s;
1139
1140        s.state.surface = handle;
1141        s.state.layerId = sc->getLayerId();
1142
1143        mComposerStates[handle] = s;
1144    }
1145
1146    return &(mComposerStates[handle].state);
1147}

state生效过程

在SurfaceControl.Transaction的apply

SurfaceControl.apply

→SurfaceControl.apply

→android_view_SurfaceControl::nativeApplyTransaction

→SurfaceComposerClient::apply(sync)

→SurfaceFlinger::setTransactionState

→SurfaceFlinger::waitForSynchronousTransaction

→SurfaceFlinger::applyTransactionState

→SurfaceFlinger::setClientStateLocked

SurfaceControl.java
public void apply() {
    apply(false);
}
 
public void apply(boolean sync) {
    applyResizedSurfaces();
    notifyReparentedSurfaces();
    nativeApplyTransaction(mNativeObject, sync);
}
frameworks/base/core/jni/android_view_SurfaceControl.cpp

557static void nativeApplyTransaction(JNIEnv* env, jclass clazz, jlong transactionObj, jboolean sync) {
558    auto transaction = reinterpret_cast<SurfaceComposerClient::Transaction*>(transactionObj);
559    transaction->apply(sync);
560}
frameworks/native/libs/gui/SurfaceComposerClient.cpp
status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay) {
    if (mStatus != NO_ERROR) {
        return mStatus;
    }

    std::shared_ptr<SyncCallback> syncCallback = std::make_shared<SyncCallback>();
    if (synchronous) {
        syncCallback->init();
        addTransactionCommittedCallback(SyncCallback::getCallback(syncCallback),
                                        /*callbackContext=*/nullptr);
    }

    bool hasListenerCallbacks = !mListenerCallbacks.empty();
    std::vector<ListenerCallbacks> listenerCallbacks;
    // For every listener with registered callbacks
    for (const auto& [listener, callbackInfo] : mListenerCallbacks) {
        auto& [callbackIds, surfaceControls] = callbackInfo;
        if (callbackIds.empty()) {
            continue;
        }

        if (surfaceControls.empty()) {
            listenerCallbacks.emplace_back(IInterface::asBinder(listener), std::move(callbackIds));
        } else {
            // If the listener has any SurfaceControls set on this Transaction update the surface
            // state
            for (const auto& surfaceControl : surfaceControls) {
                layer_state_t* s = getLayerState(surfaceControl);
                if (!s) {
                    ALOGE("failed to get layer state");
                    continue;
                }
                std::vector<CallbackId> callbacks(callbackIds.begin(), callbackIds.end());
                s->what |= layer_state_t::eHasListenerCallbacksChanged;
                s->listeners.emplace_back(IInterface::asBinder(listener), callbacks);
            }
        }
    }

    cacheBuffers();

    Vector<ComposerState> composerStates;
    Vector<DisplayState> displayStates;
    uint32_t flags = 0;

    for (auto const& kv : mComposerStates) {
        composerStates.add(kv.second);
    }

    displayStates = std::move(mDisplayStates);

    if (mAnimation) {
        flags |= ISurfaceComposer::eAnimation;
    }
    if (oneWay) {
        if (synchronous) {
            ALOGE("Transaction attempted to set synchronous and one way at the same time"
                  " this is an invalid request. Synchronous will win for safety");
        } else {
            flags |= ISurfaceComposer::eOneWay;
        }
    }

    // If both mEarlyWakeupStart and mEarlyWakeupEnd are set
    // it is equivalent for none
    if (mEarlyWakeupStart && !mEarlyWakeupEnd) {
        flags |= ISurfaceComposer::eEarlyWakeupStart;
    }
    if (mEarlyWakeupEnd && !mEarlyWakeupStart) {
        flags |= ISurfaceComposer::eEarlyWakeupEnd;
    }

    sp<IBinder> applyToken = mApplyToken ? mApplyToken : sApplyToken;

    sp<ISurfaceComposer> sf(ComposerService::getComposerService());
    sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken,
                            mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp,
                            mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId,
                            mMergedTransactionIds);
    mId = generateId();

    // Clear the current states and flags
    clear();

    if (synchronous) {
        syncCallback->wait();
    }

    mStatus = NO_ERROR;
    return NO_ERROR;
}
SurfaceFlinger.cpp

status_t SurfaceFlinger::setTransactionState(
        const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& states,
        const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
        InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp,
        const std::vector<client_cache_t>& uncacheBuffers, bool hasListenerCallbacks,
        const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId,
        const std::vector<uint64_t>& mergedTransactionIds) {
    ATRACE_CALL();

    IPCThreadState* ipc = IPCThreadState::self();
    const int originPid = ipc->getCallingPid();
    const int originUid = ipc->getCallingUid();
    uint32_t permissions = LayerStatePermissions::getTransactionPermissions(originPid, originUid);
    for (auto composerState : states) {
        composerState.state.sanitize(permissions);
    }

    for (DisplayState display : displays) {
        display.sanitize(permissions);
    }

    if (!inputWindowCommands.empty() &&
        (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) {
        ALOGE("Only privileged callers are allowed to send input commands.");
        inputWindowCommands.clear();
    }

    if (flags & (eEarlyWakeupStart | eEarlyWakeupEnd)) {
        const bool hasPermission =
                (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
                callingThreadHasPermission(sWakeupSurfaceFlinger);
        if (!hasPermission) {
            ALOGE("Caller needs permission android.permission.WAKEUP_SURFACE_FLINGER to use "
                  "eEarlyWakeup[Start|End] flags");
            flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
        }
    }

    const int64_t postTime = systemTime();

    std::vector<uint64_t> uncacheBufferIds;
    uncacheBufferIds.reserve(uncacheBuffers.size());
    for (const auto& uncacheBuffer : uncacheBuffers) {
        sp<GraphicBuffer> buffer = ClientCache::getInstance().erase(uncacheBuffer);
        if (buffer != nullptr) {
            uncacheBufferIds.push_back(buffer->getId());
        }
    }

    std::vector<ResolvedComposerState> resolvedStates;
    resolvedStates.reserve(states.size());
    for (auto& state : states) {
        resolvedStates.emplace_back(std::move(state));
        auto& resolvedState = resolvedStates.back();
        if (resolvedState.state.hasBufferChanges() && resolvedState.state.hasValidBuffer() &&
            resolvedState.state.surface) {
            sp<Layer> layer = LayerHandle::getLayer(resolvedState.state.surface);
            std::string layerName = (layer) ?
                    layer->getDebugName() : std::to_string(resolvedState.state.layerId);
            resolvedState.externalTexture =
                    getExternalTextureFromBufferData(*resolvedState.state.bufferData,
                                                     layerName.c_str(), transactionId);
            mBufferCountTracker.increment(resolvedState.state.surface->localBinder());
        }
        resolvedState.layerId = LayerHandle::getLayerId(resolvedState.state.surface);
        if (resolvedState.state.what & layer_state_t::eReparent) {
            resolvedState.parentId =
                    getLayerIdFromSurfaceControl(resolvedState.state.parentSurfaceControlForChild);
        }
        if (resolvedState.state.what & layer_state_t::eRelativeLayerChanged) {
            resolvedState.relativeParentId =
                    getLayerIdFromSurfaceControl(resolvedState.state.relativeLayerSurfaceControl);
        }
        if (resolvedState.state.what & layer_state_t::eInputInfoChanged) {
            wp<IBinder>& touchableRegionCropHandle =
                    resolvedState.state.windowInfoHandle->editInfo()->touchableRegionCropHandle;
            resolvedState.touchCropId =
                    LayerHandle::getLayerId(touchableRegionCropHandle.promote());
        }
    }

    TransactionState state{frameTimelineInfo,
                           resolvedStates,
                           displays,
                           flags,
                           applyToken,
                           std::move(inputWindowCommands),
                           desiredPresentTime,
                           isAutoTimestamp,
                           std::move(uncacheBufferIds),
                           postTime,
                           hasListenerCallbacks,
                           listenerCallbacks,
                           originPid,
                           originUid,
                           transactionId,
                           mergedTransactionIds};

    if (mTransactionTracing) {
        mTransactionTracing->addQueuedTransaction(state);
    }

    const auto schedule = [](uint32_t flags) {
        if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
        if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
        return TransactionSchedule::Late;
    }(state.flags);

    const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
    mTransactionHandler.queueTransaction(std::move(state));
    setTransactionFlags(eTransactionFlushNeeded, schedule, applyToken, frameHint);
    return NO_ERROR;
}

调用了applyTransactionState

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
                                           std::vector<ResolvedComposerState>& states,
                                           Vector<DisplayState>& displays, uint32_t flags,
                                           const InputWindowCommands& inputWindowCommands,
                                           const int64_t desiredPresentTime, bool isAutoTimestamp,
                                           const std::vector<uint64_t>& uncacheBufferIds,
                                           const int64_t postTime, bool hasListenerCallbacks,
                                           const std::vector<ListenerCallbacks>& listenerCallbacks,
                                           int originPid, int originUid, uint64_t transactionId) {
    uint32_t transactionFlags = 0;
    if (!mLayerLifecycleManagerEnabled) {
        for (DisplayState& display : displays) {
            transactionFlags |= setDisplayStateLocked(display);
        }
    }

    // start and end registration for listeners w/ no surface so they can get their callback.  Note
    // that listeners with SurfaceControls will start registration during setClientStateLocked
    // below.
    for (const auto& listener : listenerCallbacks) {
        mTransactionCallbackInvoker.addEmptyTransaction(listener);
    }

    uint32_t clientStateFlags = 0;
    for (auto& resolvedState : states) {
        if (mLegacyFrontEndEnabled) {
            clientStateFlags |=
                    setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime,
                                         isAutoTimestamp, postTime, transactionId);

        } else /*mLayerLifecycleManagerEnabled*/ {
            clientStateFlags |= updateLayerCallbacksAndStats(frameTimelineInfo, resolvedState,
                                                             desiredPresentTime, isAutoTimestamp,
                                                             postTime, transactionId);
        }
        if ((flags & eAnimation) && resolvedState.state.surface) {
            if (const auto layer = LayerHandle::getLayer(resolvedState.state.surface)) {
                const auto layerProps = scheduler::LayerProps{
                        .visible = layer->isVisible(),
                        .bounds = layer->getBounds(),
                        .transform = layer->getTransform(),
                        .setFrameRateVote = layer->getFrameRateForLayerTree(),
                        .frameRateSelectionPriority = layer->getFrameRateSelectionPriority(),
                };
                layer->recordLayerHistoryAnimationTx(layerProps);
            }
        }
    }

    transactionFlags |= clientStateFlags;
    transactionFlags |= addInputWindowCommands(inputWindowCommands);

    for (uint64_t uncacheBufferId : uncacheBufferIds) {
        mBufferIdsToUncache.push_back(uncacheBufferId);
    }

    // If a synchronous transaction is explicitly requested without any changes, force a transaction
    // anyway. This can be used as a flush mechanism for previous async transactions.
    // Empty animation transaction can be used to simulate back-pressure, so also force a
    // transaction for empty animation transactions.
    if (transactionFlags == 0 && (flags & eAnimation)) {
        transactionFlags = eTransactionNeeded;
    }

    bool needsTraversal = false;
    if (transactionFlags) {
        // We are on the main thread, we are about to perform a traversal. Clear the traversal bit
        // so we don't have to wake up again next frame to perform an unnecessary traversal.
        if (transactionFlags & eTraversalNeeded) {
            transactionFlags = transactionFlags & (~eTraversalNeeded);
            needsTraversal = true;
        }
        if (transactionFlags) {
            setTransactionFlags(transactionFlags);
        }
    }

    return needsTraversal;
}
setClientStateLocked 将暂存的属性设置到layer中
uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
                                              ComposerState& composerState,
                                              int64_t desiredPresentTime, bool isAutoTimestamp,
                                              int64_t postTime, uint32_t permissions) {
    layer_state_t& s = composerState.state;
    s.sanitize(permissions);
 
    std::vector<ListenerCallbacks> filteredListeners;
    for (auto& listener : s.listeners) {
        // Starts a registration but separates the callback ids according to callback type. This
        // allows the callback invoker to send on latch callbacks earlier.
        // note that startRegistration will not re-register if the listener has
        // already be registered for a prior surface control
 
        ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
        if (!onCommitCallbacks.callbackIds.empty()) {
            filteredListeners.push_back(onCommitCallbacks);
        }
 
        ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
        if (!onCompleteCallbacks.callbackIds.empty()) {
            filteredListeners.push_back(onCompleteCallbacks);
        }
    }
 
    const uint64_t what = s.what;
    uint32_t flags = 0;
    sp<Layer> layer = nullptr;
    if (s.surface) {
        layer = fromHandle(s.surface).promote();
    } else {
        // The client may provide us a null handle. Treat it as if the layer was removed.
        ALOGW("Attempt to set client state with a null layer handle");
    }
    if (layer == nullptr) {
        for (auto& [listener, callbackIds] : s.listeners) {
            mTransactionCallbackInvoker.registerUnpresentedCallbackHandle(
                    new CallbackHandle(listener, callbackIds, s.surface));
        }
        return 0;
    }
 
    // Only set by BLAST adapter layers
    if (what & layer_state_t::eProducerDisconnect) {
        layer->onDisconnect();
    }
 
    if (what & layer_state_t::ePositionChanged) {
        if (layer->setPosition(s.x, s.y)) { //调用到setPositon
            flags |= eTraversalNeeded;
        }
    }




bool Layer::setPosition(float x, float y) {
    if (mDrawingState.transform.tx() == x && mDrawingState.transform.ty() == y) return false;
    mDrawingState.sequence++;
    mDrawingState.transform.set(x, y);
 
    mDrawingState.modified = true;
    setTransactionFlags(eTransactionNeeded);
    return true;
}

将值设置到mDrawingState的transform中

frameworks/native/include/ui/Transform.cpp

void Transform::set(float tx, float ty) {
    mMatrix[2][0] = tx;
    mMatrix[2][1] = ty;
    mMatrix[2][2] = 1.0f;
 
    if (isZero(tx) && isZero(ty)) {
        mType &= ~TRANSLATE;
    } else {
        mType |= TRANSLATE;
    }
}

transform通过平移旋转等进行计算visibleRegion

frameworks/native/include/ui/Transform.cpp

void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
                                         const sp<IBinder>& applyToken, FrameHint frameHint) {
    modulateVsync(&VsyncModulator::setTransactionSchedule, schedule, applyToken);
 
    if (const bool scheduled = mTransactionFlags.fetch_or(mask) & mask; !scheduled) {
        scheduleCommit(frameHint);
    }
}
frameworks/native/services/surfaceflinger/SurfaceFlinger.h


603    void modulateVsync(Handler handler, Args... args) {
604        if (const auto config = (*mVsyncModulator.*handler)(args...)) {
605            const auto vsyncPeriod = mScheduler->getVsyncPeriodFromRefreshRateConfigs();
606            setVsyncConfig(*config, vsyncPeriod);
607        }
608    }

然后等待vsync的信号到来

Vsync信号到来时VisibleRegion的计算过程

Layer 属性发生变化做的操作

SurfaceFlinger::commit
→SurfaceFlinger::commitTransactions

→SurfaceFlinger::commitTransactionsLocked

→SurfaceFlinger::doCommitTransactions

→SurfaceFlinger::commitOffscreenLayers

→SurfaceFlinger::doTransaction(0)

→layer::doTransaction

→layer::commitTransaction

→layer::setPresentState 赋值mPresentState = presentState;

  1. 根据Layer的size是否变化,改变buffer大小
  2. mCurrentSate.active=mCurrentSate.requested(一般情况下都会赋值,除非flags设置了eDontUpdateGeometryState),
  3. 修改flags(使之重新计算visibelRegion的值)
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
bool SurfaceFlinger::commit(TimePoint frameTime, VsyncId vsyncId, TimePoint expectedVsyncTime)
        FTL_FAKE_GUARD(kMainThreadContext) {
        const bool shouldCommit =
                (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
        if (shouldCommit) {
            commitTransactions();
        }

        updateLayerGeometry(); //计算bounds
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::commitTransactions() {
    ATRACE_CALL();
 
    // Keep a copy of the drawing state (that is going to be overwritten
    // by commitTransactionsLocked) 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 lock(mStateLock);
    mDebugInTransaction = systemTime();
 
    // Here we're guaranteed that some transaction flags are set
    // so we can call commitTransactionsLocked unconditionally.
    // We clear the flags with mStateLock held to guarantee that
    // mCurrentState won't change until the transaction is committed.
    modulateVsync(&VsyncModulator::onTransactionCommit);
    commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
 
    mDebugInTransaction = 0;
}

mPresentState = presentState;

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp

void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {

    // some layers might have been removed, so
    // we need to update the regions they're exposing.
    if (mLayersRemoved) {
        mLayersRemoved = false;
        mVisibleRegionsDirty = true;
        mUpdateInputInfo = true;
        mDrawingState.traverseInZOrder([&](Layer* layer) {
            if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
                // this layer is not visible anymore
                Region visibleReg;
                visibleReg.set(layer->getScreenBounds());
                invalidateLayerStack(layer->getOutputFilter(), visibleReg);
            }
        });
    }


    doCommitTransactions();

void SurfaceFlinger::doCommitTransactions() {
    ATRACE_CALL();
    commitOffscreenLayers();
}


void SurfaceFlinger::commitOffscreenLayers() {
    for (Layer* offscreenLayer : mOffscreenLayers) {
        offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
            if (layer->clearTransactionFlags(eTransactionNeeded)) {
                layer->doTransaction(0);
                layer->commitChildList();
            }
        });
    }
}
Layer.cpp

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

    // TODO: This is unfortunate.
    mDrawingStateModified = mDrawingState.modified;
    mDrawingState.modified = false;

    const State& s(getDrawingState());

    if (updateGeometry()) {
        // invalidate and recompute the visible regions if needed
        flags |= Layer::eVisibleRegion;
    }

    if (s.sequence != mLastCommittedTxSequence) {
        // invalidate and recompute the visible regions if needed
        mLastCommittedTxSequence = s.sequence;
        flags |= eVisibleRegion;
        this->contentDirty = true;

        // we may use linear filtering, if the matrix scales us
        mNeedsFiltering = getActiveTransform(s).needsBilinearFiltering();
    }

    if (!mPotentialCursor && (flags & Layer::eVisibleRegion)) {
        mFlinger->mUpdateInputInfo = true;
    }

    commitTransaction(mDrawingState);

    return flags;
}


void Layer::commitTransaction(State&) {
    // Set the present state for all bufferlessSurfaceFramesTX to Presented. The
    // bufferSurfaceFrameTX will be presented in latchBuffer.
    for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
        if (surfaceFrame->getPresentState() != PresentState::Presented) {
            // With applyPendingStates, we could end up having presented surfaceframes from previous
            // states
            surfaceFrame->setPresentState(PresentState::Presented, mLastLatchTime);
            mFlinger->mFrameTimeline->addSurfaceFrame(surfaceFrame);
        }
    }
    mDrawingState.bufferlessSurfaceFramesTX.clear();
}
frameworks/native/services/surfaceflinger/FrameTimeline/FrameTimeline.cpp

void SurfaceFrame::setPresentState(PresentState presentState, nsecs_t lastLatchTime) {
    std::scoped_lock lock(mMutex);
    LOG_ALWAYS_FATAL_IF(mPresentState != PresentState::Unknown,
                        "setPresentState called on a SurfaceFrame from Layer - %s, that has a "
                        "PresentState - %s set already.",
                        mDebugName.c_str(), toString(mPresentState).c_str());
    mPresentState = presentState;
    mLastLatchTime = lastLatchTime;
}
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
void SurfaceFlinger::updateLayerGeometry() {
    ATRACE_CALL();
 
    if (mVisibleRegionsDirty) {
        computeLayerBounds();
    }
 
    for (auto& layer : mLayersPendingRefresh) {
        Region visibleReg;
        visibleReg.set(layer->getScreenBounds());
        invalidateLayerStack(layer, visibleReg);
    }
 
    setDisplayAnimating();
 
    mLayersPendingRefresh.clear();
}

 计算region

frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp 

void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
    for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
        auto display = displayDevice->getCompositionDisplay();
        if (display->includesLayer(layer->getOutputFilter())) {
            display->editState().dirtyRegion.orSelf(dirty);
        }
    }
}
frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp 

void SurfaceFlinger::computeLayerBounds() {
    const FloatRect maxBounds = getMaxDisplayBounds();
    for (const auto& layer : mDrawingState.layersSortedByZ) {
        layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
            if (layer->getName().find("com.tencent.qqlive") != std::string::npos) {
            ALOGD("jinyanmeilayer computeLayerBounds 0000  maxBounds=(%f,%f,%f,%f) :",  maxBounds.left, maxBounds.top, maxBounds.right, maxBounds.bottom);
            ALOGD("jinyanmeilayer computeLayerBounds 0000  getDebugName: %s ",layer->getName().c_str());
            }
    }
}
frameworks/native/services/surfaceflinger/Layer.h 
inline State& getDrawingState() { return mDrawingState; }
ui::Transform getActiveTransform(const Layer::State& s) const { return s.transform; }
virtual FloatRect computeSourceBounds(const FloatRect& parentBounds) const {
    return parentBounds;
}
virtual Rect getCrop(const Layer::State& s) const { return s.crop; }
frameworks/native/services/surfaceflinger/Layer.cpp 

void Layer::computeBounds(FloatRect parentBounds, ui::Transform parentTransform,
                          float parentShadowRadius) {
    const State& s(getDrawingState());   //根据保存的State
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds ----  parentTransform=parentTransform %f parentTransform.ty %f, sx %f, tx() %f, ty %f, sy:%f, det %f, getScaleX %f, getScaleY %f "
    ,parentTransform.tx(), parentTransform.ty(),
   parentTransform.dsdx(), parentTransform.dtdx(), parentTransform.dtdy(),
    parentTransform.dsdy(), parentTransform.det(),parentTransform.getScaleX(), parentTransform.getScaleY());
 
      //  ALOGD("jinyanmeilayer computeBounds ----  parentTransform=(%s) ",  parentTransform.transformToString(parentTransform));
    ALOGD("jinyanmeilayer computeBounds ----  parentBounds=(%f,%f,%f,%f) :",  parentBounds.left, parentBounds.top, parentBounds.right, parentBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds ----  getDebugName: %s ",getDebugName());
    android::CallStack stack("jinyanmeilayer");
    }
    // Calculate effective layer transform
    mEffectiveTransform = parentTransform * getActiveTransform(s);//getActiveTransform(s)得到s.transform;
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
        ALOGD("jinyanmeilayer computeBounds ----   getActiveTransform(s) %f  getActiveTransform(s).ty %f, sx %f, tx() %f, ty %f, sy:%f, det %f, getScaleX %f, getScaleY %f "
            , getActiveTransform(s).tx(),  getActiveTransform(s).ty(),
            getActiveTransform(s).dsdx(),  getActiveTransform(s).dtdx(),  getActiveTransform(s).dtdy(),
             getActiveTransform(s).dsdy(),  getActiveTransform(s).det(), getActiveTransform(s).getScaleX(),  getActiveTransform(s).getScaleY());
    ALOGD("jinyanmeilayer computeBounds ----  mEffectiveTransform=mEffectiveTransform %f mEffectiveTransform.ty %f, sx %f, tx() %f, ty %f, sy:%f, det %f, getScaleX %f, getScaleY %f "
    ,mEffectiveTransform.tx(), mEffectiveTransform.ty(),
   mEffectiveTransform.dsdx(), mEffectiveTransform.dtdx(), mEffectiveTransform.dtdy(),
    mEffectiveTransform.dsdy(), mEffectiveTransform.det(),mEffectiveTransform.getScaleX(), mEffectiveTransform.getScaleY());
    }
 
    if (CC_UNLIKELY(!isTransformValid())) {
        ALOGW("Stop computing bounds for %s because it has invalid transformation.",
              getDebugName());
        return;
    }
    // Transform parent bounds to layer space
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 0000  parentBounds=(%f,%f,%f,%f) :",  parentBounds.left, parentBounds.top, parentBounds.right, parentBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 0000  getDebugName: %s ",getDebugName());
    }
 
    parentBounds = getActiveTransform(s).inverse().transform(parentBounds);
 
        if (getName().find("com.tencent.qqlive") != std::string::npos) {
                ALOGD("jinyanmeilayer computeBounds ----  getActiveTransform(s)() %f getActiveTransform.ty %f, sx %f, tx() %f, ty %f, sy:%f, det %f, getScaleX %f, getScaleY %f "
                ,getActiveTransform(s).tx(), getActiveTransform(s).ty(),
               getActiveTransform(s).dsdx(), getActiveTransform(s).dtdx(), getActiveTransform(s).dtdy(),
                getActiveTransform(s).dsdy(), getActiveTransform(s).det(),getActiveTransform(s).getScaleX(), getActiveTransform(s).getScaleY());
 
        ALOGD("jinyanmeilayer computeBounds ----  getActiveTransform(s).inverse() %f mEffectiveTransform.ty %f, sx %f, tx() %f, ty %f, sy:%f, det %f, getScaleX %f, getScaleY %f "
        ,getActiveTransform(s).inverse().tx(), getActiveTransform(s).inverse().ty(),
       getActiveTransform(s).inverse().dsdx(), getActiveTransform(s).inverse().dtdx(), getActiveTransform(s).inverse().dtdy(),
        getActiveTransform(s).inverse().dsdy(), getActiveTransform(s).inverse().det(),getActiveTransform(s).inverse().getScaleX(), getActiveTransform(s).inverse().getScaleY());
        }
 
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 1111  parentBounds=(%f,%f,%f,%f) :",  parentBounds.left, parentBounds.top, parentBounds.right, parentBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 11111  getDebugName: %s ",getDebugName());
    }
    // Calculate source bounds
    mSourceBounds = computeSourceBounds(parentBounds);
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 222  mSourceBounds=(%f,%f,%f,%f) :",  mSourceBounds.left, mSourceBounds.top, mSourceBounds.right, mSourceBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 222  getDebugName: %s ",getDebugName());
    }
 
    // Calculate bounds by croping diplay frame with layer crop and parent bounds
    FloatRect bounds = mSourceBounds;
    const Rect layerCrop = getCrop(s);
#if MI_SCREEN_PROJECTION
    if (!MiSurfaceFlingerStub::continueComputeBounds(this)) return;
#endif
    if (!layerCrop.isEmpty()) {
        bounds = mSourceBounds.intersect(layerCrop.toFloatRect());
    }
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 333  bounds=(%f,%f,%f,%f) :",  bounds.left, bounds.top, bounds.right, bounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 333  getDebugName: %s ",getDebugName());
    }
 
    bounds = bounds.intersect(parentBounds);
 
    mBounds = bounds;
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 444  parentBounds=(%f,%f,%f,%f) :",  mBounds.left, mBounds.top, mBounds.right, mBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 444  getDebugName: %s ",getDebugName());
    }
    mScreenBounds = mEffectiveTransform.transform(mBounds);
    if (getName().find("com.tencent.qqlive") != std::string::npos) {
    ALOGD("jinyanmeilayer computeBounds 555  mScreenBounds=(%f,%f,%f,%f) :",  mScreenBounds.left, mScreenBounds.top, mScreenBounds.right, mScreenBounds.bottom);
    ALOGD("jinyanmeilayer computeBounds 555  getDebugName: %s ",getDebugName());
    }
 
 
    // Use the layer's own shadow radius if set. Otherwise get the radius from
    // parent.
    if (s.shadowRadius > 0.f) {
        mEffectiveShadowRadius = s.shadowRadius;
    } else {
        mEffectiveShadowRadius = parentShadowRadius;
    }
 
    // Shadow radius is passed down to only one layer so if the layer can draw shadows,
    // don't pass it to its children.
    const float childShadowRadius = canDrawShadows() ? 0.f : mEffectiveShadowRadius;
 
    for (const sp<Layer>& child : mDrawingChildren) {
        child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
    }
}