• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef RS_MAIN_THREAD
17 #define RS_MAIN_THREAD
18 
19 #include <event_handler.h>
20 #include <future>
21 #include <memory>
22 #include <mutex>
23 #include <queue>
24 #include <set>
25 #include <thread>
26 
27 #include "refbase.h"
28 #include "rs_base_render_engine.h"
29 #include "rs_draw_frame.h"
30 #include "vsync_distributor.h"
31 #include "vsync_receiver.h"
32 
33 #include "command/rs_command.h"
34 #include "common/rs_common_def.h"
35 #include "common/rs_thread_handler.h"
36 #include "common/rs_thread_looper.h"
37 #include "drawable/rs_render_node_drawable_adapter.h"
38 #include "ipc_callbacks/iapplication_agent.h"
39 #include "ipc_callbacks/rs_iocclusion_change_callback.h"
40 #include "ipc_callbacks/rs_isurface_occlusion_change_callback.h"
41 #include "ipc_callbacks/rs_iuiextension_callback.h"
42 #include "memory/rs_app_state_listener.h"
43 #include "memory/rs_memory_graphic.h"
44 #include "params/rs_render_thread_params.h"
45 #include "pipeline/rs_context.h"
46 #include "pipeline/rs_draw_frame.h"
47 #include "pipeline/rs_uni_render_judgement.h"
48 #include "platform/common/rs_event_manager.h"
49 #include "platform/drawing/rs_vsync_client.h"
50 #include "transaction/rs_transaction_data.h"
51 #include "transaction/rs_uiextension_data.h"
52 
53 #ifdef RES_SCHED_ENABLE
54 #include "vsync_system_ability_listener.h"
55 #endif
56 
57 namespace OHOS::Rosen {
58 #if defined(ACCESSIBILITY_ENABLE)
59 class AccessibilityObserver;
60 #endif
61 class HgmFrameRateManager;
62 class RSUniRenderVisitor;
63 struct FrameRateRangeData;
64 namespace Detail {
65 template<typename Task>
66 class ScheduledTask : public RefBase {
67 public:
Create(Task && task)68     static auto Create(Task&& task)
69     {
70         sptr<ScheduledTask<Task>> t(new ScheduledTask(std::forward<Task&&>(task)));
71         return std::make_pair(t, t->task_.get_future());
72     }
73 
Run()74     void Run()
75     {
76         task_();
77     }
78 
79 private:
ScheduledTask(Task && task)80     explicit ScheduledTask(Task&& task) : task_(std::move(task)) {}
81     ~ScheduledTask() override = default;
82 
83     using Return = std::invoke_result_t<Task>;
84     std::packaged_task<Return()> task_;
85 };
86 } // namespace Detail
87 
88 class RSMainThread {
89 public:
90     static RSMainThread* Instance();
91 
92     void Init();
93     void Start();
94     void UpdateFocusNodeId(NodeId focusNodeId);
95     void UpdateNeedDrawFocusChange(NodeId id);
96     bool IsNeedProcessBySingleFrameComposer(std::unique_ptr<RSTransactionData>& rsTransactionData);
97     void ProcessDataBySingleFrameComposer(std::unique_ptr<RSTransactionData>& rsTransactionData);
98     void RecvAndProcessRSTransactionDataImmediately(std::unique_ptr<RSTransactionData>& rsTransactionData);
99     void RecvRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
100     void RequestNextVSync(const std::string& fromWhom = "unknown", int64_t lastVSyncTS = 0);
101     void PostTask(RSTaskMessage::RSTask task);
102     void PostTask(RSTaskMessage::RSTask task, const std::string& name, int64_t delayTime,
103         AppExecFwk::EventQueue::Priority priority = AppExecFwk::EventQueue::Priority::IDLE);
104     void RemoveTask(const std::string& name);
105     void PostSyncTask(RSTaskMessage::RSTask task);
106     bool IsIdle() const;
107     void TransactionDataMapDump(const TransactionDataMap& transactionDataMap, std::string& dumpString);
108     void RenderServiceTreeDump(std::string& dumpString, bool forceDumpSingleFrame = true);
109     void SendClientDumpNodeTreeCommands(uint32_t taskId);
110     void CollectClientNodeTreeResult(uint32_t taskId, std::string& dumpString, size_t timeout);
111     void RsEventParamDump(std::string& dumpString);
112     bool IsUIFirstOn() const;
113     void UpdateAnimateNodeFlag();
114     void ResetAnimateNodeFlag();
115     void GetAppMemoryInMB(float& cpuMemSize, float& gpuMemSize);
116     void ClearMemoryCache(ClearMemoryMoment moment, bool deeply = false, pid_t pid = -1);
117     static bool CheckIsHdrSurface(const RSSurfaceRenderNode& surfaceNode);
118 
119     template<typename Task, typename Return = std::invoke_result_t<Task>>
ScheduleTask(Task && task)120     std::future<Return> ScheduleTask(Task&& task)
121     {
122         auto [scheduledTask, taskFuture] = Detail::ScheduledTask<Task>::Create(std::forward<Task&&>(task));
123         PostTask([t(std::move(scheduledTask))]() { t->Run(); });
124         return std::move(taskFuture);
125     }
126 
GetRenderEngine()127     const std::shared_ptr<RSBaseRenderEngine> GetRenderEngine() const
128     {
129         RS_LOGD("You'd better to call GetRenderEngine from RSUniRenderThread directly");
130         return isUniRender_ ? std::move(RSUniRenderThread::Instance().GetRenderEngine()) : renderEngine_;
131     }
132 
GetClearMemoryFinished()133     bool GetClearMemoryFinished() const
134     {
135         return clearMemoryFinished_;
136     }
137 
GetContext()138     RSContext& GetContext()
139     {
140         return *context_;
141     }
142 
Id()143     std::thread::id Id() const
144     {
145         return mainThreadId_;
146     }
147 
CheckIsHardwareEnabledBufferUpdated()148     bool CheckIsHardwareEnabledBufferUpdated() const
149     {
150         return isHardwareEnabledBufferUpdated_;
151     }
152 
SetGlobalDarkColorMode(bool isDark)153     void SetGlobalDarkColorMode(bool isDark)
154     {
155         isGlobalDarkColorMode_ = isDark;
156     }
157 
GetGlobalDarkColorMode()158     bool GetGlobalDarkColorMode() const
159     {
160         return isGlobalDarkColorMode_;
161     }
162 
163     /* Judge if rootnode has to be prepared based on it corresponding process is active
164      * If its pid is in activeProcessPids_ set, return true
165      */
166     bool CheckNodeHasToBePreparedByPid(NodeId nodeId, bool isClassifyByRoot);
167     // check if active app has static drawing cache
168     bool IsDrawingGroupChanged(const RSRenderNode& cacheRootNode) const;
169     // check if active instance only move or scale it's main window surface without rearrangement
170     // instanceNodeId should be MainWindowType, or it cannot grep correct app's info
171     void CheckAndUpdateInstanceContentStaticStatus(std::shared_ptr<RSSurfaceRenderNode> instanceNode) const;
172 
173     void RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app);
174     void UnRegisterApplicationAgent(sptr<IApplicationAgent> app);
175 
176     void RegisterOcclusionChangeCallback(pid_t pid, sptr<RSIOcclusionChangeCallback> callback);
177     void UnRegisterOcclusionChangeCallback(pid_t pid);
178 
179     void RegisterSurfaceOcclusionChangeCallback(
180         NodeId id, pid_t pid, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints);
181     void UnRegisterSurfaceOcclusionChangeCallback(NodeId id);
182     void ClearSurfaceOcclusionChangeCallback(pid_t pid);
183     bool SurfaceOcclusionCallBackIfOnTreeStateChanged();
184 
185     void WaitUtilUniRenderFinished();
186     void NotifyUniRenderFinish();
187 
188     bool WaitHardwareThreadTaskExecute();
189     void NotifyHardwareThreadCanExecuteTask();
190 
191     void ClearTransactionDataPidInfo(pid_t remotePid);
192     void AddTransactionDataPidInfo(pid_t remotePid);
193 
194     void SetFocusAppInfo(
195         int32_t pid, int32_t uid, const std::string& bundleName, const std::string& abilityName, uint64_t focusNodeId);
196     const std::unordered_map<NodeId, bool>& GetCacheCmdSkippedNodes() const;
197 
198     sptr<VSyncDistributor> rsVSyncDistributor_;
199     sptr<VSyncController> rsVSyncController_;
200     sptr<VSyncController> appVSyncController_;
201     sptr<VSyncGenerator> vsyncGenerator_;
202 
203     void ReleaseSurface();
204     void AddToReleaseQueue(std::shared_ptr<Drawing::Surface>&& surface);
205 
206     void AddUiCaptureTask(NodeId id, std::function<void()> task);
207     void ProcessUiCaptureTasks();
208 
209     void SetDirtyFlag(bool isDirty = true);
210     bool GetDirtyFlag();
211     void SetNoNeedToPostTask(bool noNeedToPostTask);
212     void SetAccessibilityConfigChanged();
213     void SetScreenPowerOnChanged(bool val);
214     bool GetScreenPowerOnChanged() const;
215     bool IsAccessibilityConfigChanged() const;
216     bool IsCurtainScreenUsingStatusChanged() const;
217     void ForceRefreshForUni();
218     void TrimMem(std::unordered_set<std::u16string>& argSets, std::string& result);
219     void DumpMem(std::unordered_set<std::u16string>& argSets, std::string& result, std::string& type, pid_t pid = 0);
220     void CountMem(int pid, MemoryGraphic& mem);
221     void CountMem(std::vector<MemoryGraphic>& mems);
222     void SetAppWindowNum(uint32_t num);
223     bool SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes);
224     SystemAnimatedScenes GetSystemAnimatedScenes();
225     void ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool flag);
226     void SetIsCachedSurfaceUpdated(bool isCachedSurfaceUpdated);
227     pid_t GetDesktopPidForRotationScene() const;
SetForceUpdateUniRenderFlag(bool flag)228     void SetForceUpdateUniRenderFlag(bool flag)
229     {
230         forceUpdateUniRenderFlag_ = flag;
231     }
SetIdleTimerExpiredFlag(bool flag)232     void SetIdleTimerExpiredFlag(bool flag)
233     {
234         idleTimerExpiredFlag_ = flag;
235     }
SetRSIdleTimerExpiredFlag(bool flag)236     void SetRSIdleTimerExpiredFlag(bool flag)
237     {
238         rsIdleTimerExpiredFlag_ = flag;
239     }
240     std::shared_ptr<Drawing::Image> GetWatermarkImg();
241     bool GetWatermarkFlag();
242 
IsWatermarkFlagChanged()243     bool IsWatermarkFlagChanged() const
244     {
245         return lastWatermarkFlag_ != watermarkFlag_;
246     }
247 
GetFrameCount()248     uint64_t GetFrameCount() const
249     {
250         return frameCount_;
251     }
GetDrawStatusVec()252     std::vector<NodeId>& GetDrawStatusVec()
253     {
254         return curDrawStatusVec_;
255     }
SetAppVSyncDistributor(const sptr<VSyncDistributor> & appVSyncDistributor)256     void SetAppVSyncDistributor(const sptr<VSyncDistributor>& appVSyncDistributor)
257     {
258         appVSyncDistributor_ = appVSyncDistributor;
259     }
260 
261     DeviceType GetDeviceType() const;
262     bool IsSingleDisplay();
263     bool HasMirrorDisplay() const;
264     bool GetNoNeedToPostTask();
265     uint64_t GetFocusNodeId() const;
266     uint64_t GetFocusLeashWindowId() const;
GetClearMemDeeply()267     bool GetClearMemDeeply() const
268     {
269         return clearMemDeeply_;
270     }
271 
GetClearMoment()272     ClearMemoryMoment GetClearMoment() const
273     {
274         if (!context_) {
275             return ClearMemoryMoment::NO_CLEAR;
276         }
277         return context_->clearMoment_;
278     }
279 
SetClearMoment(ClearMemoryMoment moment)280     void SetClearMoment(ClearMemoryMoment moment)
281     {
282         if (!context_) {
283             return;
284         }
285         context_->clearMoment_ = moment;
286     }
287 
IsPCThreeFingerScenesListScene()288     bool IsPCThreeFingerScenesListScene() const
289     {
290         return !threeFingerScenesList_.empty();
291     }
292 
293     void SurfaceOcclusionChangeCallback(VisibleData& dstCurVisVec);
294     void SurfaceOcclusionCallback();
295     void SubscribeAppState();
296     void HandleOnTrim(Memory::SystemMemoryLevel level);
297     void SetCurtainScreenUsingStatus(bool isCurtainScreenOn);
298     void AddPidNeedDropFrame(std::vector<int32_t> pid);
299     void ClearNeedDropframePidList();
300     bool IsNeedDropFrameByPid(NodeId nodeId);
301     void SetLuminanceChangingStatus(bool isLuminanceChanged);
302     bool ExchangeLuminanceChangingStatus();
303     bool IsCurtainScreenOn() const;
304 
305     bool GetParallelCompositionEnabled();
GetFrameRateMgr()306     std::shared_ptr<HgmFrameRateManager> GetFrameRateMgr() { return frameRateMgr_; };
307     void SetFrameIsRender(bool isRender);
308     const std::vector<std::shared_ptr<RSSurfaceRenderNode>>& GetSelfDrawingNodes() const;
309     const std::vector<DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr>& GetSelfDrawables() const;
310 
IsOnVsync()311     bool IsOnVsync() const
312     {
313         return isOnVsync_.load();
314     }
315 
GetDiscardJankFrames()316     bool GetDiscardJankFrames() const
317     {
318         return discardJankFrames_.load();
319     }
320 
SetDiscardJankFrames(bool discardJankFrames)321     void SetDiscardJankFrames(bool discardJankFrames)
322     {
323         if (discardJankFrames_.load() != discardJankFrames) {
324             discardJankFrames_.store(discardJankFrames);
325         }
326     }
327 
GetSkipJankAnimatorFrame()328     bool GetSkipJankAnimatorFrame() const
329     {
330         return skipJankAnimatorFrame_.load();
331     }
332 
IsFirstFrameOfDrawingCacheDFXSwitch()333     bool IsFirstFrameOfDrawingCacheDFXSwitch() const
334     {
335         return isDrawingCacheDfxEnabledOfCurFrame_ != isDrawingCacheDfxEnabledOfLastFrame_;
336     }
337 
SetDrawingCacheDfxEnabledOfCurFrame(bool isDrawingCacheDfxEnabledOfCurFrame)338     void SetDrawingCacheDfxEnabledOfCurFrame(bool isDrawingCacheDfxEnabledOfCurFrame)
339     {
340         isDrawingCacheDfxEnabledOfCurFrame_ = isDrawingCacheDfxEnabledOfCurFrame;
341     }
342 
SetSkipJankAnimatorFrame(bool skipJankAnimatorFrame)343     void SetSkipJankAnimatorFrame(bool skipJankAnimatorFrame)
344     {
345         skipJankAnimatorFrame_.store(skipJankAnimatorFrame);
346     }
347 
348     bool IsRequestedNextVSync();
349 
GetNextDVsyncAnimateFlag()350     bool GetNextDVsyncAnimateFlag() const
351     {
352         return needRequestNextVsyncAnimate_;
353     }
354 
IsFirstFrameOfPartialRender()355     bool IsFirstFrameOfPartialRender() const
356     {
357         return isFirstFrameOfPartialRender_;
358     }
359 
360     bool IsHardwareEnabledNodesNeedSync();
361     bool IsOcclusionNodesNeedSync(NodeId id, bool useCurWindow);
362 
363     void CallbackDrawContextStatusToWMS(bool isUniRender = false);
364     void SetHardwareTaskNum(uint32_t num);
365     void RegisterUIExtensionCallback(pid_t pid, uint64_t userId, sptr<RSIUIExtensionCallback> callback,
366         bool unobscured = false);
367     void UnRegisterUIExtensionCallback(pid_t pid);
368 
369     void SetAncoForceDoDirect(bool direct);
370 
IsFirstFrameOfOverdrawSwitch()371     bool IsFirstFrameOfOverdrawSwitch() const
372     {
373         return isOverDrawEnabledOfCurFrame_ != isOverDrawEnabledOfLastFrame_;
374     }
375 
376     uint64_t GetRealTimeOffsetOfDvsync(int64_t time);
GetCurrentVsyncTime()377     uint64_t GetCurrentVsyncTime() const
378     {
379         return curTime_;
380     }
381 
GetMultiDisplayChange()382     bool GetMultiDisplayChange() const
383     {
384         return isMultiDisplayChange_;
385     }
GetMultiDisplayStatus()386     bool GetMultiDisplayStatus() const
387     {
388         return isMultiDisplayPre_;
389     }
StartGPUDraw()390     void StartGPUDraw()
391     {
392         gpuDrawCount_.fetch_add(1, std::memory_order_relaxed);
393     }
394 
EndGPUDraw()395     void EndGPUDraw()
396     {
397         if (gpuDrawCount_.fetch_sub(1, std::memory_order_acq_rel) == 1) {
398             // gpuDrawCount_ is now 0
399             ClearUnmappedCache();
400         }
401     }
402 
403     struct GPUCompositonCacheGuard {
GPUCompositonCacheGuardGPUCompositonCacheGuard404         GPUCompositonCacheGuard()
405         {
406             RSMainThread::Instance()->StartGPUDraw();
407         }
~GPUCompositonCacheGuardGPUCompositonCacheGuard408         ~GPUCompositonCacheGuard()
409         {
410             RSMainThread::Instance()->EndGPUDraw();
411         }
412     };
413 
AddToUnmappedCacheSet(int32_t bufferId)414     void AddToUnmappedCacheSet(int32_t bufferId)
415     {
416         std::lock_guard<std::mutex> lock(unmappedCacheSetMutex_);
417         unmappedCacheSet_.insert(bufferId);
418     }
419 
420     void ClearUnmappedCache();
421     void InitVulkanErrorCallback(Drawing::GPUContext* gpuContext);
422 private:
423     using TransactionDataIndexMap = std::unordered_map<pid_t,
424         std::pair<uint64_t, std::vector<std::unique_ptr<RSTransactionData>>>>;
425     using DrawablesVec = std::vector<std::pair<NodeId,
426         DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr>>;
427 
428     RSMainThread();
429     ~RSMainThread() noexcept;
430     RSMainThread(const RSMainThread&) = delete;
431     RSMainThread(const RSMainThread&&) = delete;
432     RSMainThread& operator=(const RSMainThread&) = delete;
433     RSMainThread& operator=(const RSMainThread&&) = delete;
434 
435     void OnVsync(uint64_t timestamp, uint64_t frameCount, void* data);
436     void ProcessCommand();
437     void UpdateSubSurfaceCnt();
438     void Animate(uint64_t timestamp);
439     void ConsumeAndUpdateAllNodes();
440     void CollectInfoForHardwareComposer();
441     void ReleaseAllNodesBuffer();
442     void Render();
443     void OnUniRenderDraw();
444     void SetDeviceType();
445     void UniRender(std::shared_ptr<RSBaseRenderNode> rootNode);
446     bool CheckSurfaceNeedProcess(OcclusionRectISet& occlusionSurfaces, std::shared_ptr<RSSurfaceRenderNode> curSurface);
447     void CalcOcclusionImplementation(std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces,
448         VisibleData& dstCurVisVec, std::map<NodeId, RSVisibleLevel>& dstPidVisMap);
449     void CalcOcclusion();
450     bool CheckSurfaceVisChanged(std::map<NodeId, RSVisibleLevel>& pidVisMap,
451         std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces);
452     void SetVSyncRateByVisibleLevel(std::map<NodeId, RSVisibleLevel>& pidVisMap,
453         std::vector<RSBaseRenderNode::SharedPtr>& curAllSurfaces);
454     void CallbackToWMS(VisibleData& curVisVec);
455     void SendCommands();
456     void InitRSEventDetector();
457     void RemoveRSEventDetector();
458     void SetRSEventDetectorLoopStartTag();
459     void SetRSEventDetectorLoopFinishTag();
460     void CheckSystemSceneStatus();
461     void UpdateUIFirstSwitch();
462     // ROG: Resolution Online Government
463     void UpdateRogSizeIfNeeded();
464     void UpdateDisplayNodeScreenId();
465     uint32_t GetRefreshRate() const;
466     uint32_t GetDynamicRefreshRate() const;
467     void SkipCommandByNodeId(std::vector<std::unique_ptr<RSTransactionData>>& transactionVec, pid_t pid);
468     static void OnHideNotchStatusCallback(const char *key, const char *value, void *context);
469     static void OnDrawingCacheDfxSwitchCallback(const char *key, const char *value, void *context);
470 
471     bool DoParallelComposition(std::shared_ptr<RSBaseRenderNode> rootNode);
472 
473     void ClassifyRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
474     void ProcessRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData, pid_t pid);
475     void ProcessSyncRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData, pid_t pid);
476     void ProcessSyncTransactionCount(std::unique_ptr<RSTransactionData>& rsTransactionData);
477     void StartSyncTransactionFallbackTask(std::unique_ptr<RSTransactionData>& rsTransactionData);
478     void ProcessAllSyncTransactionData();
479     void ProcessCommandForDividedRender();
480     void ProcessCommandForUniRender();
481     void WaitUntilUnmarshallingTaskFinished();
482     void MergeToEffectiveTransactionDataMap(TransactionDataMap& cachedTransactionDataMap);
483 
484     void ClearDisplayBuffer();
485     void PerfAfterAnim(bool needRequestNextVsync);
486     void PerfForBlurIfNeeded();
487     void PerfMultiWindow();
488     void RenderFrameStart(uint64_t timestamp);
489     void ResetHardwareEnabledState(bool isUniRender);
490     void CheckIfHardwareForcedDisabled();
491     void CheckAndUpdateTransactionIndex(
492         std::shared_ptr<TransactionDataMap>& transactionDataEffective, std::string& transactionFlags);
493 
494     bool IsResidentProcess(pid_t pid) const;
495     bool IsNeedSkip(NodeId instanceRootNodeId, pid_t pid);
496     void UpdateAceDebugBoundaryEnabled();
497 
498     // UIFirst
499     bool CheckParallelSubThreadNodesStatus();
500     void CacheCommands();
501     bool CheckSubThreadNodeStatusIsDoing(NodeId appNodeId) const;
502 
503     // used for informing hgm the bundle name of SurfaceRenderNodes
504     void InformHgmNodeInfo();
505     void CheckIfNodeIsBundle(std::shared_ptr<RSSurfaceRenderNode> node);
506 
507     void SetFocusLeashWindowId();
508     void ProcessHgmFrameRate(uint64_t timestamp);
509     bool IsLastFrameUIFirstEnabled(NodeId appNodeId) const;
510     RSVisibleLevel GetRegionVisibleLevel(const Occlusion::Region& curRegion,
511         const Occlusion::Region& visibleRegion);
512     void PrintCurrentStatus();
513     void ProcessScreenHotPlugEvents();
514     void WaitUntilUploadTextureTaskFinishedForGL();
515 #ifdef RES_SCHED_ENABLE
516     void SubScribeSystemAbility();
517 #endif
518 #if defined(RS_ENABLE_CHIPSET_VSYNC)
519     void ConnectChipsetVsyncSer();
520     void SetVsyncInfo(uint64_t timestamp);
521 #endif
522 
523     bool DoDirectComposition(std::shared_ptr<RSBaseRenderNode> rootNode, bool waitForRT);
524 
525     void RSJankStatsOnVsyncStart(int64_t onVsyncStartTime, int64_t onVsyncStartTimeSteady,
526                                  float onVsyncStartTimeSteadyFloat);
527     void RSJankStatsOnVsyncEnd(int64_t onVsyncStartTime, int64_t onVsyncStartTimeSteady,
528                                float onVsyncStartTimeSteadyFloat);
529     int64_t GetCurrentSystimeMs() const;
530     int64_t GetCurrentSteadyTimeMs() const;
531     float GetCurrentSteadyTimeMsFloat() const;
532     void RequestNextVsyncForCachedCommand(std::string& transactionFlags, pid_t pid, uint64_t curIndex);
533     void UpdateLuminance();
534     void DvsyncCheckRequestNextVsync();
535 
536     void PrepareUiCaptureTasks(std::shared_ptr<RSUniRenderVisitor> uniVisitor);
537     void UIExtensionNodesTraverseAndCallback();
538     bool CheckUIExtensionCallbackDataChanged() const;
539 
540     void OnCommitDumpClientNodeTree(NodeId nodeId, pid_t pid, uint32_t taskId, const std::string& result);
541 
542     // Used for CommitAndReleaseLayers task
543     void SetFrameInfo(uint64_t frameCount);
544 
545     // Record change status of multi or single display
546     void MultiDisplayChange(bool isMultiDisplay);
547 
548     std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr;
549     std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
550     RSTaskMessage::RSTask mainLoop_;
551     std::unique_ptr<RSVsyncClient> vsyncClient_ = nullptr;
552     std::unordered_map<NodeId, uint64_t> dividedRenderbufferTimestamps_;
553 
554     std::mutex transitionDataMutex_;
555     std::unordered_map<NodeId, std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>>> cachedCommands_;
556     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> effectiveCommands_;
557     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> pendingEffectiveCommands_;
558     std::unordered_map<pid_t, std::vector<std::unique_ptr<RSTransactionData>>> syncTransactionData_;
559     std::unordered_map<int32_t, int32_t> subSyncTransactionCounts_;
560 
561     TransactionDataMap cachedTransactionDataMap_;
562     TransactionDataIndexMap effectiveTransactionDataIndexMap_;
563     std::map<pid_t, std::vector<std::unique_ptr<RSTransactionData>>> cachedSkipTransactionDataMap_;
564     std::unordered_map<pid_t, uint64_t> transactionDataLastWaitTime_;
565 
566     std::set<int32_t> unmappedCacheSet_ = {};
567     std::mutex unmappedCacheSetMutex_;
568     std::atomic<int> gpuDrawCount_ = 0;
569     uint64_t curTime_ = 0;
570     uint64_t timestamp_ = 0;
571     uint64_t vsyncId_ = 0;
572     uint64_t lastAnimateTimestamp_ = 0;
573     uint64_t prePerfTimestamp_ = 0;
574     uint64_t lastCleanCacheTimestamp_ = 0;
575     pid_t lastCleanCachePid_ = -1;
576     int hardwareTid_ = -1;
577     std::string transactionFlags_ = "";
578     std::unordered_map<uint32_t, sptr<IApplicationAgent>> applicationAgentMap_;
579 
580     std::shared_ptr<RSContext> context_;
581     std::thread::id mainThreadId_;
582     std::shared_ptr<VSyncReceiver> receiver_ = nullptr;
583     std::map<pid_t, sptr<RSIOcclusionChangeCallback>> occlusionListeners_;
584     std::mutex occlusionMutex_;
585 
586     bool isUniRender_ = RSUniRenderJudgement::IsUniRender();
587     RSTaskMessage::RSTask unmarshalBarrierTask_;
588     std::condition_variable unmarshalTaskCond_;
589     std::mutex unmarshalMutex_;
590     int32_t unmarshalFinishedCount_ = 0;
591     bool needWaitUnmarshalFinished_ = true;
592     sptr<VSyncDistributor> appVSyncDistributor_ = nullptr;
593 
594 #if defined(RS_ENABLE_PARALLEL_UPLOAD) && defined(RS_ENABLE_GL)
595     RSTaskMessage::RSTask uploadTextureBarrierTask_;
596     std::condition_variable uploadTextureTaskCond_;
597     std::mutex uploadTextureMutex_;
598     int32_t uploadTextureFinishedCount_ = 0;
599     EGLSyncKHR uploadTextureFence;
600 #endif
601 
602     mutable std::mutex uniRenderMutex_;
603     bool uniRenderFinished_ = false;
604     std::condition_variable uniRenderCond_;
605 
606     bool clearMemoryFinished_ = true;
607     bool clearMemDeeply_ = false;
608 
609     // Used to refresh the whole display when AccessibilityConfig is changed
610     bool isAccessibilityConfigChanged_ = false;
611 
612     // Used to refresh the whole display when curtain screen status is changed
613     bool isCurtainScreenUsingStatusChanged_ = false;
614 
615     // Used to refresh the whole display when luminance is changed
616     std::atomic<bool> isLuminanceChanged_ = false;
617 
618     // used for blocking mainThread when hardwareThread has 2 and more task to Execute
619     mutable std::mutex hardwareThreadTaskMutex_;
620     std::condition_variable hardwareThreadTaskCond_;
621 
622     std::map<NodeId, RSVisibleLevel> lastVisMapForVsyncRate_;
623     VisibleData lastVisVec_;
624     std::map<NodeId, uint64_t> lastDrawStatusMap_;
625     std::vector<NodeId> curDrawStatusVec_;
626     bool qosPidCal_ = false;
627 
628     std::atomic<bool> isDirty_ = false;
629     bool prevHdrSwitchStatus_ = true;
630     std::atomic<bool> screenPowerOnChanged_ = false;
631     std::atomic_bool doWindowAnimate_ = false;
632     std::vector<NodeId> lastSurfaceIds_;
633     std::atomic<int32_t> focusAppPid_ = -1;
634     std::atomic<int32_t> focusAppUid_ = -1;
635     const uint8_t opacity_ = 255;
636     std::string focusAppBundleName_ = "";
637     std::string focusAppAbilityName_ = "";
638     std::atomic<uint64_t> focusNodeId_ = 0;
639     uint64_t focusLeashWindowId_ = 0;
640     std::string focusLeashWindowName_ = "";
641     std::string appWindowName_ = "";
642     uint32_t appPid_ = 0;
643     uint64_t lastFocusNodeId_ = 0;
644     uint64_t appWindowId_ = 0;
645     uint32_t appWindowNum_ = 0;
646     std::atomic<uint32_t> requestNextVsyncNum_ = 0;
647     bool lastFrameHasFilter_ = false;
648     bool vsyncControlEnabled_ = true;
649     bool systemAnimatedScenesEnabled_ = false;
650     bool isFoldScreenDevice_ = false;
651     std::atomic<bool> isGlobalDarkColorMode_ = false;
652 
653     std::atomic_bool noNeedToPostTask_ = false;
654 
655     bool isAceDebugBoundaryEnabledOfLastFrame_ = false;
656     bool hasPostUpdateAceDebugBoundaryTask_ = false;
657 
658     std::shared_ptr<RSBaseRenderEngine> renderEngine_;
659     std::shared_ptr<RSBaseRenderEngine> uniRenderEngine_;
660     std::shared_ptr<RSBaseEventDetector> rsCompositionTimeoutDetector_;
661     RSEventManager rsEventManager_;
662 #if defined(ACCESSIBILITY_ENABLE)
663     std::shared_ptr<AccessibilityObserver> accessibilityObserver_;
664 #endif
665 
666     // used for hardware enabled case
667     bool doDirectComposition_ = true;
668     bool needDrawFrame_ = true;
669     bool needPostAndWait_ = true;
670     bool isLastFrameDirectComposition_ = false;
671     bool isNeedResetClearMemoryTask_ = false;
672     bool isHardwareEnabledBufferUpdated_ = false;
673     std::vector<std::shared_ptr<RSSurfaceRenderNode>> hardwareEnabledNodes_;
674     std::vector<std::shared_ptr<RSSurfaceRenderNode>> selfDrawingNodes_;
675     std::vector<DrawableV2::RSRenderNodeDrawableAdapter::SharedPtr> selfDrawables_;
676     bool isHardwareForcedDisabled_ = false; // if app node has shadow or filter, disable hardware composer for all
677     DrawablesVec hardwareEnabledDrwawables_;
678 
679     // for client node tree dump
680     struct NodeTreeDumpTask {
681         size_t count = 0;
682         size_t completionCount = 0;
683         std::map<pid_t, std::optional<std::string>> data;
684     };
685     std::mutex nodeTreeDumpMutex_;
686     std::condition_variable nodeTreeDumpCondVar_;
687     std::unordered_map<uint32_t, NodeTreeDumpTask> nodeTreeDumpTasks_;
688 
689     // used for watermark
690     std::mutex watermarkMutex_;
691     std::shared_ptr<Drawing::Image> watermarkImg_ = nullptr;
692     bool watermarkFlag_ = false;
693     bool lastWatermarkFlag_ = false;
694     bool doParallelComposition_ = false;
695     bool hasProtectedLayer_ = false;
696 
697     std::shared_ptr<HgmFrameRateManager> frameRateMgr_ = nullptr;
698     std::shared_ptr<RSRenderFrameRateLinker> rsFrameRateLinker_ = nullptr;
699     pid_t desktopPidForRotationScene_ = 0;
700     FrameRateRange rsCurrRange_;
701 
702     // UIFirst
703     std::list<std::shared_ptr<RSSurfaceRenderNode>> subThreadNodes_;
704     std::unordered_map<NodeId, bool> cacheCmdSkippedNodes_;
705     std::unordered_map<pid_t, std::pair<std::vector<NodeId>, bool>> cacheCmdSkippedInfo_;
706     std::atomic<uint64_t> frameCount_ = 0;
707     std::set<std::shared_ptr<RSBaseRenderNode>> oldDisplayChildren_;
708     DeviceType deviceType_ = DeviceType::PHONE;
709     bool isCachedSurfaceUpdated_ = false;
710     bool isUiFirstOn_ = false;
711 
712     // used for informing hgm the bundle name of SurfaceRenderNodes
713     bool noBundle_ = false;
714     std::string currentBundleName_ = "";
715     bool forceUpdateUniRenderFlag_ = false;
716     bool idleTimerExpiredFlag_ = false;
717     bool rsIdleTimerExpiredFlag_ = false;
718     // for ui first
719     std::mutex mutex_;
720     std::queue<std::shared_ptr<Drawing::Surface>> tmpSurfaces_;
721 
722     // for surface occlusion change callback
723     std::mutex surfaceOcclusionMutex_;
724     std::vector<NodeId> lastRegisteredSurfaceOnTree_;
725     std::mutex systemAnimatedScenesMutex_;
726     std::list<std::pair<SystemAnimatedScenes, time_t>> systemAnimatedScenesList_;
727     std::list<std::pair<SystemAnimatedScenes, time_t>> threeFingerScenesList_;
728     bool isReduceVSyncBySystemAnimatedScenes_ = false;
729     std::unordered_map<NodeId, // map<node ID, <pid, callback, partition points vector, level>>
730         std::tuple<pid_t, sptr<RSISurfaceOcclusionChangeCallback>,
731         std::vector<float>, uint8_t>> surfaceOcclusionListeners_;
732     std::unordered_map<NodeId, // map<node ID, <surface node, app window node>>
733         std::pair<std::shared_ptr<RSSurfaceRenderNode>, std::shared_ptr<RSSurfaceRenderNode>>> savedAppWindowNode_;
734 
735     std::shared_ptr<RSAppStateListener> rsAppStateListener_;
736     int32_t subscribeFailCount_ = 0;
737     SystemAnimatedScenes systemAnimatedScenes_ = SystemAnimatedScenes::OTHERS;
738     uint32_t leashWindowCount_ = 0;
739 
740     // for drawing cache dfx
741     bool isDrawingCacheDfxEnabledOfCurFrame_ = false;
742     bool isDrawingCacheDfxEnabledOfLastFrame_ = false;
743 
744     // for ui captures
745     std::vector<std::tuple<NodeId, std::function<void()>>> pendingUiCaptureTasks_;
746     std::queue<std::tuple<NodeId, std::function<void()>>> uiCaptureTasks_;
747 
748     // for dvsync (animate requestNextVSync after mark rsnotrendering)
749     bool needRequestNextVsyncAnimate_ = false;
750 
751     bool forceUIFirstChanged_ = false;
752 
753     // uiextension
754     std::mutex uiExtensionMutex_;
755     UIExtensionCallbackData uiExtensionCallbackData_;
756     bool lastFrameUIExtensionDataEmpty_ = false;
757     UIExtensionCallbackData unobscureduiExtensionCallbackData_;
758     // <pid, <uid, callback>>
759     std::map<pid_t, std::pair<uint64_t, sptr<RSIUIExtensionCallback>>> uiExtensionListenners_ = {};
760     std::map<pid_t, std::pair<uint64_t, sptr<RSIUIExtensionCallback>>> uiUnobscuredExtensionListenners_ = {};
761 
762     // overDraw
763     bool isOverDrawEnabledOfCurFrame_ = false;
764     bool isOverDrawEnabledOfLastFrame_ = false;
765 
766 #ifdef RS_PROFILER_ENABLED
767     friend class RSProfiler;
768 #endif
769 #if defined(RS_ENABLE_CHIPSET_VSYNC)
770     bool initVsyncServiceFlag_ = true;
771 #endif
772     pid_t exitedPid_ = -1;
773     std::set<pid_t> exitedPidSet_;
774     RSDrawFrame drawFrame_;
775     std::unique_ptr<RSRenderThreadParams> renderThreadParams_ = nullptr; // sync to render thread
776     RsParallelType rsParallelType_;
777     bool isCurtainScreenOn_ = false;
778     std::unordered_set<int32_t> surfacePidNeedDropFrame_;
779 #ifdef RES_SCHED_ENABLE
780     sptr<VSyncSystemAbilityListener> saStatusChangeListener_ = nullptr;
781 #endif
782     // for statistic of jank frames
783     std::atomic_bool isOnVsync_ = false;
784     std::atomic_bool discardJankFrames_ = false;
785     std::atomic_bool skipJankAnimatorFrame_ = false;
786     ScreenId displayNodeScreenId_ = 0;
787 
788     // partial render
789     bool isFirstFrameOfPartialRender_ = false;
790     bool isPartialRenderEnabledOfLastFrame_ = false;
791     bool isRegionDebugEnabledOfLastFrame_ = false;
792 
793     bool isForceRefresh_ = false;
794 
795     // record multidisplay status change
796     bool isMultiDisplayChange_ = false;
797     bool isMultiDisplayPre_ = false;
798 };
799 } // namespace OHOS::Rosen
800 #endif // RS_MAIN_THREAD
801