Android下SF合成流程重学习之onMessageInvalidate

Android下SF合成流程重学习之onMessageInvalidate



引言

虽然看了很多关于Android Graphics图形栈的文章和博客,但是都没有形成自己的知识点。每次学习了,仅仅是学习了而已,没有形成自己的知识体系,这次趁着有时间,这次必须把这个事情干透彻了!

本篇引用的代码,主要是Android R的。

并且Android下Graphics图形栈牵涉的点,太多了,这篇博客我们着重分析SF合成流程重学习之onMessageInvalidate的处理流程!




SurfaceFlinger layer之间的对应关系

先用一张图来看下各个部分之间layer的对应关系。接下来会根据这个图来解析是如何进行转换的,如下:

image




一. SF处理事务和处理Buffer

在SF的onMessageInvalidate主要是用来,处理事物和处理相关Buffer的,我们在下面的博客中详细分析!

在这里插入图片描述




1.1 onMessageInvalidate

文件: frameworks/native/services/surfaceflinger/Surfaceflinger.cppvoid SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {ATRACE_CALL();const nsecs_t frameStart = systemTime();// expectedVSyncTime 是vsync回调带过来的时间戳,通过nextAnticipatedVSyncTimeFrom 计算得到if (expectedVSyncTime >= frameStart) {mExpectedPresentTime = expectedVSyncTime;} else {mExpectedPresentTime = mScheduler->getDispSyncExpectedPresentTime(frameStart);}// 存储上一帧的expectedVSyncTimeconst nsecs_t lastScheduledPresentTime = mScheduledPresentTime;mScheduledPresentTime = expectedVSyncTime;...// 根据上一帧的present fence判断当前这一帧是否pendingconst TracedOrdinal<bool> framePending = {"PrevFramePending",previousFramePending(graceTimeForPresentFenceMs)};// 若framePending  或者 上一帧present fence释放的时间  > 上一帧vsync计算的时间戳 + vsync周期的一半// 则当前帧要丢掉DisplayStatInfo stats;mScheduler->getDisplayStatInfo(&stats);const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;const nsecs_t previousPresentTime = previousFramePresentTime();const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",framePending ||(previousPresentTime >= 0 &&(lastScheduledPresentTime <previousPresentTime - frameMissedSlop))};// 根据合成类型判断丢帧的类型const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",mHadDeviceComposition && frameMissed};const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",mHadClientComposition && frameMissed};...// 这部分涉及帧率切换,先是通过performSetActiveConfig 将新的帧率给到hwc,然后下一帧再更新sf这边的状态if (mSetActiveConfigPending) {if (framePending) {mEventQueue->invalidate();return;}// We received the present fence from the HWC, so we assume it successfully updated// the config, hence we update SF.mSetActiveConfigPending = false;ON_MAIN_THREAD(setActiveConfigInternal());}
}//  mPropagateBackpressure 可以通过adb shell setprop debug.sf.disable_backpressure x 来控制,表示系统是否允许丢帧//  若允许丢帧则skip这次刷帧if (framePending && mPropagateBackpressure) {if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {signalLayerUpdate();return;}}....bool refreshNeeded;{ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);// 主要的逻辑在这两个函数,简单理解为处理layer或者display的事务和layer的bufferrefreshNeeded = handleMessageTransaction();refreshNeeded |= handleMessageInvalidate();...}// 帧率切换,SurfaceFlinger主线程执行ON_MAIN_THREAD(performSetActiveConfig());...// 若layer的事务有变化或者有新的buffer,则触发refreshsignalRefresh();
}

上述onMessageInvalidate概括来说,其主要处理的事情如下:

  • 判断当前帧是否丢掉
  • handleMessageTransaction 处理layer或者display事务
  • handleMessageInvalidate 处理应用queue过来的Buffer
  • 帧率切换
  • 触发刷新流程



1.2 handleMessageTransaction

文件: frameworks/native/services/surfaceflinger/Surfaceflinger.cppbool SurfaceFlinger::handleMessageTransaction() {ATRACE_CALL();// 获取当前的mTransactionFlags,mTransactionFlags 由setTransactionFlags 赋值,比如CreateLayer时会给mTransactionFlags 赋值eTransactionNeeded// createDisplay 时会给mTransactionFlags 赋值 eDisplayTransactionNeededuint32_t transactionFlags = peekTransactionFlags();// flushTransactionQueues 会消费transactionQueue,transactionQueue 是上层通过SurfaceComposerClient 设的,然后再通过binder设置给sf这边// setDisplayStateLocked: 处理display的事务// setClientStateLocked: 处理layer的事务// 这两部分事务都存放在surfaceflinger的mCurrentState 里面bool flushedATransaction = flushTransactionQueues();// 有新的事务则要执行handleTransactionbool runHandleTransaction =(transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||flushedATransaction ||mForceTraversal;// 处理layer和display的事务if (runHandleTransaction) {handleTransaction(eTransactionMask);} else {getTransactionFlags(eTransactionFlushNeeded);}if (transactionFlushNeeded()) {setTransactionFlags(eTransactionFlushNeeded);}return runHandleTransaction;
}//来看下display和layer有哪些事务处理文件: frameworks/native/services/surfaceflinger/Surfaceflinger.cpp// display的事务,包括display Surface, layerStack , Projection , viewport, Size发生变化时附上eDisplayTransactionNeeded 这个flags
uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {const ssize_t index = mCurrentState.displays.indexOfKey(s.token);if (index < 0) return 0;uint32_t flags = 0;DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);const uint32_t what = s.what;if (what & DisplayState::eSurfaceChanged) {if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {state.surface = s.surface;flags |= eDisplayTransactionNeeded;}}if (what & DisplayState::eLayerStackChanged) {if (state.layerStack != s.layerStack) {state.layerStack = s.layerStack;flags |= eDisplayTransactionNeeded;}}if (what & DisplayState::eDisplayProjectionChanged) {if (state.orientation != s.orientation) {state.orientation = s.orientation;flags |= eDisplayTransactionNeeded;}if (state.frame != s.frame) {state.frame = s.frame;flags |= eDisplayTransactionNeeded;}if (state.viewport != s.viewport) {state.viewport = s.viewport;flags |= eDisplayTransactionNeeded;}}if (what & DisplayState::eDisplaySizeChanged) {if (state.width != s.width) {state.width = s.width;flags |= eDisplayTransactionNeeded;}if (state.height != s.height) {state.height = s.height;flags |= eDisplayTransactionNeeded;}}return flags;
}文件: frameworks/native/services/surfaceflinger/Surfaceflinger.cpp// layer的事务,包括ePositionChanged, eLayerChanged, eAlphaChanged 等等,跟上层的surface设置一样,同样的事务同步给layer
uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,bool privileged,std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
...  sp<Layer> layer = nullptr;if (s.surface) {layer = fromHandleLocked(s.surface).promote();...if (what & layer_state_t::eDeferTransaction_legacy) {layer->pushPendingState();}// Only set by BLAST adapter layersif (what & layer_state_t::eProducerDisconnect) {layer->onDisconnect();}if (what & layer_state_t::ePositionChanged) {if (layer->setPosition(s.x, s.y)) {flags |= eTraversalNeeded;}}
...
}

通过setDisplayStateLocked 和 setClientStateLocked 获取了display和layer的事务变化的flag,并且setClientStateLocked还将layer与surface进行了事务的同步。

文件:  frameworks/native/services/surfaceflinger/Surfaceflinger.cppvoid SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
{...if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {mForceTraversal = false;// 遍历mCurrentState 里面的layer,对有事务变化的layer进行处理,doTransaction 主要的处理逻辑是对sync ponit的处理,// sync ponit用于延迟显示的一些layer,根据FrameNumber进行同步,如果当前帧数达到了设定值,latchBuffer就可以消费这个layermCurrentState.traverse([&](Layer* layer) {uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);if (!trFlags) return;const uint32_t flags = layer->doTransaction(0);if (flags & Layer::eVisibleRegion)mVisibleRegionsDirty = true;if (flags & Layer::eInputInfoChanged) {mInputInfoChanged = true;}});}// 处理 display的 事务逻辑if (transactionFlags & eDisplayTransactionNeeded) {processDisplayChangesLocked();processDisplayHotplugEventsLocked();}...// SurfaceFlinger维持mCurrentState 和 mDrawingState 两个状态,是个大的结构体,mCurrentState 可以理解为下一帧的// layer和display的状态, mDrawingState 可以理解为当前帧的状态,commitTransaction 将 mCurrentState 更新到这一帧的状态commitTransaction();
}

handleMessageTransaction主要的作用是处理display和layer的事物,将上层的surface和底层的layer属性做个同步,涉及到很多的细节以后遇到具体场景来分析,最后将mCurrentState 赋给 mDrawingState 更新到当前这一帧的状态。




1.3 handleMessageInvalidate

我们接着继续往下看,累啊,学习,搞起来~

文件:frameworks/native/services/surfaceflinger/Surfaceflinger.cppbool SurfaceFlinger::handleMessageInvalidate() {ATRACE_CALL();// 处理queue过来的Bufferbool refreshNeeded = handlePageFlip();if (mVisibleRegionsDirty) {// 如果可见区域有变化,则重新计算layer的范围computeLayerBounds();}//判断需要刷新的layer是否属于当前Outputfor (auto& layer : mLayersPendingRefresh) {Region visibleReg;visibleReg.set(layer->getScreenBounds());invalidateLayerStack(layer, visibleReg);}mLayersPendingRefresh.clear();return refreshNeeded;
}bool SurfaceFlinger::handlePageFlip()
{...// 遍历 mDrawingState里面的layer,判断该layer是否可在当前vsync内显示,如果queueBuffer带过来的时间戳大于Vsync的时间戳,则表示该layer不能在当前vsync内显示// 能够显示的layer放到mLayersWithQueuedFrames 里面mDrawingState.traverse([&](Layer* layer) {if (layer->hasReadyFrame()) {frameQueued = true;if (layer->shouldPresentNow(expectedPresentTime)) {mLayersWithQueuedFrames.push_back(layer);} else {ATRACE_NAME("!layer->shouldPresentNow()");layer->useEmptyDamage();}} else {layer->useEmptyDamage();}});...// 遍历mLayersWithQueuedFrames 里面的layer,执行latchBuffer,在latchBuffer里面消费Buffer// 成功消费的layer放到mLayersPendingRefresh 里面for (auto& layer : mLayersWithQueuedFrames) {if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {mLayersPendingRefresh.push_back(layer);}layer->useSurfaceDamage();if (layer->isBufferLatched()) {newDataLatched = true;}...// 当有需要消费Buffer的layer则返回truereturn !mLayersWithQueuedFrames.empty() && newDataLatched;文件: frameworks/native/services/surfaceflinger/BufferLayer.cppbool BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,nsecs_t expectedPresentTime) {...// 执行顺序BufferQueueLayer-> updateTexImage ==> BufferLayerConsumer-> updateTexImage,具体逻辑在// BufferLayerConsumer 里面status_t err = updateTexImage(recomputeVisibleRegions, latchTime, expectedPresentTime);// 更新mBufferInfo里的buffer,这个变量是在BufferQueueLayer里面维护err = updateActiveBuffer();if (err != NO_ERROR) {return false;}//更新mBufferInfo的FrameNumbererr = updateFrameNumber(latchTime);if (err != NO_ERROR) {return false;}// 更新到mBufferInfogatherBufferInfo();...
}文件: frameworks/native/services/surfaceflinger/BufferLayerConsumer.cppstatus_t BufferLayerConsumer::updateTexImage(BufferRejecter* rejecter, nsecs_t expectedPresentTime,bool* autoRefresh, bool* queuedBuffer,uint64_t maxFrameNumber) {...BufferItem item;// acquireBuffer:消费queue过来的Buffer,放到item里面status_t err = acquireBufferLocked(&item, expectedPresentTime, maxFrameNumber);...// 更新BufferLayerConsumer 状态,都是从queueBuffer设置而来err = updateAndReleaseLocked(item, &mPendingRelease);...
}status_t BufferLayerConsumer::acquireBufferLocked(BufferItem* item, nsecs_t presentWhen,uint64_t maxFrameNumber) {status_t err = ConsumerBase::acquireBufferLocked(item, presentWhen, maxFrameNumber);...if (item->mGraphicBuffer != nullptr) {std::lock_guard<std::mutex> lock(mImagesMutex);if (mImages[item->mSlot] == nullptr || mImages[item->mSlot]->graphicBuffer() == nullptr ||mImages[item->mSlot]->graphicBuffer()->getId() != item->mGraphicBuffer->getId()) {// 将acquire出来的Buffer做成EGLImage,为了后面GPU合成mImages[item->mSlot] = std::make_shared<Image>(item->mGraphicBuffer, mRE);}}return NO_ERROR;
}文件: frameworks/native/libs/gui/ConsumerBase.cppstatus_t ConsumerBase::acquireBufferLocked(BufferItem *item,nsecs_t presentWhen, uint64_t maxFrameNumber) {...// 实现在BufferQueueConsumer的 acquireBufferstatus_t err = mConsumer->acquireBuffer(item, presentWhen, maxFrameNumber);if (err != NO_ERROR) {return err;}if (item->mGraphicBuffer != nullptr) {if (mSlots[item->mSlot].mGraphicBuffer != nullptr) {freeBufferLocked(item->mSlot);}//更新Bufferslot里面的GraphicsBuffer,这个Buffer的owner是GPU在处理mSlots[item->mSlot].mGraphicBuffer = item->mGraphicBuffer;}// 更新Bufferslot里面的frameNumber和fence,与queueBuffer设置保持一致,这里的fence为acquireFencemSlots[item->mSlot].mFrameNumber = item->mFrameNumber;mSlots[item->mSlot].mFence = item->mFence;CB_LOGV("acquireBufferLocked: -> slot=%d/%" PRIu64,item->mSlot, item->mFrameNumber);return OK;
}文件: frameworks/native/libs/gui/BufferQueueConsumer.cpp//跳过一些特殊情况代码细节,把主线code拎出来分析
status_t BufferQueueConsumer::acquireBuffer(BufferItem* outBuffer,nsecs_t expectedPresent, uint64_t maxFrameNumber) {...// queueBuffer时入的队列BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());...// 拿到queueBuffer对应的slot和BufferItemslot = front->mSlot;*outBuffer = *front;...if (!outBuffer->mIsStale) {mSlots[slot].mAcquireCalled = true;// Don't decrease the queue count if the BufferItem wasn't// previously in the queue. This happens in shared buffer mode when// the queue is empty and the BufferItem is created above.if (mCore->mQueue.empty()) {mSlots[slot].mBufferState.acquireNotInQueue();} else {// 更新状态为acquiremSlots[slot].mBufferState.acquire();}// queueBuffer入队,acquireBuffer出队mCore->mQueue.erase(front);...
}

handleMessageInvalidate主要作用是执行 latchBuffer 去 acquire 应用queue过来的Buffer,然后拿到queueBuffer时设的Bufferslot一些状态属性给到BufferQueueLayer的mBufferInfo,同时还把这个Buffer做成EGLImage为后面的GPU合成做准备,期间都是数据之间的传递,所以说SurfaceFlinger并未真正触碰Buffer的内容。

image




写在最后

好了今天的博客Android下SF合成流程重学习之onMessageInvalidate就到这里了。总之,青山不改绿水长流先到这里了。如果本博客对你有所帮助,麻烦关注或者点个赞,如果觉得很烂也可以踩一脚!谢谢各位了!!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/475016.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

三种vcruntime140.dll丢失解决方法,有效解决vcruntime140.dll文件丢失

vcruntime140.dll作为一个动态链接库文件&#xff0c;具有重要的功能和用途。它是由Microsoft Visual C Redistributable软件包提供的一个重要组件&#xff0c;用于支持运行在Windows操作系统上的应当vcruntime140.dll文件丢失时&#xff0c;将会对计算机系统产生一系列的影响。…

央视龙年春晚沈腾马丽第八度联手,紧张到嘴瓢引发全场哄笑。

♥ 为方便您进行讨论和分享&#xff0c;同时也为能带给您不一样的参与感。请您在阅读本文之前&#xff0c;点击一下“关注”&#xff0c;非常感谢您的支持&#xff01; 文 |猴哥聊娱乐 编 辑|徐 婷 校 对|侯欢庭 除夕夜&#xff0c;华灯初上&#xff0c;央视龙年春晚的舞台上…

达梦数据库——数据迁移sqlserver-dm报错问题整理

报错情况一&#xff1a;Sql server迁移达梦连接报错’驱动程序无法通过使用安全套接字Q层(SSL)加密与SQL Server 建立安全连接。错误:“The server selected protocol version TLS10 is not accepted by client preferencesITLS127‘ 原因&#xff1a;历史版本的SOL SERVER服务…

python中break和continue的用法

目录 continue&#xff1a;结束本次循环 break&#xff1a;终止最近的整个循环 跳出多重循环 continue&#xff1a;结束本次循环 s "python" for i in s:if i o:continueprint(i) 当i等于o时&#xff0c;结束整个循环&#xff0c;所以o和n都不打印出来 break&…

4核8G云服务器多少钱?价格汇总

4核8G云服务器多少钱一年&#xff1f;阿里云ECS服务器u1价格955.58元一年&#xff0c;腾讯云轻量4核8G12M带宽价格是646元15个月&#xff0c;阿腾云atengyun.com整理4核8G云服务器价格表&#xff0c;包括一年费用和1个月收费明细&#xff1a; 云服务器4核8G配置收费价格 阿里…

盲盒小程序开发

现如今&#xff0c;盲盒已经成为了市场上不可忽视的新型消费模式&#xff0c;并且也逐渐遍布在全球各地中。盲盒的种类商品也逐渐丰富完善&#xff0c;不在局限于性价比高的盲盒玩具、手办等&#xff0c;也发展到了美妆、电子、食品等行业&#xff0c;具有较大的实用性和收藏价…

leetcode:416.分割等和子集

解题思路&#xff1a; 转化为01背包问题&#xff0c;集合中每个元素只能用一次&#xff0c;看能不能凑出sum//2这个重量。&#xff08;重量值价值值&#xff09; dp含义&#xff1a;前重量j所获得的最大价值 递推公式&#xff1a;dp[j] max(dp[j],dp[j-numbers[i]] number…

几种SLAM算法跑出的效果比较

以下所有的SLAM算法均使用此辆ROS小车跑。 文章目录 1.Gmapping SLAM算法构建地图2.Hector SLAM算法构建地图3.Karto SLAM算法构建地图4.Cartographer SLAM算法构建地图5.深度摄像头的建图6.rtab-map(深度双目与激光雷达构建三维建图)7.ORB-SLAM8.无奖竞猜 1.Gmapping SLAM算法…

SHERlocked93 的 2021 年终总结

我还是和往年一样&#xff0c;总结发的又晚了一点&#xff0c;为什么又发这么晚呢&#xff0c;因为懒 年终总结 疫情之后时间时间过的太快了&#xff0c;不知道是不是只有我这样感觉。 四五月份去兰州玩了下&#xff08;其实是出差&#xff09;&#xff0c;终于看到了黄土高原&…

JDK8新特性:方法引用

进一步简化Lambda表达式 一、静态方法的引用 格式&#xff1a; 类名::静态方法 使用场景&#xff1a;如果某个Lambda表达式里只是调用一个静态方法&#xff0c;并且前后参数的形式一致&#xff0c;就可以使用静态方法引用。 之前使用Lambda简化&#xff1a; 现在我们创建一…

springboot单体项目快速生成代码

生成的是这些代码&#xff1a;controller,entity,mapper,service,service里面的impl,还有xml import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolk…

【C语言】长篇详解,字符系列篇1-----“混杂”的各种字符类型字符转换和strcpy的使用,模拟实现【图文详解】

欢迎来CILMY23的博客喔&#xff0c;本期系列为【C语言】长篇详解&#xff0c;字符系列篇1-----“混杂”的各种字符函数……&#xff0c;图文讲解各种字符函数&#xff0c;带大家更深刻理解C语言中各种字符函数的应用&#xff0c;感谢观看&#xff0c;支持的可以给个赞哇。 前言…