• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <future>
20 #include <memory>
21 #include <mutex>
22 #include <queue>
23 #include <thread>
24 
25 #include "refbase.h"
26 #include "rs_base_render_engine.h"
27 #include "vsync_distributor.h"
28 #include <event_handler.h>
29 #include "vsync_receiver.h"
30 
31 #include "command/rs_command.h"
32 #include "common/rs_thread_handler.h"
33 #include "common/rs_thread_looper.h"
34 #include "ipc_callbacks/iapplication_agent.h"
35 #include "ipc_callbacks/rs_iocclusion_change_callback.h"
36 #include "ipc_callbacks/rs_irender_mode_change_callback.h"
37 #include "pipeline/rs_context.h"
38 #include "pipeline/rs_uni_render_judgement.h"
39 #include "platform/drawing/rs_vsync_client.h"
40 #include "platform/common/rs_event_manager.h"
41 #include "transaction/rs_transaction_data.h"
42 
43 namespace OHOS::Rosen {
44 class AccessibilityObserver;
45 namespace Detail {
46 template<typename Task>
47 class ScheduledTask : public RefBase {
48 public:
Create(Task && task)49     static auto Create(Task&& task)
50     {
51         sptr<ScheduledTask<Task>> t(new ScheduledTask(std::forward<Task&&>(task)));
52         return std::make_pair(t, t->task_.get_future());
53     }
54 
Run()55     void Run()
56     {
57         task_();
58     }
59 
60 private:
ScheduledTask(Task && task)61     explicit ScheduledTask(Task&& task) : task_(std::move(task)) {}
62     ~ScheduledTask() override = default;
63 
64     using Return = std::invoke_result_t<Task>;
65     std::packaged_task<Return()> task_;
66 };
67 } // namespace Detail
68 
69 class RSMainThread {
70 public:
71     static RSMainThread* Instance();
72 
73     void Init();
74     void Start();
75     void RecvRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
76     void RequestNextVSync();
77     void PostTask(RSTaskMessage::RSTask task);
78     void PostSyncTask(RSTaskMessage::RSTask task);
79     void QosStateDump(std::string& dumpString);
80     void RenderServiceTreeDump(std::string& dumpString);
81     void RsEventParamDump(std::string& dumpString);
82 
83     template<typename Task, typename Return = std::invoke_result_t<Task>>
ScheduleTask(Task && task)84     std::future<Return> ScheduleTask(Task&& task)
85     {
86         auto [scheduledTask, taskFuture] = Detail::ScheduledTask<Task>::Create(std::forward<Task&&>(task));
87         PostTask([t(std::move(scheduledTask))]() { t->Run(); });
88         return std::move(taskFuture);
89     }
90 
GetRenderEngine()91     const std::shared_ptr<RSBaseRenderEngine>& GetRenderEngine() const
92     {
93         return IfUseUniVisitor() ? uniRenderEngine_ : renderEngine_;
94     }
95 
GetContext()96     RSContext& GetContext()
97     {
98         return *context_;
99     }
Id()100     std::thread::id Id() const
101     {
102         return mainThreadId_;
103     }
104     void RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app);
105     void UnRegisterApplicationAgent(sptr<IApplicationAgent> app);
106     void NotifyRenderModeChanged(bool useUniVisitor);
107     bool QueryIfUseUniVisitor() const;
108 
109     void RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback);
110     void UnRegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback);
111     void CleanOcclusionListener();
112 
113     void WaitUtilUniRenderFinished();
114     void NotifyUniRenderFinish();
115     void SetRenderModeChangeCallback(sptr<RSIRenderModeChangeCallback> callback);
116     bool IfUseUniVisitor() const;
117 
118     void ClearTransactionDataPidInfo(pid_t remotePid);
119     void AddTransactionDataPidInfo(pid_t remotePid);
120 
121     void SetFocusAppInfo(
122         int32_t pid, int32_t uid, const std::string &bundleName, const std::string &abilityName);
123 
124     sptr<VSyncDistributor> rsVSyncDistributor_;
125 
126     void SetDirtyFlag();
127     void ForceRefreshForUni();
128     void SetAppWindowNum(uint32_t num);
129 private:
130     using TransactionDataIndexMap = std::unordered_map<pid_t,
131         std::pair<uint64_t, std::vector<std::unique_ptr<RSTransactionData>>>>;
132 
133     RSMainThread();
134     ~RSMainThread() noexcept;
135     RSMainThread(const RSMainThread&) = delete;
136     RSMainThread(const RSMainThread&&) = delete;
137     RSMainThread& operator=(const RSMainThread&) = delete;
138     RSMainThread& operator=(const RSMainThread&&) = delete;
139 
140     void OnVsync(uint64_t timestamp, void* data);
141     void ProcessCommand();
142     void Animate(uint64_t timestamp);
143     void ConsumeAndUpdateAllNodes();
144     void ReleaseAllNodesBuffer();
145     void Render();
146     void CalcOcclusion();
147     bool CheckQosVisChanged(std::map<uint32_t, bool>& pidVisMap);
148     void CallbackToQOS(std::map<uint32_t, bool>& pidVisMap);
149     void CallbackToWMS(VisibleData& curVisVec);
150     void SendCommands();
151     void InitRSEventDetector();
152     void RemoveRSEventDetector();
153     void SetRSEventDetectorLoopStartTag();
154     void SetRSEventDetectorLoopFinishTag();
155 
156     bool DoParallelComposition(std::shared_ptr<RSBaseRenderNode> rootNode);
157     void ResetSortedChildren(std::shared_ptr<RSBaseRenderNode> node);
158 
159     void ClassifyRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
160     void ProcessCommandForDividedRender();
161     void ProcessCommandForUniRender();
162     void WaitUntilUnmarshallingTaskFinished();
163     void MergeToEffectiveTransactionDataMap(TransactionDataMap& cachedTransactionDataMap);
164 
165     void CheckBufferAvailableIfNeed();
166     void CheckUpdateSurfaceNodeIfNeed();
167 
168     void CheckDelayedSwitchTask();
169     void UpdateRenderMode(bool useUniVisitor);
170 
171     void CheckColdStartMap();
172     void ClearDisplayBuffer();
173     void PerfAfterAnim();
174     void PerfForBlurIfNeeded();
175     void PerfMultiWindow();
176 
177     std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr;
178     std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
179     RSTaskMessage::RSTask mainLoop_;
180     std::unique_ptr<RSVsyncClient> vsyncClient_ = nullptr;
181     std::unordered_map<NodeId, uint64_t> bufferTimestamps_;
182 
183     std::mutex transitionDataMutex_;
184     std::unordered_map<NodeId, std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>>> cachedCommands_;
185     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> effectiveCommands_;
186     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> pendingEffectiveCommands_;
187     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> followVisitorCommands_;
188 
189     TransactionDataMap cachedTransactionDataMap_;
190     TransactionDataIndexMap effectiveTransactionDataIndexMap_;
191     std::unordered_map<pid_t, uint64_t> transactionDataLastWaitTime_;
192 
193     uint64_t timestamp_ = 0;
194     uint64_t lastAnimateTimestamp_ = 0;
195     uint64_t prePerfTimestamp_ = 0;
196     uint64_t lastCleanCacheTimestamp_ = 0;
197     std::unordered_map<uint32_t, sptr<IApplicationAgent>> applicationAgentMap_;
198 
199     std::shared_ptr<RSContext> context_;
200     std::thread::id mainThreadId_;
201     std::shared_ptr<VSyncReceiver> receiver_ = nullptr;
202     std::vector<sptr<RSIOcclusionChangeCallback>> occlusionListeners_;
203 
204     bool waitingBufferAvailable_ = false; // uni->non-uni mode, wait for RT buffer, only used in main thread
205     bool waitingUpdateSurfaceNode_ = false; // non-uni->uni mode, wait for update surfaceView, only used in main thread
206     bool isUniRender_ = RSUniRenderJudgement::IsUniRender();
207     sptr<RSIRenderModeChangeCallback> renderModeChangeCallback_;
208     std::atomic_bool useUniVisitor_ = isUniRender_;
209     std::atomic_bool delayedTargetUniVisitor_ = isUniRender_;
210     std::atomic_bool switchDelayed_ = false;
211     RSTaskMessage::RSTask unmarshalBarrierTask_;
212     std::condition_variable unmarshalTaskCond_;
213     std::mutex unmarshalMutex_;
214     int32_t unmarshalFinishedCount_ = 0;
215 
216     mutable std::mutex uniRenderMutex_;
217     bool uniRenderFinished_ = false;
218     std::condition_variable uniRenderCond_;
219     std::map<uint32_t, bool> lastPidVisMap_;
220     VisibleData lastVisVec_;
221     bool qosPidCal_ = false;
222     bool isDirty_ = false;
223     std::atomic_bool doWindowAnimate_ = false;
224     uint32_t lastSurfaceCnt_ = 0;
225     int32_t focusAppPid_ = -1;
226     int32_t focusAppUid_ = -1;
227     std::string focusAppBundleName_ = "";
228     std::string focusAppAbilityName_ = "";
229     uint32_t appWindowNum_ = 0;
230     uint32_t requestNextVsyncNum_ = 0;
231 
232     std::shared_ptr<RSBaseRenderEngine> renderEngine_;
233     std::shared_ptr<RSBaseRenderEngine> uniRenderEngine_;
234     std::shared_ptr<RSBaseEventDetector> rsCompositionTimeoutDetector_;
235     RSEventManager rsEventManager_;
236     std::shared_ptr<AccessibilityObserver> accessibilityObserver_;
237 };
238 } // namespace OHOS::Rosen
239 #endif // RS_MAIN_THREAD
240