• 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(pid_t pid, sptr<RSIOcclusionChangeCallback> callback);
110     void UnRegisterOcclusionChangeCallback(pid_t pid);
111 
112     void WaitUtilUniRenderFinished();
113     void NotifyUniRenderFinish();
114     void SetRenderModeChangeCallback(sptr<RSIRenderModeChangeCallback> callback);
115     bool IfUseUniVisitor() const;
116 
117     void ClearTransactionDataPidInfo(pid_t remotePid);
118     void AddTransactionDataPidInfo(pid_t remotePid);
119 
120     void SetFocusAppInfo(
121         int32_t pid, int32_t uid, const std::string &bundleName, const std::string &abilityName);
122 
123     sptr<VSyncDistributor> rsVSyncDistributor_;
124 
125     void SetDirtyFlag();
126     void ForceRefreshForUni();
127     void SetAppWindowNum(uint32_t num);
128 private:
129     using TransactionDataIndexMap = std::unordered_map<pid_t,
130         std::pair<uint64_t, std::vector<std::unique_ptr<RSTransactionData>>>>;
131 
132     RSMainThread();
133     ~RSMainThread() noexcept;
134     RSMainThread(const RSMainThread&) = delete;
135     RSMainThread(const RSMainThread&&) = delete;
136     RSMainThread& operator=(const RSMainThread&) = delete;
137     RSMainThread& operator=(const RSMainThread&&) = delete;
138 
139     void OnVsync(uint64_t timestamp, void* data);
140     void ProcessCommand();
141     void Animate(uint64_t timestamp);
142     void ConsumeAndUpdateAllNodes();
143     void ReleaseAllNodesBuffer();
144     void Render();
145     void CalcOcclusion();
146     bool CheckQosVisChanged(std::map<uint32_t, bool>& pidVisMap);
147     void CallbackToQOS(std::map<uint32_t, bool>& pidVisMap);
148     void CallbackToWMS(VisibleData& curVisVec);
149     void SendCommands();
150     void InitRSEventDetector();
151     void RemoveRSEventDetector();
152     void SetRSEventDetectorLoopStartTag();
153     void SetRSEventDetectorLoopFinishTag();
154 
155     bool DoParallelComposition(std::shared_ptr<RSBaseRenderNode> rootNode);
156     void ResetSortedChildren(std::shared_ptr<RSBaseRenderNode> node);
157 
158     void ClassifyRSTransactionData(std::unique_ptr<RSTransactionData>& rsTransactionData);
159     void ProcessCommandForDividedRender();
160     void ProcessCommandForUniRender();
161     void WaitUntilUnmarshallingTaskFinished();
162     void MergeToEffectiveTransactionDataMap(TransactionDataMap& cachedTransactionDataMap);
163 
164     void CheckBufferAvailableIfNeed();
165     void CheckUpdateSurfaceNodeIfNeed();
166 
167     void CheckDelayedSwitchTask();
168     void UpdateRenderMode(bool useUniVisitor);
169 
170     void CheckColdStartMap();
171     void ClearDisplayBuffer();
172     void PerfAfterAnim();
173     void PerfForBlurIfNeeded();
174     void PerfMultiWindow();
175 
176     std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr;
177     std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
178     RSTaskMessage::RSTask mainLoop_;
179     std::unique_ptr<RSVsyncClient> vsyncClient_ = nullptr;
180     std::unordered_map<NodeId, uint64_t> bufferTimestamps_;
181 
182     std::mutex transitionDataMutex_;
183     std::unordered_map<NodeId, std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>>> cachedCommands_;
184     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> effectiveCommands_;
185     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> pendingEffectiveCommands_;
186     std::map<uint64_t, std::vector<std::unique_ptr<RSCommand>>> followVisitorCommands_;
187 
188     TransactionDataMap cachedTransactionDataMap_;
189     TransactionDataIndexMap effectiveTransactionDataIndexMap_;
190     std::unordered_map<pid_t, uint64_t> transactionDataLastWaitTime_;
191 
192     uint64_t timestamp_ = 0;
193     uint64_t lastAnimateTimestamp_ = 0;
194     uint64_t prePerfTimestamp_ = 0;
195     uint64_t lastCleanCacheTimestamp_ = 0;
196     std::unordered_map<uint32_t, sptr<IApplicationAgent>> applicationAgentMap_;
197 
198     std::shared_ptr<RSContext> context_;
199     std::thread::id mainThreadId_;
200     std::shared_ptr<VSyncReceiver> receiver_ = nullptr;
201     std::map<pid_t, sptr<RSIOcclusionChangeCallback>> occlusionListeners_;
202     std::mutex occlusionMutex_;
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