• 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 #include "rs_render_service_connection.h"
17 #include <string>
18 
19 #include "frame_report.h"
20 #include "hgm_command.h"
21 #include "hgm_core.h"
22 #include "hgm_frame_rate_manager.h"
23 #include "luminance/rs_luminance_control.h"
24 #include "offscreen_render/rs_offscreen_render_thread.h"
25 #include "rs_main_thread.h"
26 #include "rs_trace.h"
27 #include "system/rs_system_parameters.h"
28 
29 #include "command/rs_command_verify_helper.h"
30 #include "command/rs_display_node_command.h"
31 #include "command/rs_surface_node_command.h"
32 #include "common/rs_background_thread.h"
33 #include "drawable/rs_canvas_drawing_render_node_drawable.h"
34 #include "include/gpu/GrDirectContext.h"
35 #include "pipeline/parallel_render/rs_sub_thread_manager.h"
36 #include "pipeline/rs_canvas_drawing_render_node.h"
37 #include "pipeline/rs_realtime_refresh_rate_manager.h"
38 #include "pipeline/rs_render_frame_rate_linker_map.h"
39 #include "pipeline/rs_render_node_gc.h"
40 #include "pipeline/rs_render_node_map.h"
41 #include "pipeline/rs_render_service_listener.h"
42 #include "pipeline/rs_surface_buffer_callback_manager.h"
43 #include "pipeline/rs_surface_capture_task.h"
44 #include "pipeline/rs_surface_capture_task_parallel.h"
45 #include "pipeline/rs_ui_capture_task_parallel.h"
46 #include "pipeline/rs_surface_render_node.h"
47 #include "pipeline/rs_task_dispatcher.h"
48 #include "pipeline/rs_uifirst_manager.h"
49 #include "pipeline/rs_uni_render_judgement.h"
50 #include "pipeline/rs_uni_ui_capture.h"
51 #include "pipeline/rs_unmarshal_thread.h"
52 #include "pixel_map_from_surface.h"
53 #include "platform/common/rs_log.h"
54 #include "platform/common/rs_system_properties.h"
55 #include "platform/ohos/rs_jank_stats.h"
56 #include "render/rs_typeface_cache.h"
57 
58 #ifdef TP_FEATURE_ENABLE
59 #include "touch_screen/touch_screen.h"
60 #endif
61 
62 #ifdef RS_ENABLE_VK
63 #include "platform/ohos/backend/rs_vulkan_context.h"
64 #endif
65 
66 namespace OHOS {
67 namespace Rosen {
68 namespace {
69 constexpr int SLEEP_TIME_US = 1000;
70 const std::string REGISTER_NODE = "RegisterNode";
71 }
72 // we guarantee that when constructing this object,
73 // all these pointers are valid, so will not check them.
RSRenderServiceConnection(pid_t remotePid,wptr<RSRenderService> renderService,RSMainThread * mainThread,sptr<RSScreenManager> screenManager,sptr<IRemoteObject> token,sptr<VSyncDistributor> distributor)74 RSRenderServiceConnection::RSRenderServiceConnection(
75     pid_t remotePid,
76     wptr<RSRenderService> renderService,
77     RSMainThread* mainThread,
78     sptr<RSScreenManager> screenManager,
79     sptr<IRemoteObject> token,
80     sptr<VSyncDistributor> distributor)
81     : remotePid_(remotePid),
82       renderService_(renderService),
83       mainThread_(mainThread),
84       renderThread_(RSUniRenderThread::Instance()),
85       screenManager_(screenManager),
86       token_(token),
87       connDeathRecipient_(new RSConnectionDeathRecipient(this)),
88       ApplicationDeathRecipient_(new RSApplicationRenderThreadDeathRecipient(this)),
89       appVSyncDistributor_(distributor)
90 {
91     if (!token_->AddDeathRecipient(connDeathRecipient_)) {
92         RS_LOGW("RSRenderServiceConnection: Failed to set death recipient.");
93     }
94 }
95 
~RSRenderServiceConnection()96 RSRenderServiceConnection::~RSRenderServiceConnection() noexcept
97 {
98     if (token_ && connDeathRecipient_) {
99         token_->RemoveDeathRecipient(connDeathRecipient_);
100     }
101     CleanAll();
102 }
103 
CleanVirtualScreens()104 void RSRenderServiceConnection::CleanVirtualScreens() noexcept
105 {
106     std::lock_guard<std::mutex> lock(mutex_);
107 
108     for (const auto id : virtualScreenIds_) {
109         screenManager_->RemoveVirtualScreen(id);
110     }
111     virtualScreenIds_.clear();
112 
113     if (screenChangeCallback_ != nullptr) {
114         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
115         screenChangeCallback_ = nullptr;
116     }
117 }
118 
CleanRenderNodes()119 void RSRenderServiceConnection::CleanRenderNodes() noexcept
120 {
121     auto& context = mainThread_->GetContext();
122     auto& nodeMap = context.GetMutableNodeMap();
123 
124     nodeMap.FilterNodeByPid(remotePid_);
125 }
126 
CleanFrameRateLinkers()127 void RSRenderServiceConnection::CleanFrameRateLinkers() noexcept
128 {
129     auto& context = mainThread_->GetContext();
130     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
131 
132     frameRateLinkerMap.FilterFrameRateLinkerByPid(remotePid_);
133 }
134 
CleanFrameRateLinkerExpectedFpsCallbacks()135 void RSRenderServiceConnection::CleanFrameRateLinkerExpectedFpsCallbacks() noexcept
136 {
137     auto& context = mainThread_->GetContext();
138     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
139     frameRateLinkerMap.UnRegisterExpectedFpsUpdateCallbackByListener(remotePid_);
140 }
141 
CleanAll(bool toDelete)142 void RSRenderServiceConnection::CleanAll(bool toDelete) noexcept
143 {
144     {
145         std::lock_guard<std::mutex> lock(mutex_);
146         if (cleanDone_) {
147             return;
148         }
149     }
150     if (!mainThread_) {
151         return;
152     }
153     RS_LOGD("RSRenderServiceConnection::CleanAll() start.");
154     RsCommandVerifyHelper::GetInstance().RemoveCntWithPid(remotePid_);
155     mainThread_->ScheduleTask(
156         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
157             sptr<RSRenderServiceConnection> connection = weakThis.promote();
158             if (!connection) {
159                 return;
160             }
161             RS_TRACE_NAME_FMT("CleanVirtualScreens %d", connection->remotePid_);
162             connection->CleanVirtualScreens();
163         }).wait();
164     mainThread_->ScheduleTask(
165         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
166             sptr<RSRenderServiceConnection> connection = weakThis.promote();
167             if (!connection) {
168                 return;
169             }
170             RS_TRACE_NAME_FMT("CleanRenderNodes %d", connection->remotePid_);
171             connection->CleanRenderNodes();
172             connection->CleanFrameRateLinkers();
173             connection->CleanFrameRateLinkerExpectedFpsCallbacks();
174         }).wait();
175     mainThread_->ScheduleTask(
176         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
177             sptr<RSRenderServiceConnection> connection = weakThis.promote();
178             if (!connection) {
179                 return;
180             }
181             RS_TRACE_NAME_FMT("ClearTransactionDataPidInfo %d", connection->remotePid_);
182             connection->mainThread_->ClearTransactionDataPidInfo(connection->remotePid_);
183         }).wait();
184     mainThread_->ScheduleTask(
185         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
186             sptr<RSRenderServiceConnection> connection = weakThis.promote();
187             if (!connection) {
188                 return;
189             }
190             RS_TRACE_NAME_FMT("CleanHgmEvent %d", connection->remotePid_);
191             if (connection->mainThread_->GetFrameRateMgr() != nullptr) {
192                 connection->mainThread_->GetFrameRateMgr()->CleanVote(connection->remotePid_);
193             }
194         }).wait();
195     mainThread_->ScheduleTask(
196         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
197             sptr<RSRenderServiceConnection> connection = weakThis.promote();
198             if (!connection) {
199                 return;
200             }
201             RS_TRACE_NAME_FMT("UnRegisterCallback %d", connection->remotePid_);
202             HgmConfigCallbackManager::GetInstance()->UnRegisterHgmConfigChangeCallback(connection->remotePid_);
203             connection->mainThread_->UnRegisterOcclusionChangeCallback(connection->remotePid_);
204             connection->mainThread_->ClearSurfaceOcclusionChangeCallback(connection->remotePid_);
205             connection->mainThread_->UnRegisterUIExtensionCallback(connection->remotePid_);
206         }).wait();
207     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(remotePid_);
208     RSTypefaceCache::Instance().RemoveDrawingTypefacesByPid(remotePid_);
209     {
210         std::lock_guard<std::mutex> lock(mutex_);
211         cleanDone_ = true;
212     }
213 
214     if (toDelete) {
215         auto renderService = renderService_.promote();
216         if (renderService == nullptr) {
217             RS_LOGW("RSRenderServiceConnection::CleanAll() RenderService is dead.");
218         } else {
219             renderService->RemoveConnection(GetToken());
220         }
221     }
222 
223     RS_LOGD("RSRenderServiceConnection::CleanAll() end.");
224 }
225 
RSConnectionDeathRecipient(wptr<RSRenderServiceConnection> conn)226 RSRenderServiceConnection::RSConnectionDeathRecipient::RSConnectionDeathRecipient(
227     wptr<RSRenderServiceConnection> conn) : conn_(conn)
228 {
229 }
230 
OnRemoteDied(const wptr<IRemoteObject> & token)231 void RSRenderServiceConnection::RSConnectionDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
232 {
233     auto tokenSptr = token.promote();
234     if (tokenSptr == nullptr) {
235         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: can't promote remote object.");
236         return;
237     }
238 
239     auto rsConn = conn_.promote();
240     if (rsConn == nullptr) {
241         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: RSRenderServiceConnection was dead, do nothing.");
242         return;
243     }
244 
245     if (rsConn->GetToken() != tokenSptr) {
246         RS_LOGI("RSConnectionDeathRecipient::OnRemoteDied: token doesn't match, ignore it.");
247         return;
248     }
249 
250     rsConn->CleanAll(true);
251 }
252 
RSApplicationRenderThreadDeathRecipient(wptr<RSRenderServiceConnection> conn)253 RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::RSApplicationRenderThreadDeathRecipient(
254     wptr<RSRenderServiceConnection> conn) : conn_(conn)
255 {}
256 
OnRemoteDied(const wptr<IRemoteObject> & token)257 void RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
258 {
259     auto tokenSptr = token.promote();
260     if (tokenSptr == nullptr) {
261         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: can't promote remote object.");
262         return;
263     }
264 
265     auto rsConn = conn_.promote();
266     if (rsConn == nullptr) {
267         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: "
268             "RSRenderServiceConnection was dead, do nothing.");
269         return;
270     }
271 
272     RS_LOGD("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: Unregister.");
273     auto app = iface_cast<IApplicationAgent>(tokenSptr);
274     rsConn->UnRegisterApplicationAgent(app);
275 }
276 
CommitTransaction(std::unique_ptr<RSTransactionData> & transactionData)277 void RSRenderServiceConnection::CommitTransaction(std::unique_ptr<RSTransactionData>& transactionData)
278 {
279     if (!mainThread_) {
280         return;
281     }
282     pid_t callingPid = GetCallingPid();
283     bool isTokenTypeValid = true;
284     bool isNonSystemAppCalling = false;
285     RSInterfaceCodeAccessVerifierBase::GetAccessType(isTokenTypeValid, isNonSystemAppCalling);
286     bool shouldDrop = RSUnmarshalThread::Instance().ReportTransactionDataStatistics(
287         callingPid, transactionData.get(), isNonSystemAppCalling);
288     if (shouldDrop) {
289         RS_LOGW("RSRenderServiceConnection::CommitTransaction data droped");
290         return;
291     }
292     bool isProcessBySingleFrame = mainThread_->IsNeedProcessBySingleFrameComposer(transactionData);
293     if (isProcessBySingleFrame) {
294         mainThread_->ProcessDataBySingleFrameComposer(transactionData);
295     } else {
296         mainThread_->RecvRSTransactionData(transactionData);
297     }
298 }
299 
ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask> & task)300 void RSRenderServiceConnection::ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask>& task)
301 {
302     if (task == nullptr || mainThread_ == nullptr) {
303         RS_LOGW("RSRenderServiceConnection::ExecuteSynchronousTask, task or main thread is null!");
304         return;
305     }
306     // After a synchronous task times out, it will no longer be executed.
307     auto isTimeout = std::make_shared<bool>(0);
308     std::weak_ptr<bool> isTimeoutWeak = isTimeout;
309     std::chrono::nanoseconds span(task->GetTimeout());
310     mainThread_->ScheduleTask([task, mainThread = mainThread_, isTimeoutWeak] {
311         if (task == nullptr || mainThread == nullptr || isTimeoutWeak.expired()) {
312             return;
313         }
314         task->Process(mainThread->GetContext());
315     }).wait_for(span);
316     isTimeout.reset();
317 }
318 
GetUniRenderEnabled()319 bool RSRenderServiceConnection::GetUniRenderEnabled()
320 {
321     return RSUniRenderJudgement::IsUniRender();
322 }
323 
CreateNode(const RSDisplayNodeConfig & displayNodeConfig,NodeId nodeId)324 bool RSRenderServiceConnection::CreateNode(const RSDisplayNodeConfig& displayNodeConfig, NodeId nodeId)
325 {
326     if (!mainThread_) {
327         return false;
328     }
329     std::shared_ptr<RSDisplayRenderNode> node =
330         DisplayNodeCommandHelper::CreateWithConfigInRS(mainThread_->GetContext(), nodeId,
331             displayNodeConfig);
332     if (node == nullptr) {
333         RS_LOGE("RSRenderService::CreateNode Failed.");
334         return false;
335     }
336     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this),
337         mirrorNodeId = displayNodeConfig.mirrorNodeId, isMirrored = displayNodeConfig.isMirrored]() -> void {
338         sptr<RSRenderServiceConnection> connection = weakThis.promote();
339         if (!connection) {
340             return;
341         }
342         auto& context = connection->mainThread_->GetContext();
343         context.GetMutableNodeMap().RegisterDisplayRenderNode(node);
344         context.GetGlobalRootRenderNode()->AddChild(node);
345         if (isMirrored) {
346             auto mirrorSourceNode = context.GetNodeMap()
347                 .GetRenderNode<RSDisplayRenderNode>(mirrorNodeId);
348             if (!mirrorSourceNode) {
349                 return;
350             }
351             node->SetMirrorSource(mirrorSourceNode);
352         }
353     };
354     mainThread_->PostSyncTask(registerNode);
355     return true;
356 }
357 
CreateNode(const RSSurfaceRenderNodeConfig & config)358 bool RSRenderServiceConnection::CreateNode(const RSSurfaceRenderNodeConfig& config)
359 {
360     if (!mainThread_) {
361         return false;
362     }
363     std::shared_ptr<RSSurfaceRenderNode> node =
364         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext());
365     if (node == nullptr) {
366         RS_LOGE("RSRenderService::CreateNode fail");
367         return false;
368     }
369     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
370         sptr<RSRenderServiceConnection> connection = weakThis.promote();
371         if (!connection) {
372             return;
373         }
374         connection->mainThread_->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
375     };
376     mainThread_->PostTask(registerNode);
377     return true;
378 }
379 
CreateNodeAndSurface(const RSSurfaceRenderNodeConfig & config,bool unobscured)380 sptr<Surface> RSRenderServiceConnection::CreateNodeAndSurface(const RSSurfaceRenderNodeConfig& config, bool unobscured)
381 {
382     if (!mainThread_) {
383         return nullptr;
384     }
385     std::shared_ptr<RSSurfaceRenderNode> node =
386         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext(), unobscured);
387     if (node == nullptr) {
388         RS_LOGE("RSRenderService::CreateNodeAndSurface CreateNode fail");
389         return nullptr;
390     }
391     sptr<IConsumerSurface> surface = IConsumerSurface::Create(config.name);
392     if (surface == nullptr) {
393         RS_LOGE("RSRenderService::CreateNodeAndSurface get consumer surface fail");
394         return nullptr;
395     }
396     const std::string& surfaceName = surface->GetName();
397     RS_LOGI("RsDebug RSRenderService::CreateNodeAndSurface node" \
398         "id:%{public}" PRIu64 " name:%{public}s bundleName:%{public}s surface id:%{public}" PRIu64 " name:%{public}s",
399         node->GetId(), node->GetName().c_str(), node->GetBundleName().c_str(),
400         surface->GetUniqueId(), surfaceName.c_str());
401     auto defaultUsage = surface->GetDefaultUsage();
402     surface->SetDefaultUsage(defaultUsage | BUFFER_USAGE_MEM_DMA | BUFFER_USAGE_HW_COMPOSER);
403     node->GetRSSurfaceHandler()->SetConsumer(surface);
404     RSMainThread* mainThread = mainThread_;
405     std::function<void()> registerNode = [node, mainThread]() -> void {
406         if (auto preNode = mainThread->GetContext().GetNodeMap().GetRenderNode(node->GetId())) {
407             RS_LOGE("CreateNodeAndSurface same id node:%{public}" PRIu64 ", type:%d",
408                 node->GetId(), preNode->GetType());
409             usleep(SLEEP_TIME_US);
410         }
411         mainThread->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
412     };
413     if (config.isSync) {
414         mainThread_->PostSyncTask(registerNode);
415     } else {
416         mainThread_->PostTask(registerNode, REGISTER_NODE, 0, AppExecFwk::EventQueue::Priority::VIP);
417     }
418     std::weak_ptr<RSSurfaceRenderNode> surfaceRenderNode(node);
419     sptr<IBufferConsumerListener> listener = new RSRenderServiceListener(surfaceRenderNode);
420     SurfaceError ret = surface->RegisterConsumerListener(listener);
421     if (ret != SURFACE_ERROR_OK) {
422         RS_LOGE("RSRenderService::CreateNodeAndSurface Register Consumer Listener fail");
423         return nullptr;
424     }
425     sptr<IBufferProducer> producer = surface->GetProducer();
426     sptr<Surface> pSurface = Surface::CreateSurfaceAsProducer(producer);
427     return pSurface;
428 }
429 
CreateVSyncConnection(const std::string & name,const sptr<VSyncIConnectionToken> & token,uint64_t id,NodeId windowNodeId,bool fromXcomponent)430 sptr<IVSyncConnection> RSRenderServiceConnection::CreateVSyncConnection(const std::string& name,
431                                                                         const sptr<VSyncIConnectionToken>& token,
432                                                                         uint64_t id,
433                                                                         NodeId windowNodeId,
434                                                                         bool fromXcomponent)
435 {
436     if (!mainThread_) {
437         return nullptr;
438     }
439     if (fromXcomponent) {
440         const auto& nodeMap = RSMainThread::Instance()->GetContext().GetNodeMap();
441         nodeMap.TraverseSurfaceNodes(
442             [this, &windowNodeId](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
443                 if (surfaceNode == nullptr || surfaceNode->GetRSSurfaceHandler() == nullptr ||
444                     surfaceNode->GetRSSurfaceHandler()->GetConsumer() == nullptr) {
445                     return;
446                 }
447                 if (surfaceNode->GetRSSurfaceHandler()->GetConsumer()->GetUniqueId() == windowNodeId) {
448                     windowNodeId = surfaceNode->GetInstanceRootNodeId();
449                     return;
450                 }
451             }
452         );
453     }
454     sptr<VSyncConnection> conn = new VSyncConnection(appVSyncDistributor_, name, token->AsObject(), 0, windowNodeId);
455     if (ExtractPid(id) == remotePid_) {
456         mainThread_->ScheduleTask([weakThis = wptr<RSRenderServiceConnection>(this), id]() {
457             sptr<RSRenderServiceConnection> connection = weakThis.promote();
458             if (!connection) {
459                 return;
460             }
461             auto linker = std::make_shared<RSRenderFrameRateLinker>(id);
462             auto& context = connection->mainThread_->GetContext();
463             auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
464             frameRateLinkerMap.RegisterFrameRateLinker(linker);
465         }).wait();
466         conn->id_ = id;
467     }
468     auto ret = appVSyncDistributor_->AddConnection(conn, windowNodeId);
469     if (ret != VSYNC_ERROR_OK) {
470         return nullptr;
471     }
472     return conn;
473 }
474 
CreatePixelMapFromSurface(sptr<Surface> surface,const Rect & srcRect)475 std::shared_ptr<Media::PixelMap> RSRenderServiceConnection::CreatePixelMapFromSurface(sptr<Surface> surface,
476     const Rect &srcRect)
477 {
478     OHOS::Media::Rect rect = {
479         .left = srcRect.x,
480         .top = srcRect.y,
481         .width = srcRect.w,
482         .height = srcRect.h,
483     };
484     std::shared_ptr<Media::PixelMap> pixelmap = nullptr;
485     RSBackgroundThread::Instance().PostSyncTask([surface, rect, &pixelmap]() {
486         pixelmap = OHOS::Rosen::CreatePixelMapFromSurface(surface, rect);
487     });
488     return pixelmap;
489 }
490 
SetFocusAppInfo(int32_t pid,int32_t uid,const std::string & bundleName,const std::string & abilityName,uint64_t focusNodeId)491 int32_t RSRenderServiceConnection::SetFocusAppInfo(
492     int32_t pid, int32_t uid, const std::string &bundleName, const std::string &abilityName, uint64_t focusNodeId)
493 {
494     if (mainThread_ == nullptr) {
495         return INVALID_ARGUMENTS;
496     }
497     mainThread_->ScheduleTask(
498         [pid, uid, bundleName, abilityName, focusNodeId, mainThread = mainThread_]() {
499             // don't use 'this' to get mainThread poninter
500             mainThread->SetFocusAppInfo(pid, uid, bundleName, abilityName, focusNodeId);
501         }
502     );
503     return SUCCESS;
504 }
505 
GetDefaultScreenId()506 ScreenId RSRenderServiceConnection::GetDefaultScreenId()
507 {
508     if (!screenManager_) {
509         return StatusCode::SCREEN_NOT_FOUND;
510     }
511     std::lock_guard<std::mutex> lock(mutex_);
512     return screenManager_->GetDefaultScreenId();
513 }
514 
GetActiveScreenId()515 ScreenId RSRenderServiceConnection::GetActiveScreenId()
516 {
517     if (!screenManager_) {
518         return StatusCode::SCREEN_NOT_FOUND;
519     }
520     std::lock_guard<std::mutex> lock(mutex_);
521     return screenManager_->GetActiveScreenId();
522 }
523 
GetAllScreenIds()524 std::vector<ScreenId> RSRenderServiceConnection::GetAllScreenIds()
525 {
526     std::vector<ScreenId> ids;
527     if (!screenManager_) {
528         return ids;
529     }
530     std::lock_guard<std::mutex> lock(mutex_);
531     return screenManager_->GetAllScreenIds();
532 }
533 
CreateVirtualScreen(const std::string & name,uint32_t width,uint32_t height,sptr<Surface> surface,ScreenId mirrorId,int32_t flags,std::vector<NodeId> whiteList)534 ScreenId RSRenderServiceConnection::CreateVirtualScreen(
535     const std::string &name,
536     uint32_t width,
537     uint32_t height,
538     sptr<Surface> surface,
539     ScreenId mirrorId,
540     int32_t flags,
541     std::vector<NodeId> whiteList)
542 {
543     if (!screenManager_) {
544         return StatusCode::SCREEN_NOT_FOUND;
545     }
546     std::lock_guard<std::mutex> lock(mutex_);
547     auto newVirtualScreenId = screenManager_->CreateVirtualScreen(
548         name, width, height, surface, mirrorId, flags, whiteList);
549     virtualScreenIds_.insert(newVirtualScreenId);
550     if (surface != nullptr) {
551         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ, name };
552         NotifyRefreshRateEvent(event);
553     }
554     return newVirtualScreenId;
555 }
556 
SetVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)557 int32_t RSRenderServiceConnection::SetVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
558 {
559     if (!screenManager_) {
560         return StatusCode::SCREEN_NOT_FOUND;
561     }
562     std::lock_guard<std::mutex> lock(mutex_);
563     if (blackListVector.empty()) {
564         RS_LOGW("SetVirtualScreenBlackList blackList is empty.");
565     }
566     return screenManager_->SetVirtualScreenBlackList(id, blackListVector);
567 }
568 
AddVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)569 int32_t RSRenderServiceConnection::AddVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
570 {
571     if (blackListVector.empty()) {
572         RS_LOGW("AddVirtualScreenBlackList blackList is empty.");
573         return StatusCode::BLACKLIST_IS_EMPTY;
574     }
575     std::lock_guard<std::mutex> lock(mutex_);
576     if (!screenManager_) {
577         return StatusCode::SCREEN_NOT_FOUND;
578     }
579     return screenManager_->AddVirtualScreenBlackList(id, blackListVector);
580 }
581 
RemoveVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)582 int32_t RSRenderServiceConnection::RemoveVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
583 {
584     if (blackListVector.empty()) {
585         RS_LOGW("RemoveVirtualScreenBlackList blackList is empty.");
586         return StatusCode::BLACKLIST_IS_EMPTY;
587     }
588     std::lock_guard<std::mutex> lock(mutex_);
589     if (!screenManager_) {
590         return StatusCode::SCREEN_NOT_FOUND;
591     }
592     return screenManager_->RemoveVirtualScreenBlackList(id, blackListVector);
593 }
594 
SetVirtualScreenSecurityExemptionList(ScreenId id,const std::vector<NodeId> & securityExemptionList)595 int32_t RSRenderServiceConnection::SetVirtualScreenSecurityExemptionList(
596     ScreenId id,
597     const std::vector<NodeId>& securityExemptionList)
598 {
599     if (!screenManager_) {
600         return StatusCode::SCREEN_NOT_FOUND;
601     }
602     return screenManager_->SetVirtualScreenSecurityExemptionList(id, securityExemptionList);
603 }
604 
SetCastScreenEnableSkipWindow(ScreenId id,bool enable)605 int32_t RSRenderServiceConnection::SetCastScreenEnableSkipWindow(ScreenId id, bool enable)
606 {
607     if (!screenManager_) {
608         return StatusCode::SCREEN_NOT_FOUND;
609     }
610     std::lock_guard<std::mutex> lock(mutex_);
611     return screenManager_->SetCastScreenEnableSkipWindow(id, enable);
612 }
613 
SetVirtualScreenSurface(ScreenId id,sptr<Surface> surface)614 int32_t RSRenderServiceConnection::SetVirtualScreenSurface(ScreenId id, sptr<Surface> surface)
615 {
616     if (!screenManager_) {
617         return StatusCode::SCREEN_NOT_FOUND;
618     }
619     std::lock_guard<std::mutex> lock(mutex_);
620     return screenManager_->SetVirtualScreenSurface(id, surface);
621 }
622 
RemoveVirtualScreen(ScreenId id)623 void RSRenderServiceConnection::RemoveVirtualScreen(ScreenId id)
624 {
625     if (!screenManager_) {
626         return;
627     }
628     std::lock_guard<std::mutex> lock(mutex_);
629     screenManager_->RemoveVirtualScreen(id);
630     virtualScreenIds_.erase(id);
631     EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
632     NotifyRefreshRateEvent(event);
633 }
634 
SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)635 int32_t RSRenderServiceConnection::SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)
636 {
637     if (!callback) {
638         return INVALID_ARGUMENTS;
639     }
640     std::unique_lock<std::mutex> lock(mutex_);
641     if (screenChangeCallback_ == callback) {
642         return INVALID_ARGUMENTS;
643     }
644 
645     if (screenChangeCallback_ != nullptr) {
646         // remove the old callback
647         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
648     }
649 
650     // update
651     int32_t status = screenManager_->AddScreenChangeCallback(callback);
652     auto tmp = screenChangeCallback_;
653     screenChangeCallback_ = callback;
654     lock.unlock();
655     return status;
656 }
657 
SetScreenActiveMode(ScreenId id,uint32_t modeId)658 void RSRenderServiceConnection::SetScreenActiveMode(ScreenId id, uint32_t modeId)
659 {
660     if (!screenManager_) {
661         return;
662     }
663     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
664     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
665         return RSHardwareThread::Instance().ScheduleTask(
666             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
667     } else {
668         return mainThread_->ScheduleTask(
669             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
670     }
671 }
672 
SetScreenRefreshRate(ScreenId id,int32_t sceneId,int32_t rate)673 void RSRenderServiceConnection::SetScreenRefreshRate(ScreenId id, int32_t sceneId, int32_t rate)
674 {
675     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetScreenRefreshRate");
676     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
677     int32_t setResult = hgmCore.SetScreenRefreshRate(id, sceneId, rate);
678     if (setResult != 0) {
679         RS_LOGW("SetScreenRefreshRate request of screen %{public}" PRIu64 " of rate %{public}d is refused",
680             id, rate);
681         return;
682     }
683     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
684 }
685 
SetRefreshRateMode(int32_t refreshRateMode)686 void RSRenderServiceConnection::SetRefreshRateMode(int32_t refreshRateMode)
687 {
688     if (!mainThread_) {
689         return;
690     }
691     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetRefreshRateMode");
692     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
693     int32_t setResult = hgmCore.SetRefreshRateMode(refreshRateMode);
694     RSSystemProperties::SetHgmRefreshRateModesEnabled(std::to_string(refreshRateMode));
695     if (setResult != 0) {
696         RS_LOGW("SetRefreshRateMode mode %{public}d is not supported", refreshRateMode);
697     }
698     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
699 }
700 
SyncFrameRateRange(FrameRateLinkerId id,const FrameRateRange & range,int32_t animatorExpectedFrameRate)701 void RSRenderServiceConnection::SyncFrameRateRange(FrameRateLinkerId id,
702     const FrameRateRange& range, int32_t animatorExpectedFrameRate)
703 {
704     if (!mainThread_) {
705         return;
706     }
707     mainThread_->ScheduleTask(
708         [weakThis = wptr<RSRenderServiceConnection>(this), id, &range, animatorExpectedFrameRate]() {
709             sptr<RSRenderServiceConnection> connection = weakThis.promote();
710             if (!connection) {
711                 return;
712             }
713             auto& context = connection->mainThread_->GetContext();
714             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
715             auto linker = linkerMap.GetFrameRateLinker(id);
716             if (linker == nullptr) {
717                 RS_LOGW("SyncFrameRateRange there is no frameRateLinker for id %{public}" PRIu64, id);
718                 return;
719             }
720             linker->SetExpectedRange(range);
721             linker->SetAnimatorExpectedFrameRate(animatorExpectedFrameRate);
722         }).wait();
723 }
724 
UnregisterFrameRateLinker(FrameRateLinkerId id)725 void RSRenderServiceConnection::UnregisterFrameRateLinker(FrameRateLinkerId id)
726 {
727     if (!mainThread_) {
728         return;
729     }
730     mainThread_->ScheduleTask(
731         [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
732             sptr<RSRenderServiceConnection> connection = weakThis.promote();
733             if (!connection) {
734                 return;
735             }
736             auto& context = connection->mainThread_->GetContext();
737             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
738             auto linker = linkerMap.GetFrameRateLinker(id);
739             if (linker == nullptr) {
740                 RS_LOGE("UnregisterFrameRateLinker there is no frameRateLinker for id %{public}" PRIu64, id);
741                 return;
742             }
743             linkerMap.UnregisterFrameRateLinker(id);
744         }).wait();
745 }
746 
GetScreenCurrentRefreshRate(ScreenId id)747 uint32_t RSRenderServiceConnection::GetScreenCurrentRefreshRate(ScreenId id)
748 {
749     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
750     uint32_t rate = hgmCore.GetScreenCurrentRefreshRate(id);
751     if (rate == 0) {
752         RS_LOGW("GetScreenCurrentRefreshRate failed to get current refreshrate of"
753             " screen : %{public}" PRIu64 "", id);
754     }
755     return rate;
756 }
757 
GetScreenSupportedRefreshRates(ScreenId id)758 std::vector<int32_t> RSRenderServiceConnection::GetScreenSupportedRefreshRates(ScreenId id)
759 {
760     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
761     std::vector<int32_t> rates = hgmCore.GetScreenComponentRefreshRates(id);
762     return rates;
763 }
764 
GetShowRefreshRateEnabled()765 bool RSRenderServiceConnection::GetShowRefreshRateEnabled()
766 {
767     return RSRealtimeRefreshRateManager::Instance().GetShowRefreshRateEnabled();
768 }
769 
SetShowRefreshRateEnabled(bool enable)770 void RSRenderServiceConnection::SetShowRefreshRateEnabled(bool enable)
771 {
772     return RSRealtimeRefreshRateManager::Instance().SetShowRefreshRateEnabled(enable);
773 }
774 
GetRefreshInfo(pid_t pid)775 std::string RSRenderServiceConnection::GetRefreshInfo(pid_t pid)
776 {
777     if (!mainThread_) {
778         return "";
779     }
780     auto& context = mainThread_->GetContext();
781     auto& nodeMap = context.GetMutableNodeMap();
782     std::string surfaceName = nodeMap.GetSelfDrawSurfaceNameByPid(pid);
783     if (surfaceName.empty()) {
784         return "";
785     }
786     std::string dumpString;
787     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
788     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
789         RSHardwareThread::Instance().ScheduleTask(
790             [this, &dumpString, &surfaceName]() { return screenManager_->FpsDump(dumpString, surfaceName); }).wait();
791     } else {
792         mainThread_->ScheduleTask(
793             [this, &dumpString, &surfaceName]() { return screenManager_->FpsDump(dumpString, surfaceName); }).wait();
794     }
795     return dumpString;
796 }
797 
GetCurrentRefreshRateMode()798 int32_t RSRenderServiceConnection::GetCurrentRefreshRateMode()
799 {
800     auto &hgmCore = OHOS::Rosen::HgmCore::Instance();
801     int32_t refreshRateMode = hgmCore.GetCurrentRefreshRateMode();
802     return refreshRateMode;
803 }
804 
SetPhysicalScreenResolution(ScreenId id,uint32_t width,uint32_t height)805 int32_t RSRenderServiceConnection::SetPhysicalScreenResolution(ScreenId id, uint32_t width, uint32_t height)
806 {
807     if (!screenManager_) {
808         return StatusCode::SCREEN_MANAGER_NULL;
809     }
810     return screenManager_->SetPhysicalScreenResolution(id, width, height);
811 }
812 
SetVirtualScreenResolution(ScreenId id,uint32_t width,uint32_t height)813 int32_t RSRenderServiceConnection::SetVirtualScreenResolution(ScreenId id, uint32_t width, uint32_t height)
814 {
815     if (!screenManager_) {
816         return StatusCode::SCREEN_NOT_FOUND;
817     }
818     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
819     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
820         return RSHardwareThread::Instance().ScheduleTask(
821             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
822     } else {
823         return mainThread_->ScheduleTask(
824             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
825     }
826 }
827 
MarkPowerOffNeedProcessOneFrame()828 void RSRenderServiceConnection::MarkPowerOffNeedProcessOneFrame()
829 {
830     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
831     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
832         renderThread_.PostTask(
833             [weakThis = wptr<RSRenderServiceConnection>(this)]() {
834                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
835                 if (!connection) {
836                     return;
837                 }
838                 connection->screenManager_->MarkPowerOffNeedProcessOneFrame();
839             }
840         );
841     }
842 }
843 
DisablePowerOffRenderControl(ScreenId id)844 void RSRenderServiceConnection::DisablePowerOffRenderControl(ScreenId id)
845 {
846     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
847     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
848         renderThread_.PostTask(
849             [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
850                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
851                 if (!connection) {
852                     return;
853                 }
854                 connection->screenManager_->DisablePowerOffRenderControl(id);
855             }
856         );
857     }
858 }
859 
SetScreenPowerStatus(ScreenId id,ScreenPowerStatus status)860 void RSRenderServiceConnection::SetScreenPowerStatus(ScreenId id, ScreenPowerStatus status)
861 {
862     if (!screenManager_) {
863         return;
864     }
865     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
866     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
867         RSHardwareThread::Instance().ScheduleTask(
868             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
869         mainThread_->SetDiscardJankFrames(true);
870         renderThread_.SetDiscardJankFrames(true);
871         OHOS::Rosen::HgmCore::Instance().NotifyScreenPowerStatus(id, status);
872     } else {
873         mainThread_->ScheduleTask(
874             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
875     }
876 }
877 
878 namespace {
TakeSurfaceCaptureForUiParallel(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const Drawing::Rect & specifiedAreaRect)879 void TakeSurfaceCaptureForUiParallel(
880     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
881     const Drawing::Rect& specifiedAreaRect)
882 {
883     RS_LOGI("TakeSurfaceCaptureForUiParallel nodeId:[%{public}" PRIu64 "], issync:%{public}s", id,
884         captureConfig.isSync ? "true" : "false");
885     std::function<void()> captureTask = [id, callback, captureConfig, specifiedAreaRect]() {
886         RSUiCaptureTaskParallel::Capture(id, callback, captureConfig, specifiedAreaRect);
887     };
888 
889     if (captureConfig.isSync) {
890         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
891         return;
892     }
893 
894     auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
895     if (!node) {
896         RS_LOGE("RSRenderServiceConnection::TakeSurfaceCaptureForUiParallel node is nullptr");
897         callback->OnSurfaceCapture(id, nullptr);
898         return;
899     }
900 
901     if (node->IsOnTheTree() && !node->IsDirty() && !node->IsSubTreeDirty()) {
902         RSMainThread::Instance()->PostTask(captureTask);
903     } else {
904         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
905     }
906 }
907 
TakeSurfaceCaptureForUIWithUni(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)908 void TakeSurfaceCaptureForUIWithUni(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
909     const RSSurfaceCaptureConfig& captureConfig)
910 {
911     std::function<void()> offscreenRenderTask = [id, callback, captureConfig]() -> void {
912         RS_LOGD("RSRenderService::TakeSurfaceCaptureForUIWithUni callback->OnOffscreenRender"
913             " nodeId:[%{public}" PRIu64 "]", id);
914         ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCaptureForUIWithUni");
915         std::shared_ptr<RSUniUICapture> rsUniUICapture = std::make_shared<RSUniUICapture>(id, captureConfig);
916         std::shared_ptr<Media::PixelMap> pixelmap = rsUniUICapture->TakeLocalCapture();
917         callback->OnSurfaceCapture(id, pixelmap.get());
918         ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
919     };
920     if (!captureConfig.isSync) {
921         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
922     } else {
923         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
924         if (node == nullptr || !node->GetCommandExecuted()) {
925             RSOffscreenRenderThread::Instance().InSertCaptureTask(id, offscreenRenderTask);
926             return;
927         }
928         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
929         node->SetCommandExecuted(false);
930     }
931 }
932 }
933 
TakeSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const Drawing::Rect & specifiedAreaRect,RSSurfaceCapturePermissions permissions)934 void RSRenderServiceConnection::TakeSurfaceCapture(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
935     const RSSurfaceCaptureConfig& captureConfig, const Drawing::Rect& specifiedAreaRect,
936     RSSurfaceCapturePermissions permissions)
937 {
938     if (!mainThread_) {
939         return;
940     }
941     std::function<void()> captureTask = [id, callback, captureConfig, specifiedAreaRect,
942         screenCapturePermission = permissions.screenCapturePermission,
943         isSystemCalling = permissions.isSystemCalling,
944         selfCapture = permissions.selfCapture]() -> void {
945         if (captureConfig.captureType == SurfaceCaptureType::UICAPTURE) {
946             // When the isSync flag in captureConfig is true, UI capture processes commands before capture.
947             // When the isSync flag in captureConfig is false, UI capture will check null node independently.
948             // Therefore, a null node is valid for UI capture.
949             auto uiCaptureHasPermission = selfCapture || isSystemCalling;
950             if (!uiCaptureHasPermission) {
951                 RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture uicapture failed, nodeId:[%{public}" PRIu64
952                         "], isSystemCalling: %{public}u, selfCapture: %{public}u",
953                     id, isSystemCalling, selfCapture);
954                 callback->OnSurfaceCapture(id, nullptr);
955                 return;
956             }
957             if (RSUniRenderJudgement::IsUniRender()) {
958                 TakeSurfaceCaptureForUiParallel(id, callback, captureConfig, specifiedAreaRect);
959             } else {
960                 TakeSurfaceCaptureForUIWithUni(id, callback, captureConfig);
961             }
962             return;
963         }
964         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
965         if (node == nullptr) {
966             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node is nullptr");
967             callback->OnSurfaceCapture(id, nullptr);
968             return;
969         }
970         auto displayCaptureHasPermission = screenCapturePermission && isSystemCalling;
971         auto surfaceCaptureHasPermission = selfCapture || isSystemCalling;
972         if ((node->GetType() == RSRenderNodeType::DISPLAY_NODE && !displayCaptureHasPermission) ||
973             (node->GetType() == RSRenderNodeType::SURFACE_NODE && !surfaceCaptureHasPermission)) {
974             RS_LOGE("RSRenderServiceConnection::TakeSurfaceCapture failed, node type: %{public}u, "
975                 "screenCapturePermission: %{public}u, isSystemCalling: %{public}u, selfCapture: %{public}u",
976                 node->GetType(), screenCapturePermission, isSystemCalling, selfCapture);
977             callback->OnSurfaceCapture(id, nullptr);
978             return;
979         }
980         if (RSUniRenderJudgement::GetUniRenderEnabledType() == UniRenderEnabledType::UNI_RENDER_DISABLED) {
981             RS_LOGD("RSRenderService::TakeSurfaceCapture captureTaskInner nodeId:[%{public}" PRIu64 "]", id);
982             ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCapture");
983             RSSurfaceCaptureTask task(id, captureConfig);
984             if (!task.Run(callback)) {
985                 callback->OnSurfaceCapture(id, nullptr);
986             }
987             ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
988         } else {
989             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
990             RSSurfaceCaptureTaskParallel::Capture(id, callback, captureConfig, isSystemCalling);
991         }
992     };
993     mainThread_->PostTask(captureTask);
994 }
995 
SetWindowFreezeImmediately(NodeId id,bool isFreeze,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)996 void RSRenderServiceConnection::SetWindowFreezeImmediately(
997     NodeId id, bool isFreeze, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
998 {
999     if (!mainThread_) {
1000         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1001         return;
1002     }
1003     std::function<void()> setWindowFreezeTask = [id, isFreeze, callback, captureConfig]() -> void {
1004         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1005         if (node == nullptr) {
1006             RS_LOGE("RSRenderServiceConnection::SetWindowFreezeImmediately failed, node is nullptr");
1007             if (callback) {
1008                 callback->OnSurfaceCapture(id, nullptr);
1009             }
1010             return;
1011         }
1012         node->SetStaticCached(isFreeze);
1013         if (isFreeze) {
1014             bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1015                 RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ +
1016                 "::SET_WINDOW_FREEZE_IMMEDIATELY");
1017             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1018             RSSurfaceCaptureTaskParallel::Capture(id, callback, captureConfig, isSystemCalling, isFreeze);
1019         } else {
1020             RSSurfaceCaptureTaskParallel::ClearCacheImageByFreeze(id);
1021         }
1022     };
1023     mainThread_->PostTask(setWindowFreezeTask);
1024 }
1025 
RegisterApplicationAgent(uint32_t pid,sptr<IApplicationAgent> app)1026 void RSRenderServiceConnection::RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app)
1027 {
1028     if (!mainThread_) {
1029         RS_LOGE("RSRenderServiceConnection::RegisterApplicationAgent mainThread_ is nullptr");
1030         return;
1031     }
1032     auto captureTask = [weakThis = wptr<RSRenderServiceConnection>(this), pid, app]() -> void {
1033         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1034         if (connection == nullptr || connection->mainThread_ == nullptr) {
1035             RS_LOGE("RSRenderServiceConnection::RegisterApplicationAgent connection or mainThread_ is nullptr");
1036             return;
1037         }
1038         connection->mainThread_->RegisterApplicationAgent(pid, app);
1039     };
1040     mainThread_->PostTask(captureTask);
1041 
1042     app->AsObject()->AddDeathRecipient(ApplicationDeathRecipient_);
1043 }
1044 
UnRegisterApplicationAgent(sptr<IApplicationAgent> app)1045 void RSRenderServiceConnection::UnRegisterApplicationAgent(sptr<IApplicationAgent> app)
1046 {
1047     auto captureTask = [app]() -> void {
1048         RSMainThread::Instance()->UnRegisterApplicationAgent(app);
1049     };
1050     RSMainThread::Instance()->ScheduleTask(captureTask).wait();
1051 }
1052 
GetVirtualScreenResolution(ScreenId id)1053 RSVirtualScreenResolution RSRenderServiceConnection::GetVirtualScreenResolution(ScreenId id)
1054 {
1055     RSVirtualScreenResolution virtualScreenResolution;
1056     if (!screenManager_) {
1057         return virtualScreenResolution;
1058     }
1059     screenManager_->GetVirtualScreenResolution(id, virtualScreenResolution);
1060     return virtualScreenResolution;
1061 }
1062 
GetScreenActiveMode(ScreenId id)1063 RSScreenModeInfo RSRenderServiceConnection::GetScreenActiveMode(ScreenId id)
1064 {
1065     RSScreenModeInfo screenModeInfo;
1066     if (!screenManager_) {
1067         return screenModeInfo;
1068     }
1069     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1070     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1071         RSHardwareThread::Instance().ScheduleTask(
1072             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1073     } else {
1074         mainThread_->ScheduleTask(
1075             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1076     }
1077     return screenModeInfo;
1078 }
1079 
GetTotalAppMemSize(float & cpuMemSize,float & gpuMemSize)1080 bool RSRenderServiceConnection::GetTotalAppMemSize(float& cpuMemSize, float& gpuMemSize)
1081 {
1082     RSMainThread::Instance()->GetAppMemoryInMB(cpuMemSize, gpuMemSize);
1083     gpuMemSize += RSSubThreadManager::Instance()->GetAppGpuMemoryInMB();
1084     return true;
1085 }
1086 
GetMemoryGraphic(int pid)1087 MemoryGraphic RSRenderServiceConnection::GetMemoryGraphic(int pid)
1088 {
1089     MemoryGraphic memoryGraphic;
1090     if (!mainThread_) {
1091         return memoryGraphic;
1092     }
1093     if (GetUniRenderEnabled()) {
1094         RSMainThread* mainThread = mainThread_;
1095         mainThread_->ScheduleTask([mainThread, &pid, &memoryGraphic]() {
1096             if (RSMainThread::Instance()->GetContext().GetNodeMap().ContainPid(pid)) {
1097                 mainThread->CountMem(pid, memoryGraphic);
1098             }
1099         }).wait();
1100         return memoryGraphic;
1101     } else {
1102         return memoryGraphic;
1103     }
1104 }
1105 
GetMemoryGraphics()1106 std::vector<MemoryGraphic> RSRenderServiceConnection::GetMemoryGraphics()
1107 {
1108     std::vector<MemoryGraphic> memoryGraphics;
1109     if (!mainThread_) {
1110         return memoryGraphics;
1111     }
1112     if (GetUniRenderEnabled()) {
1113         mainThread_->ScheduleTask(
1114             [weakThis = wptr<RSRenderServiceConnection>(this), &memoryGraphics]() {
1115                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1116                 if (!connection) {
1117                     return;
1118                 }
1119                 return connection->mainThread_->CountMem(memoryGraphics);
1120             }).wait();
1121         return memoryGraphics;
1122     } else {
1123         return memoryGraphics;
1124     }
1125 }
1126 
GetScreenSupportedModes(ScreenId id)1127 std::vector<RSScreenModeInfo> RSRenderServiceConnection::GetScreenSupportedModes(ScreenId id)
1128 {
1129     std::vector<RSScreenModeInfo> screenSupportedModes;
1130     if (!screenManager_) {
1131         return screenSupportedModes;
1132     }
1133     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1134     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1135         return RSHardwareThread::Instance().ScheduleTask(
1136             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1137     } else {
1138         return mainThread_->ScheduleTask(
1139             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1140     }
1141 }
1142 
GetScreenCapability(ScreenId id)1143 RSScreenCapability RSRenderServiceConnection::GetScreenCapability(ScreenId id)
1144 {
1145     RSScreenCapability screenCapability;
1146     if (!screenManager_) {
1147         return screenCapability;
1148     }
1149     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1150     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1151         return RSHardwareThread::Instance().ScheduleTask(
1152             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1153     } else {
1154         return mainThread_->ScheduleTask(
1155             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1156     }
1157 }
1158 
GetScreenPowerStatus(ScreenId id)1159 ScreenPowerStatus RSRenderServiceConnection::GetScreenPowerStatus(ScreenId id)
1160 {
1161     if (!screenManager_) {
1162         return ScreenPowerStatus::INVALID_POWER_STATUS;
1163     }
1164     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1165     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1166         return RSHardwareThread::Instance().ScheduleTask(
1167             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1168     } else {
1169         return mainThread_->ScheduleTask(
1170             [=]() { return screenManager_->GetScreenPowerStatus(id); }).get();
1171     }
1172 }
1173 
GetScreenData(ScreenId id)1174 RSScreenData RSRenderServiceConnection::GetScreenData(ScreenId id)
1175 {
1176     RSScreenData screenData;
1177     if (!screenManager_) {
1178         return screenData;
1179     }
1180     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1181     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1182         return RSHardwareThread::Instance().ScheduleTask(
1183             [=]() { return screenManager_->GetScreenData(id); }).get();
1184     } else {
1185         return mainThread_->ScheduleTask(
1186             [=]() { return screenManager_->GetScreenData(id); }).get();
1187     }
1188 }
1189 
GetScreenBacklight(ScreenId id)1190 int32_t RSRenderServiceConnection::GetScreenBacklight(ScreenId id)
1191 {
1192     if (!screenManager_) {
1193         return INVALID_BACKLIGHT_VALUE;
1194     }
1195     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1196     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1197         return RSHardwareThread::Instance().ScheduleTask(
1198             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1199     } else {
1200         return mainThread_->ScheduleTask(
1201             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1202     }
1203 }
1204 
SetScreenBacklight(ScreenId id,uint32_t level)1205 void RSRenderServiceConnection::SetScreenBacklight(ScreenId id, uint32_t level)
1206 {
1207     if (!screenManager_) {
1208         return;
1209     }
1210     RSLuminanceControl::Get().SetSdrLuminance(id, level);
1211     if (RSLuminanceControl::Get().IsHdrOn(id) && level > 0) {
1212         auto task = [weakThis = wptr<RSRenderServiceConnection>(this)]() {
1213             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1214             if (!connection) {
1215                 RS_LOGE("RSRenderServiceConnection::SetScreenBacklight fail");
1216                 return;
1217             }
1218             connection->mainThread_->SetForceUpdateUniRenderFlag(true);
1219             connection->mainThread_->SetLuminanceChangingStatus(true);
1220             connection->mainThread_->SetDirtyFlag();
1221             connection->mainThread_->RequestNextVSync();
1222         };
1223         mainThread_->PostTask(task);
1224         return;
1225     }
1226 
1227     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1228     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1229         screenManager_->SetScreenBacklight(id, level);
1230     } else {
1231         mainThread_->ScheduleTask(
1232             [=]() { screenManager_->SetScreenBacklight(id, level); }).wait();
1233     }
1234 }
1235 
RegisterBufferClearListener(NodeId id,sptr<RSIBufferClearCallback> callback)1236 void RSRenderServiceConnection::RegisterBufferClearListener(
1237     NodeId id, sptr<RSIBufferClearCallback> callback)
1238 {
1239     if (!mainThread_) {
1240         return;
1241     }
1242     auto registerBufferClearListener =
1243         [id, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1244             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1245             if (!connection) {
1246                 return false;
1247             }
1248             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1249                 node->RegisterBufferClearListener(callback);
1250                 return true;
1251             }
1252             return false;
1253     };
1254     if (!registerBufferClearListener()) {
1255         mainThread_->PostTask(registerBufferClearListener);
1256     }
1257 }
1258 
RegisterBufferAvailableListener(NodeId id,sptr<RSIBufferAvailableCallback> callback,bool isFromRenderThread)1259 void RSRenderServiceConnection::RegisterBufferAvailableListener(
1260     NodeId id, sptr<RSIBufferAvailableCallback> callback, bool isFromRenderThread)
1261 {
1262     if (!mainThread_) {
1263         return;
1264     }
1265     auto registerBufferAvailableListener =
1266         [id, callback, isFromRenderThread, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1267             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1268             if (!connection) {
1269                 return false;
1270             }
1271             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1272                 node->RegisterBufferAvailableListener(callback, isFromRenderThread);
1273                 return true;
1274             }
1275             return false;
1276     };
1277     mainThread_->PostTask(registerBufferAvailableListener);
1278 }
1279 
GetScreenSupportedColorGamuts(ScreenId id,std::vector<ScreenColorGamut> & mode)1280 int32_t RSRenderServiceConnection::GetScreenSupportedColorGamuts(ScreenId id, std::vector<ScreenColorGamut>& mode)
1281 {
1282     if (!screenManager_) {
1283         return StatusCode::SCREEN_NOT_FOUND;
1284     }
1285     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1286     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1287         return RSHardwareThread::Instance().ScheduleTask(
1288             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1289     } else {
1290         return mainThread_->ScheduleTask(
1291             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1292     }
1293 }
1294 
GetScreenSupportedMetaDataKeys(ScreenId id,std::vector<ScreenHDRMetadataKey> & keys)1295 int32_t RSRenderServiceConnection::GetScreenSupportedMetaDataKeys(ScreenId id, std::vector<ScreenHDRMetadataKey>& keys)
1296 {
1297     if (!screenManager_) {
1298         return StatusCode::SCREEN_NOT_FOUND;
1299     }
1300     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1301     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1302         return RSHardwareThread::Instance().ScheduleTask(
1303             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1304     } else {
1305         return mainThread_->ScheduleTask(
1306             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1307     }
1308 }
1309 
GetScreenColorGamut(ScreenId id,ScreenColorGamut & mode)1310 int32_t RSRenderServiceConnection::GetScreenColorGamut(ScreenId id, ScreenColorGamut& mode)
1311 {
1312     if (!screenManager_) {
1313         return StatusCode::SCREEN_NOT_FOUND;
1314     }
1315     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1316     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1317         return RSHardwareThread::Instance().ScheduleTask(
1318             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1319     } else {
1320         return mainThread_->ScheduleTask(
1321             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1322     }
1323 }
1324 
SetScreenColorGamut(ScreenId id,int32_t modeIdx)1325 int32_t RSRenderServiceConnection::SetScreenColorGamut(ScreenId id, int32_t modeIdx)
1326 {
1327     if (!screenManager_) {
1328         return StatusCode::SCREEN_NOT_FOUND;
1329     }
1330     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1331     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1332         return RSHardwareThread::Instance().ScheduleTask(
1333             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1334     } else {
1335         return mainThread_->ScheduleTask(
1336             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
1337     }
1338 }
1339 
SetScreenGamutMap(ScreenId id,ScreenGamutMap mode)1340 int32_t RSRenderServiceConnection::SetScreenGamutMap(ScreenId id, ScreenGamutMap mode)
1341 {
1342     if (!screenManager_) {
1343         return StatusCode::SCREEN_NOT_FOUND;
1344     }
1345     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1346     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1347         return RSHardwareThread::Instance().ScheduleTask(
1348             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1349     } else {
1350         return mainThread_->ScheduleTask(
1351             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
1352     }
1353 }
1354 
SetScreenCorrection(ScreenId id,ScreenRotation screenRotation)1355 int32_t RSRenderServiceConnection::SetScreenCorrection(ScreenId id, ScreenRotation screenRotation)
1356 {
1357     if (!screenManager_) {
1358         return StatusCode::SCREEN_NOT_FOUND;
1359     }
1360     std::lock_guard<std::mutex> lock(mutex_);
1361     return screenManager_->SetScreenCorrection(id, screenRotation);
1362 }
1363 
SetVirtualMirrorScreenCanvasRotation(ScreenId id,bool canvasRotation)1364 bool RSRenderServiceConnection::SetVirtualMirrorScreenCanvasRotation(ScreenId id, bool canvasRotation)
1365 {
1366     if (!screenManager_) {
1367         return false;
1368     }
1369     std::lock_guard<std::mutex> lock(mutex_);
1370     return screenManager_->SetVirtualMirrorScreenCanvasRotation(id, canvasRotation);
1371 }
1372 
SetGlobalDarkColorMode(bool isDark)1373 bool RSRenderServiceConnection::SetGlobalDarkColorMode(bool isDark)
1374 {
1375     if (!mainThread_) {
1376         return false;
1377     }
1378     std::lock_guard<std::mutex> lock(mutex_);
1379     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isDark]() {
1380         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1381         if (!connection) {
1382             RS_LOGE("RSRenderServiceConnection::SetGlobalDarkColorMode fail");
1383             return;
1384         }
1385         connection->mainThread_->SetGlobalDarkColorMode(isDark);
1386     };
1387     mainThread_->PostTask(task);
1388     return true;
1389 }
1390 
SetVirtualMirrorScreenScaleMode(ScreenId id,ScreenScaleMode scaleMode)1391 bool RSRenderServiceConnection::SetVirtualMirrorScreenScaleMode(ScreenId id, ScreenScaleMode scaleMode)
1392 {
1393     if (!screenManager_) {
1394         return false;
1395     }
1396     std::lock_guard<std::mutex> lock(mutex_);
1397     return screenManager_->SetVirtualMirrorScreenScaleMode(id, scaleMode);
1398 }
1399 
GetScreenGamutMap(ScreenId id,ScreenGamutMap & mode)1400 int32_t RSRenderServiceConnection::GetScreenGamutMap(ScreenId id, ScreenGamutMap& mode)
1401 {
1402     if (!screenManager_) {
1403         return StatusCode::SCREEN_NOT_FOUND;
1404     }
1405     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1406     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1407         return RSHardwareThread::Instance().ScheduleTask(
1408             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1409     } else {
1410         return mainThread_->ScheduleTask(
1411             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
1412     }
1413 }
1414 
GetScreenHDRCapability(ScreenId id,RSScreenHDRCapability & screenHdrCapability)1415 int32_t RSRenderServiceConnection::GetScreenHDRCapability(ScreenId id, RSScreenHDRCapability& screenHdrCapability)
1416 {
1417     if (!screenManager_) {
1418         return StatusCode::SCREEN_NOT_FOUND;
1419     }
1420     std::lock_guard<std::mutex> lock(mutex_);
1421     return screenManager_->GetScreenHDRCapability(id, screenHdrCapability);
1422 }
1423 
GetPixelFormat(ScreenId id,GraphicPixelFormat & pixelFormat)1424 int32_t RSRenderServiceConnection::GetPixelFormat(ScreenId id, GraphicPixelFormat& pixelFormat)
1425 {
1426     if (!screenManager_) {
1427         return StatusCode::SCREEN_NOT_FOUND;
1428     }
1429     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1430     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1431         return RSHardwareThread::Instance().ScheduleTask(
1432             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1433     } else {
1434         return mainThread_->ScheduleTask(
1435             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
1436     }
1437 }
1438 
SetPixelFormat(ScreenId id,GraphicPixelFormat pixelFormat)1439 int32_t RSRenderServiceConnection::SetPixelFormat(ScreenId id, GraphicPixelFormat pixelFormat)
1440 {
1441     if (!screenManager_) {
1442         return StatusCode::SCREEN_NOT_FOUND;
1443     }
1444     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1445     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1446         return RSHardwareThread::Instance().ScheduleTask(
1447             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1448     } else {
1449         return mainThread_->ScheduleTask(
1450             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
1451     }
1452 }
1453 
GetScreenSupportedHDRFormats(ScreenId id,std::vector<ScreenHDRFormat> & hdrFormats)1454 int32_t RSRenderServiceConnection::GetScreenSupportedHDRFormats(ScreenId id, std::vector<ScreenHDRFormat>& hdrFormats)
1455 {
1456     if (!screenManager_) {
1457         return StatusCode::SCREEN_NOT_FOUND;
1458     }
1459     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1460     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1461         return RSHardwareThread::Instance().ScheduleTask(
1462             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1463     } else {
1464         return mainThread_->ScheduleTask(
1465             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
1466     }
1467 }
1468 
GetScreenHDRFormat(ScreenId id,ScreenHDRFormat & hdrFormat)1469 int32_t RSRenderServiceConnection::GetScreenHDRFormat(ScreenId id, ScreenHDRFormat& hdrFormat)
1470 {
1471     if (!screenManager_) {
1472         return StatusCode::SCREEN_NOT_FOUND;
1473     }
1474     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1475     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1476         return RSHardwareThread::Instance().ScheduleTask(
1477             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1478     } else {
1479         return mainThread_->ScheduleTask(
1480             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
1481     }
1482 }
1483 
SetScreenHDRFormat(ScreenId id,int32_t modeIdx)1484 int32_t RSRenderServiceConnection::SetScreenHDRFormat(ScreenId id, int32_t modeIdx)
1485 {
1486     if (!screenManager_) {
1487         return StatusCode::SCREEN_NOT_FOUND;
1488     }
1489     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1490     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1491         return RSHardwareThread::Instance().ScheduleTask(
1492             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1493     } else {
1494         return mainThread_->ScheduleTask(
1495             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
1496     }
1497 }
1498 
GetScreenSupportedColorSpaces(ScreenId id,std::vector<GraphicCM_ColorSpaceType> & colorSpaces)1499 int32_t RSRenderServiceConnection::GetScreenSupportedColorSpaces(
1500     ScreenId id, std::vector<GraphicCM_ColorSpaceType>& colorSpaces)
1501 {
1502     if (!screenManager_) {
1503         return StatusCode::SCREEN_NOT_FOUND;
1504     }
1505     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1506     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1507         return RSHardwareThread::Instance().ScheduleTask(
1508             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
1509     } else {
1510         return mainThread_->ScheduleTask(
1511             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
1512     }
1513 }
1514 
GetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType & colorSpace)1515 int32_t RSRenderServiceConnection::GetScreenColorSpace(ScreenId id, GraphicCM_ColorSpaceType& colorSpace)
1516 {
1517     if (!screenManager_) {
1518         return StatusCode::SCREEN_NOT_FOUND;
1519     }
1520     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1521     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1522         return RSHardwareThread::Instance().ScheduleTask(
1523             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
1524     } else {
1525         return mainThread_->ScheduleTask(
1526             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
1527     }
1528 }
1529 
SetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType colorSpace)1530 int32_t RSRenderServiceConnection::SetScreenColorSpace(ScreenId id, GraphicCM_ColorSpaceType colorSpace)
1531 {
1532     if (!screenManager_) {
1533         return StatusCode::SCREEN_NOT_FOUND;
1534     }
1535     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1536     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1537         return RSHardwareThread::Instance().ScheduleTask(
1538             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
1539     } else {
1540         return mainThread_->ScheduleTask(
1541             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
1542     }
1543 }
1544 
GetScreenType(ScreenId id,RSScreenType & screenType)1545 int32_t RSRenderServiceConnection::GetScreenType(ScreenId id, RSScreenType& screenType)
1546 {
1547     if (!screenManager_) {
1548         return StatusCode::SCREEN_NOT_FOUND;
1549     }
1550     std::lock_guard<std::mutex> lock(mutex_);
1551     return screenManager_->GetScreenType(id, screenType);
1552 }
1553 
GetBitmap(NodeId id,Drawing::Bitmap & bitmap)1554 bool RSRenderServiceConnection::GetBitmap(NodeId id, Drawing::Bitmap& bitmap)
1555 {
1556     if (!mainThread_) {
1557         return false;
1558     }
1559     std::promise<bool> result;
1560     std::future<bool> future = result.get_future();
1561     RSMainThread* mainThread = mainThread_;
1562     RSUniRenderThread* renderThread = &renderThread_;
1563     auto getBitmapTask = [id, &bitmap, mainThread, renderThread, &result]() {
1564         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
1565         if (node == nullptr) {
1566             RS_LOGE("RSRenderServiceConnection::GetBitmap cannot find NodeId: [%{public}" PRIu64 "]", id);
1567             result.set_value(false);
1568             return;
1569         }
1570         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
1571             RS_LOGE("RSRenderServiceConnection::GetBitmap RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
1572             result.set_value(false);
1573             return;
1574         }
1575         auto grContext = renderThread->GetRenderEngine()->GetRenderContext()->GetDrGPUContext();
1576         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
1577         auto getDrawableBitmapTask = [drawableNode, &bitmap, grContext, &result]() {
1578             bitmap = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)
1579                 ->GetBitmap(grContext);
1580             result.set_value(!bitmap.IsEmpty());
1581         };
1582         renderThread->PostTask(getDrawableBitmapTask);
1583     };
1584     mainThread_->PostTask(getBitmapTask);
1585     return future.get();
1586 }
1587 
GetPixelmap(NodeId id,const std::shared_ptr<Media::PixelMap> pixelmap,const Drawing::Rect * rect,std::shared_ptr<Drawing::DrawCmdList> drawCmdList)1588 bool RSRenderServiceConnection::GetPixelmap(NodeId id, const std::shared_ptr<Media::PixelMap> pixelmap,
1589     const Drawing::Rect* rect, std::shared_ptr<Drawing::DrawCmdList> drawCmdList)
1590 {
1591     if (!mainThread_) {
1592         return false;
1593     }
1594     std::promise<bool> result;
1595     std::future<bool> future = result.get_future();
1596     RSMainThread* mainThread = mainThread_;
1597     RSUniRenderThread* renderThread = &renderThread_;
1598     auto getPixelMapTask = [id, pixelmap, rect, drawCmdList, mainThread, renderThread, &result]() {
1599         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
1600         if (node == nullptr) {
1601             RS_LOGD("RSRenderServiceConnection::GetPixelmap: cannot find NodeId: [%{public}" PRIu64 "]", id);
1602             result.set_value(false);
1603             return;
1604         }
1605         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
1606             RS_LOGE("RSRenderServiceConnection::GetPixelmap: RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
1607             result.set_value(false);
1608             return;
1609         }
1610 
1611         auto tid = node->GetTid(); // planning: id may change in subthread
1612         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
1613         if (drawableNode) {
1614             tid = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->GetTid();
1615         }
1616         auto getDrawablePixelmapTask = [drawableNode, pixelmap, rect, &result, tid, drawCmdList]() {
1617             result.set_value(std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->
1618                 GetPixelmap(pixelmap, rect, tid, drawCmdList));
1619         };
1620         if (!node->IsOnTheTree()) {
1621             node->ClearOp();
1622         }
1623         if (tid == UNI_MAIN_THREAD_INDEX) {
1624             if (!mainThread->IsIdle() && mainThread->GetContext().HasActiveNode(node)) {
1625                 result.set_value(false);
1626                 return;
1627             }
1628             result.set_value(node->GetPixelmap(pixelmap, rect, tid, drawCmdList));
1629         } else if (tid == UNI_RENDER_THREAD_INDEX) {
1630             renderThread->PostTask(getDrawablePixelmapTask);
1631         } else {
1632             RSTaskDispatcher::GetInstance().PostTask(
1633                 RSSubThreadManager::Instance()->GetReThreadIndexMap()[tid], getDrawablePixelmapTask, false);
1634         }
1635     };
1636     mainThread_->PostTask(getPixelMapTask);
1637     return future.get();
1638 }
1639 
RegisterTypeface(uint64_t globalUniqueId,std::shared_ptr<Drawing::Typeface> & typeface)1640 bool RSRenderServiceConnection::RegisterTypeface(uint64_t globalUniqueId,
1641     std::shared_ptr<Drawing::Typeface>& typeface)
1642 {
1643     RS_LOGD("RSRenderServiceConnection::RegisterTypeface: pid[%{public}d] register typeface[%{public}u]",
1644         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
1645     RSTypefaceCache::Instance().CacheDrawingTypeface(globalUniqueId, typeface);
1646     return true;
1647 }
1648 
UnRegisterTypeface(uint64_t globalUniqueId)1649 bool RSRenderServiceConnection::UnRegisterTypeface(uint64_t globalUniqueId)
1650 {
1651     RS_LOGD("RSRenderServiceConnection::UnRegisterTypeface: pid[%{public}d] unregister typeface[%{public}u]",
1652         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
1653     RSTypefaceCache::Instance().AddDelayDestroyQueue(globalUniqueId);
1654     return true;
1655 }
1656 
SetScreenSkipFrameInterval(ScreenId id,uint32_t skipFrameInterval)1657 int32_t RSRenderServiceConnection::SetScreenSkipFrameInterval(ScreenId id, uint32_t skipFrameInterval)
1658 {
1659     if (!screenManager_) {
1660         return StatusCode::SCREEN_NOT_FOUND;
1661     }
1662     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1663     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1664         return RSHardwareThread::Instance().ScheduleTask(
1665             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
1666     } else {
1667         return mainThread_->ScheduleTask(
1668             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
1669     }
1670 }
1671 
SetVirtualScreenRefreshRate(ScreenId id,uint32_t maxRefreshRate,uint32_t & actualRefreshRate)1672 int32_t RSRenderServiceConnection::SetVirtualScreenRefreshRate(
1673     ScreenId id, uint32_t maxRefreshRate, uint32_t& actualRefreshRate)
1674 {
1675     if (!screenManager_) {
1676         return StatusCode::SCREEN_NOT_FOUND;
1677     }
1678     return screenManager_->SetVirtualScreenRefreshRate(id, maxRefreshRate, actualRefreshRate);
1679 }
1680 
SetScreenActiveRect(ScreenId id,const Rect & activeRect)1681 uint32_t RSRenderServiceConnection::SetScreenActiveRect(
1682     ScreenId id, const Rect& activeRect)
1683 {
1684     if (!screenManager_) {
1685         return StatusCode::SCREEN_NOT_FOUND;
1686     }
1687     GraphicIRect dstActiveRect {
1688         .x = activeRect.x,
1689         .y = activeRect.y,
1690         .w = activeRect.w,
1691         .h = activeRect.h,
1692     };
1693     return screenManager_->SetScreenActiveRect(id, dstActiveRect);
1694 }
1695 
RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)1696 int32_t RSRenderServiceConnection::RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback)
1697 {
1698     if (!mainThread_) {
1699         return StatusCode::INVALID_ARGUMENTS;
1700     }
1701     std::lock_guard<std::mutex> lock(mutex_);
1702     if (!callback) {
1703         RS_LOGD("RSRenderServiceConnection::RegisterOcclusionChangeCallback: callback is nullptr");
1704         return StatusCode::INVALID_ARGUMENTS;
1705     }
1706     mainThread_->RegisterOcclusionChangeCallback(remotePid_, callback);
1707     return StatusCode::SUCCESS;
1708 }
1709 
RegisterSurfaceOcclusionChangeCallback(NodeId id,sptr<RSISurfaceOcclusionChangeCallback> callback,std::vector<float> & partitionPoints)1710 int32_t RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback(
1711     NodeId id, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints)
1712 {
1713     if (!mainThread_) {
1714         return StatusCode::INVALID_ARGUMENTS;
1715     }
1716     std::lock_guard<std::mutex> lock(mutex_);
1717     if (!callback) {
1718         RS_LOGD("RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback: callback is nullptr");
1719         return StatusCode::INVALID_ARGUMENTS;
1720     }
1721     mainThread_->RegisterSurfaceOcclusionChangeCallback(id, remotePid_, callback, partitionPoints);
1722     return StatusCode::SUCCESS;
1723 }
1724 
UnRegisterSurfaceOcclusionChangeCallback(NodeId id)1725 int32_t RSRenderServiceConnection::UnRegisterSurfaceOcclusionChangeCallback(NodeId id)
1726 {
1727     if (!mainThread_) {
1728         return StatusCode::INVALID_ARGUMENTS;
1729     }
1730     std::lock_guard<std::mutex> lock(mutex_);
1731     mainThread_->UnRegisterSurfaceOcclusionChangeCallback(id);
1732     return StatusCode::SUCCESS;
1733 }
1734 
RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)1735 int32_t RSRenderServiceConnection::RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)
1736 {
1737     std::lock_guard<std::mutex> lock(mutex_);
1738     if (!callback) {
1739         RS_LOGD("RSRenderServiceConnection::RegisterHgmConfigChangeCallback: callback is nullptr");
1740         return StatusCode::INVALID_ARGUMENTS;
1741     }
1742 
1743     HgmConfigCallbackManager::GetInstance()->RegisterHgmConfigChangeCallback(remotePid_, callback);
1744     return StatusCode::SUCCESS;
1745 }
1746 
RegisterHgmRefreshRateModeChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)1747 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback(
1748     sptr<RSIHgmConfigChangeCallback> callback)
1749 {
1750     std::lock_guard<std::mutex> lock(mutex_);
1751     if (!callback) {
1752         RS_LOGD("RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback: callback is nullptr");
1753         return StatusCode::INVALID_ARGUMENTS;
1754     }
1755 
1756     HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateModeChangeCallback(remotePid_, callback);
1757     return StatusCode::SUCCESS;
1758 }
1759 
RegisterHgmRefreshRateUpdateCallback(sptr<RSIHgmConfigChangeCallback> callback)1760 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateUpdateCallback(
1761     sptr<RSIHgmConfigChangeCallback> callback)
1762 {
1763     std::lock_guard<std::mutex> lock(mutex_);
1764 
1765     HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateUpdateCallback(remotePid_, callback);
1766     return StatusCode::SUCCESS;
1767 }
1768 
RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)1769 int32_t RSRenderServiceConnection::RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,
1770     sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)
1771 {
1772     if (!mainThread_ || dstPid == 0) {
1773         return StatusCode::INVALID_ARGUMENTS;
1774     }
1775     auto task = [pid = remotePid_, dstPid, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() {
1776         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1777         if (!connection || !connection->mainThread_) {
1778             return;
1779         }
1780         connection->mainThread_->GetContext().GetMutableFrameRateLinkerMap()
1781             .RegisterFrameRateLinkerExpectedFpsUpdateCallback(pid, dstPid, callback);
1782     };
1783     mainThread_->PostTask(task);
1784     return StatusCode::SUCCESS;
1785 }
1786 
SetAppWindowNum(uint32_t num)1787 void RSRenderServiceConnection::SetAppWindowNum(uint32_t num)
1788 {
1789     if (!mainThread_) {
1790         return;
1791     }
1792     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), num]() -> void {
1793         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1794         if (!connection || !connection->mainThread_) {
1795             return;
1796         }
1797         connection->mainThread_->SetAppWindowNum(num);
1798     };
1799     mainThread_->PostTask(task);
1800 }
1801 
SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes)1802 bool RSRenderServiceConnection::SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes)
1803 {
1804     if (!mainThread_) {
1805         return false;
1806     }
1807     RSUifirstManager::Instance().OnProcessAnimateScene(systemAnimatedScenes);
1808     std::lock_guard<std::mutex> lock(mutex_);
1809     return mainThread_->SetSystemAnimatedScenes(systemAnimatedScenes);
1810 }
1811 
ShowWatermark(const std::shared_ptr<Media::PixelMap> & watermarkImg,bool isShow)1812 void RSRenderServiceConnection::ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool isShow)
1813 {
1814     if (!mainThread_) {
1815         return;
1816     }
1817     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), watermarkImg, isShow]() -> void {
1818         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1819         if (!connection) {
1820             return;
1821         }
1822         connection->mainThread_->ShowWatermark(watermarkImg, isShow);
1823     };
1824     mainThread_->PostTask(task);
1825 }
1826 
ResizeVirtualScreen(ScreenId id,uint32_t width,uint32_t height)1827 int32_t RSRenderServiceConnection::ResizeVirtualScreen(ScreenId id, uint32_t width, uint32_t height)
1828 {
1829     if (!screenManager_) {
1830         return StatusCode::SCREEN_NOT_FOUND;
1831     }
1832     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1833     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1834         return RSHardwareThread::Instance().ScheduleTask(
1835             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
1836                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1837                 if (!connection) {
1838                     return RS_CONNECTION_ERROR;
1839                 }
1840                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
1841             }
1842         ).get();
1843     } else {
1844         return mainThread_->ScheduleTask(
1845             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
1846                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1847                 if (!connection) {
1848                     return RS_CONNECTION_ERROR;
1849                 }
1850                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
1851             }
1852         ).get();
1853     }
1854 }
1855 
ReportJankStats()1856 void RSRenderServiceConnection::ReportJankStats()
1857 {
1858     auto task = []() -> void { RSJankStats::GetInstance().ReportJankStats(); };
1859     renderThread_.PostTask(task);
1860 }
1861 
NotifyLightFactorStatus(bool isSafe)1862 void RSRenderServiceConnection::NotifyLightFactorStatus(bool isSafe)
1863 {
1864     if (!mainThread_) {
1865         return;
1866     }
1867     if (mainThread_->GetFrameRateMgr() == nullptr) {
1868         RS_LOGW("RSRenderServiceConnection::NotifyLightFactorStatus: frameRateMgr is nullptr.");
1869         return;
1870     }
1871     mainThread_->GetFrameRateMgr()->HandleLightFactorStatus(remotePid_, isSafe);
1872 }
1873 
NotifyPackageEvent(uint32_t listSize,const std::vector<std::string> & packageList)1874 void RSRenderServiceConnection::NotifyPackageEvent(uint32_t listSize, const std::vector<std::string>& packageList)
1875 {
1876     if (!mainThread_) {
1877         return;
1878     }
1879     if (mainThread_->GetFrameRateMgr() == nullptr) {
1880         RS_LOGW("RSRenderServiceConnection::NotifyPackageEvent: frameRateMgr is nullptr.");
1881         return;
1882     }
1883     mainThread_->GetFrameRateMgr()->HandlePackageEvent(remotePid_, packageList);
1884 }
1885 
NotifyRefreshRateEvent(const EventInfo & eventInfo)1886 void RSRenderServiceConnection::NotifyRefreshRateEvent(const EventInfo& eventInfo)
1887 {
1888     if (!mainThread_) {
1889         return;
1890     }
1891     if (mainThread_->GetFrameRateMgr() == nullptr) {
1892         RS_LOGW("RSRenderServiceConnection::NotifyRefreshRateEvent: frameRateMgr is nullptr.");
1893         return;
1894     }
1895     mainThread_->GetFrameRateMgr()->HandleRefreshRateEvent(remotePid_, eventInfo);
1896 }
1897 
NotifyTouchEvent(int32_t touchStatus,int32_t touchCnt)1898 void RSRenderServiceConnection::NotifyTouchEvent(int32_t touchStatus, int32_t touchCnt)
1899 {
1900     if (!mainThread_) {
1901         return;
1902     }
1903     if (mainThread_->GetFrameRateMgr() == nullptr) {
1904         RS_LOGW("RSRenderServiceConnection::NotifyTouchEvent: frameRateMgr is nullptr.");
1905         return;
1906     }
1907     mainThread_->GetFrameRateMgr()->HandleTouchEvent(remotePid_, touchStatus, touchCnt);
1908 }
1909 
NotifyDynamicModeEvent(bool enableDynamicModeEvent)1910 void RSRenderServiceConnection::NotifyDynamicModeEvent(bool enableDynamicModeEvent)
1911 {
1912     HgmTaskHandleThread::Instance().PostTask([enableDynamicModeEvent] () {
1913         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
1914         if (frameRateMgr == nullptr) {
1915             RS_LOGW("RSRenderServiceConnection::NotifyDynamicModeEvent: frameRateMgr is nullptr.");
1916             return;
1917         }
1918         frameRateMgr->HandleDynamicModeEvent(enableDynamicModeEvent);
1919     });
1920 }
1921 
ReportEventResponse(DataBaseRs info)1922 void RSRenderServiceConnection::ReportEventResponse(DataBaseRs info)
1923 {
1924     auto task = [info]() -> void {
1925         RSJankStats::GetInstance().SetReportEventResponse(info);
1926     };
1927     renderThread_.PostTask(task);
1928     RSUifirstManager::Instance().OnProcessEventResponse(info);
1929 }
1930 
ReportEventComplete(DataBaseRs info)1931 void RSRenderServiceConnection::ReportEventComplete(DataBaseRs info)
1932 {
1933     auto task = [info]() -> void {
1934         RSJankStats::GetInstance().SetReportEventComplete(info);
1935     };
1936     renderThread_.PostTask(task);
1937     RSUifirstManager::Instance().OnProcessEventComplete(info);
1938 }
1939 
ReportEventJankFrame(DataBaseRs info)1940 void RSRenderServiceConnection::ReportEventJankFrame(DataBaseRs info)
1941 {
1942     bool isReportTaskDelayed = renderThread_.IsMainLooping();
1943     auto task = [info, isReportTaskDelayed]() -> void {
1944         RSJankStats::GetInstance().SetReportEventJankFrame(info, isReportTaskDelayed);
1945     };
1946     renderThread_.PostTask(task);
1947 }
1948 
ReportGameStateData(GameStateData info)1949 void RSRenderServiceConnection::ReportGameStateData(GameStateData info)
1950 {
1951     RS_LOGD("RSRenderServiceConnection::ReportGameStateData = %{public}s, uid = %{public}d, state = %{public}d, "
1952             "pid = %{public}d renderTid = %{public}d ",
1953         info.bundleName.c_str(), info.uid, info.state, info.pid, info.renderTid);
1954 
1955     FrameReport::GetInstance().SetGameScene(info.pid, info.state);
1956 }
1957 
SetHardwareEnabled(NodeId id,bool isEnabled,SelfDrawingNodeType selfDrawingType,bool dynamicHardwareEnable)1958 void RSRenderServiceConnection::SetHardwareEnabled(NodeId id, bool isEnabled, SelfDrawingNodeType selfDrawingType,
1959     bool dynamicHardwareEnable)
1960 {
1961     if (!mainThread_) {
1962         return;
1963     }
1964     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, isEnabled, selfDrawingType,
1965         dynamicHardwareEnable]() -> void {
1966         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1967         if (!connection) {
1968             return;
1969         }
1970         auto& context = connection->mainThread_->GetContext();
1971         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
1972         if (node) {
1973             node->SetHardwareEnabled(isEnabled, selfDrawingType, dynamicHardwareEnable);
1974         }
1975     };
1976     mainThread_->PostTask(task);
1977 }
1978 
SetHidePrivacyContent(NodeId id,bool needHidePrivacyContent)1979 uint32_t RSRenderServiceConnection::SetHidePrivacyContent(NodeId id, bool needHidePrivacyContent)
1980 {
1981     if (!mainThread_) {
1982         return static_cast<int32_t>(RSInterfaceErrorCode::UNKNOWN_ERROR);
1983     }
1984     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, needHidePrivacyContent]() -> void {
1985         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1986         if (!connection) {
1987             return;
1988         }
1989         auto& context = connection->mainThread_->GetContext();
1990         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
1991         if (node) {
1992             node->SetHidePrivacyContent(needHidePrivacyContent);
1993         }
1994     };
1995     mainThread_->PostTask(task);
1996     return static_cast<uint32_t>(RSInterfaceErrorCode::NO_ERROR);
1997 }
1998 
SetCacheEnabledForRotation(bool isEnabled)1999 void RSRenderServiceConnection::SetCacheEnabledForRotation(bool isEnabled)
2000 {
2001     if (!mainThread_) {
2002         return;
2003     }
2004     auto task = [isEnabled]() {
2005         RSSystemProperties::SetCacheEnabledForRotation(isEnabled);
2006     };
2007     mainThread_->PostTask(task);
2008 }
2009 
GetActiveDirtyRegionInfo()2010 std::vector<ActiveDirtyRegionInfo> RSRenderServiceConnection::GetActiveDirtyRegionInfo()
2011 {
2012     const auto& activeDirtyRegionInfos = GpuDirtyRegionCollection::GetInstance().GetActiveDirtyRegionInfo();
2013     GpuDirtyRegionCollection::GetInstance().ResetActiveDirtyRegionInfo();
2014     return activeDirtyRegionInfos;
2015 }
2016 
GetGlobalDirtyRegionInfo()2017 GlobalDirtyRegionInfo RSRenderServiceConnection::GetGlobalDirtyRegionInfo()
2018 {
2019     const auto& globalDirtyRegionInfo = GpuDirtyRegionCollection::GetInstance().GetGlobalDirtyRegionInfo();
2020     GpuDirtyRegionCollection::GetInstance().ResetGlobalDirtyRegionInfo();
2021     return globalDirtyRegionInfo;
2022 }
2023 
GetLayerComposeInfo()2024 LayerComposeInfo RSRenderServiceConnection::GetLayerComposeInfo()
2025 {
2026     const auto& layerComposeInfo = LayerComposeCollection::GetInstance().GetLayerComposeInfo();
2027     LayerComposeCollection::GetInstance().ResetLayerComposeInfo();
2028     return layerComposeInfo;
2029 }
2030 
GetHwcDisabledReasonInfo()2031 HwcDisabledReasonInfos RSRenderServiceConnection::GetHwcDisabledReasonInfo()
2032 {
2033     return HwcDisabledReasonCollection::GetInstance().GetHwcDisabledReasonInfo();
2034 }
2035 
SetVmaCacheStatus(bool flag)2036 void RSRenderServiceConnection::SetVmaCacheStatus(bool flag)
2037 {
2038     renderThread_.SetVmaCacheStatus(flag);
2039 }
2040 
2041 #ifdef TP_FEATURE_ENABLE
SetTpFeatureConfig(int32_t feature,const char * config,TpFeatureConfigType tpFeatureConfigType)2042 void RSRenderServiceConnection::SetTpFeatureConfig(int32_t feature, const char* config,
2043     TpFeatureConfigType tpFeatureConfigType)
2044 {
2045     switch (tpFeatureConfigType) {
2046         case TpFeatureConfigType::DEFAULT_TP_FEATURE: {
2047             if (!TOUCH_SCREEN->IsSetFeatureConfigHandleValid()) {
2048                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfigHandl is nullptr");
2049                 return;
2050             }
2051             if (TOUCH_SCREEN->SetFeatureConfig(feature, config) < 0) {
2052                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetFeatureConfig failed");
2053                 return;
2054             }
2055             break;
2056         }
2057         case TpFeatureConfigType::AFT_TP_FEATURE: {
2058             if (!TOUCH_SCREEN->IsSetAftConfigHandleValid()) {
2059                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfigHandl is nullptr");
2060                 return;
2061             }
2062             if (TOUCH_SCREEN->SetAftConfig(config) < 0) {
2063                 RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: SetAftConfig failed");
2064                 return;
2065             }
2066             break;
2067         }
2068         default: {
2069             RS_LOGW("RSRenderServiceConnection::SetTpFeatureConfig: unknown TpFeatureConfigType: %" PRIu8"",
2070                 static_cast<uint8_t>(tpFeatureConfigType));
2071             return;
2072         }
2073     }
2074 }
2075 #endif
2076 
SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)2077 void RSRenderServiceConnection::SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)
2078 {
2079     if (isVirtualScreenUsingStatus) {
2080         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ };
2081         NotifyRefreshRateEvent(event);
2082     } else {
2083         EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
2084         NotifyRefreshRateEvent(event);
2085     }
2086     return;
2087 }
2088 
SetCurtainScreenUsingStatus(bool isCurtainScreenOn)2089 void RSRenderServiceConnection::SetCurtainScreenUsingStatus(bool isCurtainScreenOn)
2090 {
2091     if (!mainThread_) {
2092         return;
2093     }
2094     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isCurtainScreenOn]() -> void {
2095         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2096         if (!connection) {
2097             return;
2098         }
2099         connection->mainThread_->SetCurtainScreenUsingStatus(isCurtainScreenOn);
2100     };
2101     mainThread_->PostTask(task);
2102 }
2103 
DropFrameByPid(const std::vector<int32_t> pidList)2104 void RSRenderServiceConnection::DropFrameByPid(const std::vector<int32_t> pidList)
2105 {
2106     if (!mainThread_) {
2107         return;
2108     }
2109     mainThread_->ScheduleTask(
2110         [weakThis = wptr<RSRenderServiceConnection>(this), pidList]() {
2111             // don't use 'this' directly
2112             sptr<RSRenderServiceConnection> connection = weakThis.promote();
2113             if (connection == nullptr || connection->mainThread_ == nullptr) {
2114                 return;
2115             }
2116             connection->mainThread_->AddPidNeedDropFrame(pidList);
2117         }
2118     );
2119 }
2120 
RegisterUIExtensionCallback(uint64_t userId,sptr<RSIUIExtensionCallback> callback,bool unobscured)2121 int32_t RSRenderServiceConnection::RegisterUIExtensionCallback(uint64_t userId, sptr<RSIUIExtensionCallback> callback,
2122     bool unobscured)
2123 {
2124     if (!mainThread_) {
2125         return StatusCode::INVALID_ARGUMENTS;
2126     }
2127     std::lock_guard<std::mutex> lock(mutex_);
2128     if (!callback) {
2129         RS_LOGE("RSRenderServiceConnection::RegisterUIExtensionCallback register null callback, failed.");
2130         return StatusCode::INVALID_ARGUMENTS;
2131     }
2132     mainThread_->RegisterUIExtensionCallback(remotePid_, userId, callback, unobscured);
2133     return StatusCode::SUCCESS;
2134 }
2135 
SetAncoForceDoDirect(bool direct)2136 bool RSRenderServiceConnection::SetAncoForceDoDirect(bool direct)
2137 {
2138     std::lock_guard<std::mutex> lock(mutex_);
2139     mainThread_->SetAncoForceDoDirect(direct);
2140     return true;
2141 }
2142 
RegisterSurfaceBufferCallback(pid_t pid,uint64_t uid,sptr<RSISurfaceBufferCallback> callback)2143 void RSRenderServiceConnection::RegisterSurfaceBufferCallback(pid_t pid, uint64_t uid,
2144     sptr<RSISurfaceBufferCallback> callback)
2145 {
2146     RSSurfaceBufferCallbackManager::Instance().RegisterSurfaceBufferCallback(pid, uid, callback);
2147 }
2148 
UnregisterSurfaceBufferCallback(pid_t pid,uint64_t uid)2149 void RSRenderServiceConnection::UnregisterSurfaceBufferCallback(pid_t pid, uint64_t uid)
2150 {
2151     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(pid, uid);
2152 }
2153 
SetLayerTop(const std::string & nodeIdStr,bool isTop)2154 void RSRenderServiceConnection::SetLayerTop(const std::string &nodeIdStr, bool isTop)
2155 {
2156     if (mainThread_ == nullptr) {
2157         return;
2158     }
2159     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isTop]() -> void {
2160         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2161         if (!connection) {
2162             return;
2163         }
2164         auto& context = connection->mainThread_->GetContext();
2165         context.GetNodeMap().TraverseSurfaceNodes(
2166             [&nodeIdStr, &isTop](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
2167             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
2168                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
2169                 surfaceNode->SetLayerTop(isTop);
2170                 return;
2171             }
2172         });
2173         // It can be displayed immediately after layer-top changed.
2174         connection->mainThread_->SetDirtyFlag();
2175         connection->mainThread_->RequestNextVSync();
2176     };
2177     mainThread_->PostTask(task);
2178 }
2179 
NotifyScreenSwitched()2180 void RSRenderServiceConnection::NotifyScreenSwitched()
2181 {
2182     std::lock_guard<std::mutex> lock(mutex_);
2183     if (!screenManager_) {
2184         RS_LOGE("RSRenderServiceConnection::NotifyScreenSwitched screenManager_ is nullptr");
2185         return;
2186     }
2187     RS_LOGI("RSRenderServiceConnection::NotifyScreenSwitched SetScreenSwitchStatus true");
2188     RS_TRACE_NAME_FMT("NotifyScreenSwitched");
2189     screenManager_->SetScreenSwitchStatus(true);
2190 }
2191 
SetWindowContainer(NodeId nodeId,bool value)2192 void RSRenderServiceConnection::SetWindowContainer(NodeId nodeId, bool value)
2193 {
2194     if (!mainThread_) {
2195         return;
2196     }
2197     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeId, value]() -> void {
2198         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2199         if (connection == nullptr || connection->mainThread_ == nullptr) {
2200             return;
2201         }
2202         auto& nodeMap = connection->mainThread_->GetContext().GetNodeMap();
2203         if (auto node = nodeMap.GetRenderNode<RSCanvasRenderNode>(nodeId)) {
2204             auto displayNodeId = node->GetDisplayNodeId();
2205             if (auto displayNode = nodeMap.GetRenderNode<RSDisplayRenderNode>(displayNodeId)) {
2206                 RS_LOGD("RSRenderServiceConnection::SetWindowContainer nodeId: %{public}" PRIu64 ", value: %{public}d",
2207                     nodeId, value);
2208                 displayNode->SetWindowContainer(value ? node : nullptr);
2209             } else {
2210                 RS_LOGE("RSRenderServiceConnection::SetWindowContainer displayNode is nullptr, nodeId: %{public}"
2211                     PRIu64, displayNodeId);
2212             }
2213         } else {
2214             RS_LOGE("RSRenderServiceConnection::SetWindowContainer node is nullptr, nodeId: %{public}" PRIu64,
2215                 nodeId);
2216         }
2217     };
2218     mainThread_->PostTask(task);
2219 }
2220 } // namespace Rosen
2221 } // namespace OHOS
2222