• 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 "offscreen_render/rs_offscreen_render_thread.h"
24 #include "rs_frame_report.h"
25 #include "rs_main_thread.h"
26 #include "rs_trace.h"
27 #include "rs_profiler.h"
28 //blur predict
29 #include "rs_frame_blur_predict.h"
30 #include "system/rs_system_parameters.h"
31 
32 #include "command/rs_command_verify_helper.h"
33 #include "command/rs_display_node_command.h"
34 #include "command/rs_surface_node_command.h"
35 #include "common/rs_background_thread.h"
36 #include "dirty_region/rs_gpu_dirty_collector.h"
37 #include "dirty_region/rs_optimize_canvas_dirty_collector.h"
38 #include "display_engine/rs_luminance_control.h"
39 #include "drawable/rs_canvas_drawing_render_node_drawable.h"
40 #include "feature/capture/rs_ui_capture.h"
41 #include "feature/capture/rs_uni_ui_capture.h"
42 #include "feature/capture/rs_surface_capture_task.h"
43 #include "feature/capture/rs_ui_capture_task_parallel.h"
44 #include "feature/capture/rs_ui_capture_solo_task_parallel.h"
45 #include "feature/capture/rs_surface_capture_task_parallel.h"
46 #include "feature/uifirst/rs_uifirst_frame_rate_control.h"
47 #include "gfx/fps_info/rs_surface_fps_manager.h"
48 #include "gfx/first_frame_notifier/rs_first_frame_notifier.h"
49 #ifdef RS_ENABLE_OVERLAY_DISPLAY
50 #include "feature/overlay_display/rs_overlay_display_manager.h"
51 #endif
52 #include "info_collection/rs_hdr_collection.h"
53 #ifdef RS_ENABLE_GPU
54 #include "feature/uifirst/rs_sub_thread_manager.h"
55 #endif
56 #include "feature/uifirst/rs_uifirst_manager.h"
57 #include "memory/rs_memory_manager.h"
58 #include "monitor/self_drawing_node_monitor.h"
59 #include "pipeline/rs_canvas_drawing_render_node.h"
60 #include "pipeline/rs_pointer_window_manager.h"
61 #ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
62 #include "pipeline/magic_pointer_render/rs_magic_pointer_render_manager.h"
63 #endif
64 #include "pipeline/hardware_thread/rs_realtime_refresh_rate_manager.h"
65 #include "pipeline/rs_render_frame_rate_linker_map.h"
66 #include "pipeline/rs_render_node_gc.h"
67 #include "pipeline/rs_render_node_map.h"
68 #include "pipeline/main_thread/rs_render_service_listener.h"
69 #include "pipeline/rs_surface_buffer_callback_manager.h"
70 #include "pipeline/rs_surface_render_node.h"
71 #include "pipeline/rs_task_dispatcher.h"
72 #include "pipeline/rs_uni_render_judgement.h"
73 #include "pixel_map_from_surface.h"
74 #include "platform/common/rs_log.h"
75 #include "platform/common/rs_system_properties.h"
76 #include "platform/ohos/rs_jank_stats_helper.h"
77 #include "render/rs_typeface_cache.h"
78 #include "transaction/rs_unmarshal_thread.h"
79 #include "transaction/rs_transaction_data_callback_manager.h"
80 #include "graphic_feature_param_manager.h"
81 
82 #ifdef TP_FEATURE_ENABLE
83 #include "screen_manager/touch_screen.h"
84 #endif
85 
86 #ifdef RS_ENABLE_VK
87 #include "platform/ohos/backend/rs_vulkan_context.h"
88 #endif
89 
90 #if defined(RS_ENABLE_DVSYNC)
91 #include "dvsync.h"
92 #endif
93 
94 #undef LOG_TAG
95 #define LOG_TAG "RSRenderServiceConnection"
96 
97 namespace OHOS {
98 namespace Rosen {
99 namespace {
100 constexpr int SLEEP_TIME_US = 1000;
101 const std::string REGISTER_NODE = "RegisterNode";
102 const std::string APS_SET_VSYNC = "APS_SET_VSYNC";
103 constexpr uint32_t MEM_BYTE_TO_MB = 1024 * 1024;
104 constexpr uint32_t MAX_BLACK_LIST_NUM = 1024;
105 constexpr uint32_t MAX_WHITE_LIST_NUM = 1024;
106 constexpr uint32_t PIDLIST_SIZE_MAX = 128;
107 constexpr uint64_t BUFFER_USAGE_GPU_RENDER_DIRTY = BUFFER_USAGE_HW_RENDER | BUFFER_USAGE_AUXILLARY_BUFFER0;
108 constexpr uint64_t MAX_TIME_OUT_NS = 1e9;
109 }
110 // we guarantee that when constructing this object,
111 // 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)112 RSRenderServiceConnection::RSRenderServiceConnection(
113     pid_t remotePid,
114     wptr<RSRenderService> renderService,
115     RSMainThread* mainThread,
116     sptr<RSScreenManager> screenManager,
117     sptr<IRemoteObject> token,
118     sptr<VSyncDistributor> distributor)
119     : remotePid_(remotePid),
120       renderService_(renderService),
121       mainThread_(mainThread),
122 #ifdef RS_ENABLE_GPU
123       renderThread_(RSUniRenderThread::Instance()),
124 #endif
125       screenManager_(screenManager),
126       token_(token),
127       connDeathRecipient_(new RSConnectionDeathRecipient(this)),
128       applicationDeathRecipient_(new RSApplicationRenderThreadDeathRecipient(this)),
129       appVSyncDistributor_(distributor)
130 {
131     if (token_ == nullptr || !token_->AddDeathRecipient(connDeathRecipient_)) {
132         RS_LOGW("RSRenderServiceConnection: Failed to set death recipient.");
133     }
134     if (renderService_ == nullptr) {
135         RS_LOGW("RSRenderServiceConnection: renderService_ is nullptr");
136     }
137     if (mainThread_ == nullptr) {
138         RS_LOGW("RSRenderServiceConnection: mainThread_ is nullptr");
139     }
140     if (screenManager_ == nullptr) {
141         RS_LOGW("RSRenderServiceConnection: screenManager_ is nullptr");
142     }
143     if (appVSyncDistributor_ == nullptr) {
144         RS_LOGW("RSRenderServiceConnection: appVSyncDistributor_ is nullptr");
145     }
146 }
147 
~RSRenderServiceConnection()148 RSRenderServiceConnection::~RSRenderServiceConnection() noexcept
149 {
150     if (token_ && connDeathRecipient_) {
151         token_->RemoveDeathRecipient(connDeathRecipient_);
152     }
153     CleanAll();
154 }
155 
CleanVirtualScreens()156 void RSRenderServiceConnection::CleanVirtualScreens() noexcept
157 {
158     std::lock_guard<std::mutex> lock(mutex_);
159 
160     if (screenManager_ != nullptr) {
161         for (const auto id : virtualScreenIds_) {
162             screenManager_->RemoveVirtualScreen(id);
163         }
164     }
165     virtualScreenIds_.clear();
166 
167     if (screenChangeCallback_ != nullptr && screenManager_ != nullptr) {
168         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
169         screenChangeCallback_ = nullptr;
170     }
171 }
172 
CleanRenderNodes()173 void RSRenderServiceConnection::CleanRenderNodes() noexcept
174 {
175     if (mainThread_ == nullptr) {
176         return;
177     }
178     auto& context = mainThread_->GetContext();
179     auto& nodeMap = context.GetMutableNodeMap();
180 
181     nodeMap.FilterNodeByPid(remotePid_);
182 }
183 
CleanFrameRateLinkers()184 void RSRenderServiceConnection::CleanFrameRateLinkers() noexcept
185 {
186     if (mainThread_ == nullptr) {
187         return;
188     }
189     auto& context = mainThread_->GetContext();
190     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
191 
192     frameRateLinkerMap.FilterFrameRateLinkerByPid(remotePid_);
193 }
194 
CleanFrameRateLinkerExpectedFpsCallbacks()195 void RSRenderServiceConnection::CleanFrameRateLinkerExpectedFpsCallbacks() noexcept
196 {
197     if (mainThread_ == nullptr) {
198         return;
199     }
200     auto& context = mainThread_->GetContext();
201     auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
202     frameRateLinkerMap.UnRegisterExpectedFpsUpdateCallbackByListener(remotePid_);
203 }
204 
CleanAll(bool toDelete)205 void RSRenderServiceConnection::CleanAll(bool toDelete) noexcept
206 {
207     {
208         std::lock_guard<std::mutex> lock(mutex_);
209         if (cleanDone_) {
210             return;
211         }
212     }
213     if (!mainThread_) {
214         return;
215     }
216     RS_LOGD("CleanAll() start.");
217     RS_TRACE_NAME("RSRenderServiceConnection CleanAll begin, remotePid: " + std::to_string(remotePid_));
218     RsCommandVerifyHelper::GetInstance().RemoveCntWithPid(remotePid_);
219     mainThread_->ScheduleTask(
220         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
221             sptr<RSRenderServiceConnection> connection = weakThis.promote();
222             if (!connection) {
223                 return;
224             }
225             RS_TRACE_NAME_FMT("CleanVirtualScreens %d", connection->remotePid_);
226             connection->CleanVirtualScreens();
227         }).wait();
228     mainThread_->ScheduleTask(
229         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
230             sptr<RSRenderServiceConnection> connection = weakThis.promote();
231             if (!connection) {
232                 return;
233             }
234             RS_TRACE_NAME_FMT("CleanRenderNodes %d", connection->remotePid_);
235             connection->CleanRenderNodes();
236             connection->CleanFrameRateLinkers();
237             connection->CleanFrameRateLinkerExpectedFpsCallbacks();
238         }).wait();
239     mainThread_->ScheduleTask(
240         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
241             sptr<RSRenderServiceConnection> connection = weakThis.promote();
242             if (connection == nullptr || connection->mainThread_ == nullptr) {
243                 return;
244             }
245             RS_TRACE_NAME_FMT("ClearTransactionDataPidInfo %d", connection->remotePid_);
246             connection->mainThread_->ClearTransactionDataPidInfo(connection->remotePid_);
247         }).wait();
248     mainThread_->ScheduleTask(
249         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
250             sptr<RSRenderServiceConnection> connection = weakThis.promote();
251             if (connection == nullptr || connection->mainThread_ == nullptr) {
252                 return;
253             }
254             RS_TRACE_NAME_FMT("UnRegisterCallback %d", connection->remotePid_);
255             connection->mainThread_->UnRegisterOcclusionChangeCallback(connection->remotePid_);
256             connection->mainThread_->ClearSurfaceOcclusionChangeCallback(connection->remotePid_);
257             connection->mainThread_->UnRegisterUIExtensionCallback(connection->remotePid_);
258         }).wait();
259 
260     mainThread_->ScheduleTask(
261         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
262             sptr<RSRenderServiceConnection> connection = weakThis.promote();
263             if (connection == nullptr || connection->mainThread_ == nullptr) {
264                 return;
265             }
266             connection->mainThread_->ClearWatermark(connection->remotePid_);
267         }).wait();
268     if (SelfDrawingNodeMonitor::GetInstance().IsListeningEnabled()) {
269         mainThread_->ScheduleTask(
270             [weakThis = wptr<RSRenderServiceConnection>(this)]() {
271                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
272                 if (connection == nullptr) {
273                     return;
274                 }
275                 auto &monitor = SelfDrawingNodeMonitor::GetInstance();
276                 monitor.UnRegisterRectChangeCallback(connection->remotePid_);
277             }).wait();
278     }
279     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(remotePid_);
280     HgmTaskHandleThread::Instance().ScheduleTask([pid = remotePid_] () {
281         RS_TRACE_NAME_FMT("CleanHgmEvent %d", pid);
282         HgmConfigCallbackManager::GetInstance()->UnRegisterHgmConfigChangeCallback(pid);
283         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
284         if (frameRateMgr != nullptr) {
285             frameRateMgr->CleanVote(pid);
286         }
287     }).wait();
288     RSTypefaceCache::Instance().RemoveDrawingTypefacesByPid(remotePid_);
289     {
290         std::lock_guard<std::mutex> lock(mutex_);
291         cleanDone_ = true;
292     }
293 
294     if (toDelete) {
295         auto renderService = renderService_.promote();
296         if (renderService == nullptr) {
297             RS_LOGW("CleanAll() RenderService is dead.");
298         } else {
299             renderService->RemoveConnection(GetToken());
300         }
301     }
302 
303     RS_LOGD("CleanAll() end.");
304     RS_TRACE_NAME("RSRenderServiceConnection CleanAll end, remotePid: " + std::to_string(remotePid_));
305 }
306 
RSConnectionDeathRecipient(wptr<RSRenderServiceConnection> conn)307 RSRenderServiceConnection::RSConnectionDeathRecipient::RSConnectionDeathRecipient(
308     wptr<RSRenderServiceConnection> conn) : conn_(conn)
309 {
310 }
311 
OnRemoteDied(const wptr<IRemoteObject> & token)312 void RSRenderServiceConnection::RSConnectionDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
313 {
314     auto tokenSptr = token.promote();
315     if (tokenSptr == nullptr) {
316         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: can't promote remote object.");
317         return;
318     }
319 
320     auto rsConn = conn_.promote();
321     if (rsConn == nullptr) {
322         RS_LOGW("RSConnectionDeathRecipient::OnRemoteDied: RSRenderServiceConnection was dead, do nothing.");
323         return;
324     }
325 
326     if (rsConn->GetToken() != tokenSptr) {
327         RS_LOGI("RSConnectionDeathRecipient::OnRemoteDied: token doesn't match, ignore it.");
328         return;
329     }
330 
331     rsConn->CleanAll(true);
332 }
333 
RSApplicationRenderThreadDeathRecipient(wptr<RSRenderServiceConnection> conn)334 RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::RSApplicationRenderThreadDeathRecipient(
335     wptr<RSRenderServiceConnection> conn) : conn_(conn)
336 {}
337 
OnRemoteDied(const wptr<IRemoteObject> & token)338 void RSRenderServiceConnection::RSApplicationRenderThreadDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& token)
339 {
340     auto tokenSptr = token.promote();
341     if (tokenSptr == nullptr) {
342         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: can't promote remote object.");
343         return;
344     }
345 
346     auto rsConn = conn_.promote();
347     if (rsConn == nullptr) {
348         RS_LOGW("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: "
349             "RSRenderServiceConnection was dead, do nothing.");
350         return;
351     }
352 
353     RS_LOGD("RSApplicationRenderThreadDeathRecipient::OnRemoteDied: Unregister.");
354     auto app = iface_cast<IApplicationAgent>(tokenSptr);
355     rsConn->UnRegisterApplicationAgent(app);
356 }
357 
CommitTransaction(std::unique_ptr<RSTransactionData> & transactionData)358 ErrCode RSRenderServiceConnection::CommitTransaction(std::unique_ptr<RSTransactionData>& transactionData)
359 {
360     if (!mainThread_) {
361         return ERR_INVALID_VALUE;
362     }
363     pid_t callingPid = GetCallingPid();
364     bool isTokenTypeValid = true;
365     bool isNonSystemAppCalling = false;
366     RSInterfaceCodeAccessVerifierBase::GetAccessType(isTokenTypeValid, isNonSystemAppCalling);
367     bool shouldDrop = RSUnmarshalThread::Instance().ReportTransactionDataStatistics(
368         callingPid, transactionData.get(), isNonSystemAppCalling);
369     if (shouldDrop) {
370         RS_LOGW("CommitTransaction data droped");
371         return ERR_INVALID_VALUE;
372     }
373     if (transactionData && transactionData->GetDVSyncUpdate()) {
374         mainThread_->DVSyncUpdate(transactionData->GetDVSyncTime(), transactionData->GetTimestamp());
375     }
376     bool isProcessBySingleFrame = mainThread_->IsNeedProcessBySingleFrameComposer(transactionData);
377     if (isProcessBySingleFrame) {
378         mainThread_->ProcessDataBySingleFrameComposer(transactionData);
379     } else {
380         mainThread_->RecvRSTransactionData(transactionData);
381     }
382     return ERR_OK;
383 }
384 
ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask> & task)385 ErrCode RSRenderServiceConnection::ExecuteSynchronousTask(const std::shared_ptr<RSSyncTask>& task)
386 {
387     if (task == nullptr || mainThread_ == nullptr) {
388         RS_LOGW("ExecuteSynchronousTask, task or main thread is null!");
389         return ERR_INVALID_VALUE;
390     }
391     // After a synchronous task times out, it will no longer be executed.
392     auto isTimeout = std::make_shared<bool>(0);
393     std::weak_ptr<bool> isTimeoutWeak = isTimeout;
394     std::chrono::nanoseconds span(std::min(task->GetTimeout(), MAX_TIME_OUT_NS));
395     mainThread_->ScheduleTask([task, mainThread = mainThread_, isTimeoutWeak] {
396         if (task == nullptr || mainThread == nullptr || isTimeoutWeak.expired()) {
397             return;
398         }
399         task->Process(mainThread->GetContext());
400     }).wait_for(span);
401     isTimeout.reset();
402     return ERR_OK;
403 }
404 
GetUniRenderEnabled(bool & enable)405 ErrCode RSRenderServiceConnection::GetUniRenderEnabled(bool& enable)
406 {
407     enable = RSUniRenderJudgement::IsUniRender();
408     return  ERR_OK;
409 }
410 
CreateNode(const RSDisplayNodeConfig & displayNodeConfig,NodeId nodeId,bool & success)411 ErrCode RSRenderServiceConnection::CreateNode(const RSDisplayNodeConfig& displayNodeConfig, NodeId nodeId,
412     bool& success)
413 {
414     if (!mainThread_) {
415         success = false;
416         return ERR_INVALID_VALUE;
417     }
418     auto node = DisplayNodeCommandHelper::CreateWithConfigInRS(mainThread_->GetContext(), nodeId, displayNodeConfig);
419     if (node == nullptr) {
420         RS_LOGE("RSRenderService::CreateDisplayNode fail");
421         success = false;
422         return ERR_INVALID_VALUE;
423     }
424     std::function<void()> registerNode = [this, nodeId, node, &displayNodeConfig]() {
425         if (mainThread_ == nullptr) {
426             return;
427         }
428         auto& context = mainThread_->GetContext();
429         auto& nodeMap = context.GetMutableNodeMap();
430         nodeMap.RegisterRenderNode(node);
431         nodeMap.TraverseScreenNodes([&node, id = node->GetScreenId()](auto& screenNode) {
432             if (!screenNode || screenNode->GetScreenId() != id) {
433                 return;
434             }
435             screenNode->AddChild(node);
436         });
437 
438         DisplayNodeCommandHelper::SetDisplayMode(context, nodeId, displayNodeConfig);
439     };
440     mainThread_->PostSyncTask(registerNode);
441     success = true;
442     return ERR_OK;
443 }
444 
CreateNode(const RSSurfaceRenderNodeConfig & config,bool & success)445 ErrCode RSRenderServiceConnection::CreateNode(const RSSurfaceRenderNodeConfig& config, bool& success)
446 {
447     if (!mainThread_) {
448         success = false;
449         return ERR_INVALID_VALUE;
450     }
451     std::shared_ptr<RSSurfaceRenderNode> node =
452         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext());
453     if (node == nullptr) {
454         RS_LOGE("RSRenderService::CreateNode fail");
455         success = false;
456         return ERR_INVALID_VALUE;
457     }
458     std::function<void()> registerNode = [node, weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
459         sptr<RSRenderServiceConnection> connection = weakThis.promote();
460         if (connection == nullptr || connection->mainThread_ == nullptr) {
461             return;
462         }
463         connection->mainThread_->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
464     };
465     mainThread_->PostTask(registerNode);
466     success = true;
467     return ERR_OK;
468 }
469 
CreateNodeAndSurface(const RSSurfaceRenderNodeConfig & config,sptr<Surface> & sfc,bool unobscured)470 ErrCode RSRenderServiceConnection::CreateNodeAndSurface(const RSSurfaceRenderNodeConfig& config,
471     sptr<Surface>& sfc, bool unobscured)
472 {
473     if (!mainThread_) {
474         return ERR_INVALID_VALUE;
475     }
476     std::shared_ptr<RSSurfaceRenderNode> node =
477         SurfaceNodeCommandHelper::CreateWithConfigInRS(config, mainThread_->GetContext(), unobscured);
478     if (node == nullptr) {
479         RS_LOGE("RSRenderService::CreateNodeAndSurface CreateNode fail");
480         return ERR_INVALID_VALUE;
481     }
482     sptr<IConsumerSurface> surface = IConsumerSurface::Create(config.name);
483     if (surface == nullptr) {
484         RS_LOGE("RSRenderService::CreateNodeAndSurface get consumer surface fail");
485         return ERR_INVALID_VALUE;
486     }
487     const std::string& surfaceName = surface->GetName();
488     RS_LOGI("RsDebug RSRenderService::CreateNodeAndSurface node"
489         "id:%{public}" PRIu64 " name:%{public}s surface id:%{public}" PRIu64 " name:%{public}s",
490         node->GetId(), node->GetName().c_str(),
491         surface->GetUniqueId(), surfaceName.c_str());
492     auto defaultUsage = surface->GetDefaultUsage();
493     auto nodeId = node->GetId();
494     bool isUseSelfDrawBufferUsage = RSSystemProperties::GetSelfDrawingDirtyRegionEnabled() &&
495         RSGpuDirtyCollector::GetInstance().IsGpuDirtyEnable(nodeId) &&
496         config.nodeType == RSSurfaceNodeType::SELF_DRAWING_NODE;
497     if (isUseSelfDrawBufferUsage) {
498         defaultUsage |= BUFFER_USAGE_GPU_RENDER_DIRTY;
499     }
500     surface->SetDefaultUsage(defaultUsage | BUFFER_USAGE_MEM_DMA | BUFFER_USAGE_HW_COMPOSER);
501     node->GetRSSurfaceHandler()->SetConsumer(surface);
502     RSMainThread* mainThread = mainThread_;
503     std::function<void()> registerNode = [node, mainThread]() -> void {
504         if (auto preNode = mainThread->GetContext().GetNodeMap().GetRenderNode(node->GetId())) {
505             if (auto preSurfaceNode = node->ReinterpretCastTo<RSSurfaceRenderNode>()) {
506                 RS_LOGE("CreateNodeAndSurface same id node:%{public}" PRIu64 ", name:%{public}s, type:%{public}d",
507                     node->GetId(), preSurfaceNode->GetName().c_str(), preNode->GetType());
508             } else {
509                 RS_LOGE("CreateNodeAndSurface same id node:%{public}" PRIu64 ", type:%{public}d", node->GetId(),
510                     preNode->GetType());
511             }
512             usleep(SLEEP_TIME_US);
513         }
514         RS_LOGI("CreateNodeAndSurface RegisterRenderNode id:%{public}" PRIu64 ", name:%{public}s", node->GetId(),
515             node->GetName().c_str());
516         mainThread->GetContext().GetMutableNodeMap().RegisterRenderNode(node);
517     };
518     if (config.isSync) {
519         mainThread_->PostSyncTask(registerNode);
520     } else {
521         mainThread_->PostTask(registerNode, REGISTER_NODE, 0, AppExecFwk::EventQueue::Priority::VIP);
522     }
523     std::weak_ptr<RSSurfaceRenderNode> surfaceRenderNode(node);
524     sptr<IBufferConsumerListener> listener = new RSRenderServiceListener(surfaceRenderNode);
525     SurfaceError ret = surface->RegisterConsumerListener(listener);
526     if (ret != SURFACE_ERROR_OK) {
527         RS_LOGE("RSRenderService::CreateNodeAndSurface Register Consumer Listener fail");
528         return ERR_INVALID_VALUE;
529     }
530     sptr<IBufferProducer> producer = surface->GetProducer();
531     sfc = Surface::CreateSurfaceAsProducer(producer);
532     return ERR_OK;
533 }
534 
CreateVSyncConnection(sptr<IVSyncConnection> & vsyncConn,const std::string & name,const sptr<VSyncIConnectionToken> & token,VSyncConnParam vsyncConnParam)535 ErrCode RSRenderServiceConnection::CreateVSyncConnection(sptr<IVSyncConnection>& vsyncConn,
536                                                          const std::string& name,
537                                                          const sptr<VSyncIConnectionToken>& token,
538                                                          VSyncConnParam vsyncConnParam)
539 {
540     if (mainThread_ == nullptr || appVSyncDistributor_ == nullptr) {
541         vsyncConn = nullptr;
542         return ERR_INVALID_VALUE;
543     }
544     uint64_t id = vsyncConnParam.id;
545     NodeId windowNodeId = vsyncConnParam.windowNodeId;
546     if (vsyncConnParam.fromXcomponent) {
547         mainThread_->ScheduleTask([&windowNodeId]() {
548             auto& node = RSMainThread::Instance()->GetContext().GetNodeMap()
549                         .GetRenderNode<RSRenderNode>(windowNodeId);
550             if (node == nullptr) {
551                 RS_LOGE("CreateVSyncConnection:node is nullptr");
552                 return;
553             }
554             windowNodeId = node->GetInstanceRootNodeId();
555         }).wait();
556     }
557     sptr<VSyncConnection> conn = new VSyncConnection(appVSyncDistributor_, name, token->AsObject(), 0, windowNodeId);
558     if (ExtractPid(id) == remotePid_) {
559         auto observer = [] (const RSRenderFrameRateLinker& linker) {
560             if (auto mainThread = RSMainThread::Instance(); mainThread != nullptr) {
561                 HgmCore::Instance().SetHgmTaskFlag(true);
562             }
563         };
564         mainThread_->ScheduleTask([weakThis = wptr<RSRenderServiceConnection>(this),
565             id, observer, name, windowNodeId]() {
566             sptr<RSRenderServiceConnection> connection = weakThis.promote();
567             if (connection == nullptr || connection->mainThread_ == nullptr) {
568                 return;
569             }
570             auto linker = std::make_shared<RSRenderFrameRateLinker>(id, observer);
571             linker->SetVsyncName(name);
572             linker->SetWindowNodeId(windowNodeId);
573             auto& context = connection->mainThread_->GetContext();
574             auto& frameRateLinkerMap = context.GetMutableFrameRateLinkerMap();
575             frameRateLinkerMap.RegisterFrameRateLinker(linker);
576         }).wait();
577         conn->id_ = id;
578         RS_LOGD("CreateVSyncConnection connect id: %{public}" PRIu64, id);
579     }
580     auto ret = appVSyncDistributor_->AddConnection(conn, windowNodeId);
581     if (ret != VSYNC_ERROR_OK) {
582         UnregisterFrameRateLinker(conn->id_);
583         vsyncConn = nullptr;
584         return ERR_INVALID_VALUE;
585     }
586     vsyncConn = conn;
587     return ERR_OK;
588 }
589 
GetPixelMapByProcessId(std::vector<PixelMapInfo> & pixelMapInfoVector,pid_t pid,int32_t & repCode)590 ErrCode RSRenderServiceConnection::GetPixelMapByProcessId(
591     std::vector<PixelMapInfo>& pixelMapInfoVector, pid_t pid, int32_t& repCode)
592 {
593     if (mainThread_ == nullptr) {
594         repCode = INVALID_ARGUMENTS;
595         return ERR_INVALID_VALUE;
596     }
597     std::vector<std::tuple<sptr<SurfaceBuffer>, std::string, RectI>> sfBufferInfoVector;
598     std::function<void()> getSurfaceBufferByPidTask = [weakThis = wptr<RSRenderServiceConnection>(this),
599                                                           &sfBufferInfoVector, pid]() -> void {
600         sptr<RSRenderServiceConnection> connection = weakThis.promote();
601         if (connection == nullptr || connection->mainThread_ == nullptr) {
602             return;
603         }
604         RS_TRACE_NAME_FMT("RSRenderServiceConnection::GetPixelMapByProcessId getSurfaceBufferByPidTask pid: %d", pid);
605         auto selfDrawingNodeVector =
606             connection->mainThread_->GetContext().GetMutableNodeMap().GetSelfDrawingNodeInProcess(pid);
607         for (auto iter = selfDrawingNodeVector.rbegin(); iter != selfDrawingNodeVector.rend(); ++iter) {
608             auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(*iter);
609             if (auto surfaceNode = node->ReinterpretCastTo<RSSurfaceRenderNode>()) {
610                 auto surfaceBuffer = surfaceNode->GetRSSurfaceHandler()->GetBuffer();
611                 auto surfaceBufferInfo = std::make_tuple(surfaceBuffer, surfaceNode->GetName(),
612                     surfaceNode->GetRenderProperties().GetBoundsGeometry()->GetAbsRect());
613                 sfBufferInfoVector.push_back(surfaceBufferInfo);
614             }
615         }
616     };
617     mainThread_->PostSyncTask(getSurfaceBufferByPidTask);
618 
619     for (uint32_t i = 0; i < sfBufferInfoVector.size(); i++) {
620         auto surfaceBuffer = std::get<0>(sfBufferInfoVector[i]);
621         const auto surfaceName = std::get<1>(sfBufferInfoVector[i]);
622         const auto& absRect = std::get<2>(sfBufferInfoVector[i]);
623         if (surfaceBuffer) {
624             OHOS::Media::Rect rect = { 0, 0, surfaceBuffer->GetWidth(), surfaceBuffer->GetHeight() };
625             std::shared_ptr<Media::PixelMap> pixelmap = nullptr;
626             RSBackgroundThread::Instance().PostSyncTask([&surfaceBuffer, rect, &pixelmap]() {
627                 pixelmap = Rosen::CreatePixelMapFromSurfaceBuffer(surfaceBuffer, rect);
628             });
629             if (pixelmap) {
630                 pixelMapInfoVector.emplace_back(PixelMapInfo { pixelmap,
631                     { absRect.GetLeft(), absRect.GetTop(), absRect.GetWidth(), absRect.GetHeight(), i },
632                     surfaceName,
633                     GetRotationInfoFromSurfaceBuffer(surfaceBuffer) });
634             } else {
635                 RS_LOGE("CreatePixelMapFromSurfaceBuffer pixelmap is null, nodeName:%{public}s", surfaceName.c_str());
636             }
637         } else {
638             RS_LOGE("CreatePixelMapFromSurface surfaceBuffer is null, nodeName:%{public}s, rect:%{public}s",
639                 surfaceName.c_str(), absRect.ToString().c_str());
640         }
641     }
642     repCode = SUCCESS;
643     return ERR_OK;
644 }
645 
GetRotationInfoFromSurfaceBuffer(const sptr<SurfaceBuffer> & buffer)646 float RSRenderServiceConnection::GetRotationInfoFromSurfaceBuffer(const sptr<SurfaceBuffer>& buffer)
647 {
648     if (buffer == nullptr) {
649         RS_LOGE("GetRotationInfoFromSurfaceBuffer buffer is null");
650         return 0.0f;
651     }
652     auto transformType = buffer->GetSurfaceBufferTransform();
653     if (transformType == GRAPHIC_ROTATE_90) {
654         return 90.0f;
655     } else if (transformType == GRAPHIC_ROTATE_180) {
656         return 180.0f;
657     } else if (transformType == GRAPHIC_ROTATE_270) {
658         return 270.0f;
659     }
660     return 0.0f;
661 }
662 
CreatePixelMapFromSurface(sptr<Surface> surface,const Rect & srcRect,std::shared_ptr<Media::PixelMap> & pixelMap)663 ErrCode RSRenderServiceConnection::CreatePixelMapFromSurface(sptr<Surface> surface,
664     const Rect &srcRect, std::shared_ptr<Media::PixelMap> &pixelMap)
665 {
666     OHOS::Media::Rect rect = {
667         .left = srcRect.x,
668         .top = srcRect.y,
669         .width = srcRect.w,
670         .height = srcRect.h,
671     };
672     RSBackgroundThread::Instance().PostSyncTask([surface, rect, &pixelMap]() {
673         pixelMap = Rosen::CreatePixelMapFromSurface(surface, rect);
674     });
675     return ERR_OK;
676 }
677 
SetFocusAppInfo(const FocusAppInfo & info,int32_t & repCode)678 ErrCode RSRenderServiceConnection::SetFocusAppInfo(const FocusAppInfo& info, int32_t& repCode)
679 {
680     if (mainThread_ == nullptr) {
681         repCode = INVALID_ARGUMENTS;
682         return ERR_INVALID_VALUE;
683     }
684     mainThread_->ScheduleTask(
685         [info, mainThread = mainThread_]() {
686             // don't use 'this' to get mainThread poninter
687             mainThread->SetFocusAppInfo(info);
688         }
689     );
690     repCode = SUCCESS;
691     return ERR_OK;
692 }
693 
SetWatermark(const std::string & name,std::shared_ptr<Media::PixelMap> watermark,bool & success)694 ErrCode RSRenderServiceConnection::SetWatermark(const std::string& name, std::shared_ptr<Media::PixelMap> watermark,
695     bool& success)
696 {
697     if (!mainThread_) {
698         success = false;
699         return ERR_INVALID_VALUE;
700     }
701     pid_t callingPid = GetCallingPid();
702     mainThread_->SetWatermark(callingPid, name, watermark);
703     success = true;
704     return ERR_OK;
705 }
706 
GetDefaultScreenId(uint64_t & screenId)707 ErrCode RSRenderServiceConnection::GetDefaultScreenId(uint64_t& screenId)
708 {
709     std::lock_guard<std::mutex> lock(mutex_);
710     if (!screenManager_) {
711         screenId = INVALID_SCREEN_ID;
712         return ERR_INVALID_VALUE;
713     }
714     screenId = screenManager_->GetDefaultScreenId();
715     return ERR_OK;
716 }
717 
GetActiveScreenId(uint64_t & screenId)718 ErrCode RSRenderServiceConnection::GetActiveScreenId(uint64_t& screenId)
719 {
720     std::lock_guard<std::mutex> lock(mutex_);
721     if (!screenManager_) {
722         screenId =  INVALID_SCREEN_ID;
723         return ERR_INVALID_VALUE;
724     }
725     screenId = screenManager_->GetActiveScreenId();
726     return ERR_OK;
727 }
728 
GetAllScreenIds()729 std::vector<ScreenId> RSRenderServiceConnection::GetAllScreenIds()
730 {
731     std::lock_guard<std::mutex> lock(mutex_);
732     if (!screenManager_) {
733         return std::vector<ScreenId>();
734     }
735     return screenManager_->GetAllScreenIds();
736 }
737 
CreateVirtualScreen(const std::string & name,uint32_t width,uint32_t height,sptr<Surface> surface,ScreenId mirrorId,int32_t flags,std::vector<NodeId> whiteList)738 ScreenId RSRenderServiceConnection::CreateVirtualScreen(
739     const std::string &name,
740     uint32_t width,
741     uint32_t height,
742     sptr<Surface> surface,
743     ScreenId mirrorId,
744     int32_t flags,
745     std::vector<NodeId> whiteList)
746 {
747     if (whiteList.size() > MAX_WHITE_LIST_NUM) {
748         RS_LOGW("%{public}s: white list is over max size!", __func__);
749         return INVALID_SCREEN_ID;
750     }
751     std::lock_guard<std::mutex> lock(mutex_);
752     if (!screenManager_) {
753         return StatusCode::SCREEN_NOT_FOUND;
754     }
755     auto newVirtualScreenId = screenManager_->CreateVirtualScreen(
756         name, width, height, surface, mirrorId, flags, whiteList);
757     virtualScreenIds_.insert(newVirtualScreenId);
758     if (surface != nullptr) {
759         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ, name };
760         NotifyRefreshRateEvent(event);
761         ROSEN_LOGI("%{public}s vote 60hz", __func__);
762     }
763     return newVirtualScreenId;
764 }
765 
SetVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector)766 int32_t RSRenderServiceConnection::SetVirtualScreenBlackList(ScreenId id, std::vector<NodeId>& blackListVector)
767 {
768     if (blackListVector.size() > MAX_BLACK_LIST_NUM) {
769         RS_LOGW("%{public}s: black list is over max size!", __func__);
770         return StatusCode::INVALID_ARGUMENTS;
771     }
772     if (blackListVector.empty()) {
773         RS_LOGW("SetVirtualScreenBlackList blackList is empty.");
774     }
775     std::lock_guard<std::mutex> lock(mutex_);
776     if (!screenManager_) {
777         return StatusCode::SCREEN_NOT_FOUND;
778     }
779     return screenManager_->SetVirtualScreenBlackList(id, blackListVector);
780 }
781 
SetVirtualScreenTypeBlackList(ScreenId id,std::vector<NodeType> & typeBlackListVector,int32_t & repCode)782 ErrCode RSRenderServiceConnection::SetVirtualScreenTypeBlackList(
783     ScreenId id, std::vector<NodeType>& typeBlackListVector, int32_t& repCode)
784 {
785     if (typeBlackListVector.empty()) {
786         RS_LOGW("SetVirtualScreenTypeBlackList typeBlackList is empty.");
787     }
788     std::lock_guard<std::mutex> lock(mutex_);
789     if (!screenManager_) {
790         repCode = StatusCode::SCREEN_NOT_FOUND;
791         return ERR_INVALID_VALUE;
792     }
793     repCode = screenManager_->SetVirtualScreenTypeBlackList(id, typeBlackListVector);
794     return ERR_OK;
795 }
796 
AddVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector,int32_t & repCode)797 ErrCode RSRenderServiceConnection::AddVirtualScreenBlackList(
798     ScreenId id, std::vector<NodeId>& blackListVector, int32_t& repCode)
799 {
800     if (blackListVector.size() > MAX_BLACK_LIST_NUM) {
801         RS_LOGW("%{public}s: black list is over max size!", __func__);
802         repCode = StatusCode::INVALID_ARGUMENTS;
803         return ERR_INVALID_VALUE;
804     }
805     if (blackListVector.empty()) {
806         RS_LOGW("AddVirtualScreenBlackList blackList is empty.");
807         repCode = StatusCode::BLACKLIST_IS_EMPTY;
808         return ERR_INVALID_VALUE;
809     }
810     std::lock_guard<std::mutex> lock(mutex_);
811     if (!screenManager_) {
812         repCode = StatusCode::SCREEN_NOT_FOUND;
813         return ERR_INVALID_VALUE;
814     }
815     repCode = screenManager_->AddVirtualScreenBlackList(id, blackListVector);
816     return ERR_OK;
817 }
818 
RemoveVirtualScreenBlackList(ScreenId id,std::vector<NodeId> & blackListVector,int32_t & repCode)819 ErrCode RSRenderServiceConnection::RemoveVirtualScreenBlackList(
820     ScreenId id, std::vector<NodeId>& blackListVector, int32_t& repCode)
821 {
822     if (blackListVector.empty()) {
823         RS_LOGW("RemoveVirtualScreenBlackList blackList is empty.");
824         repCode = StatusCode::BLACKLIST_IS_EMPTY;
825         return ERR_INVALID_VALUE;
826     }
827     std::lock_guard<std::mutex> lock(mutex_);
828     if (!screenManager_) {
829         repCode = StatusCode::SCREEN_NOT_FOUND;
830         return ERR_INVALID_VALUE;
831     }
832     repCode = screenManager_->RemoveVirtualScreenBlackList(id, blackListVector);
833     return ERR_OK;
834 }
835 
SetVirtualScreenSecurityExemptionList(ScreenId id,const std::vector<NodeId> & securityExemptionList)836 int32_t RSRenderServiceConnection::SetVirtualScreenSecurityExemptionList(
837     ScreenId id,
838     const std::vector<NodeId>& securityExemptionList)
839 {
840     if (!screenManager_) {
841         return StatusCode::SCREEN_NOT_FOUND;
842     }
843     return screenManager_->SetVirtualScreenSecurityExemptionList(id, securityExemptionList);
844 }
845 
SetScreenSecurityMask(ScreenId id,std::shared_ptr<Media::PixelMap> securityMask)846 int32_t RSRenderServiceConnection::SetScreenSecurityMask(ScreenId id,
847     std::shared_ptr<Media::PixelMap> securityMask)
848 {
849     if (!screenManager_) {
850         return StatusCode::SCREEN_NOT_FOUND;
851     }
852     return screenManager_->SetScreenSecurityMask(id, std::move(securityMask));
853 }
854 
SetMirrorScreenVisibleRect(ScreenId id,const Rect & mainScreenRect,bool supportRotation)855 int32_t RSRenderServiceConnection::SetMirrorScreenVisibleRect(ScreenId id, const Rect& mainScreenRect,
856     bool supportRotation)
857 {
858     if (screenManager_ == nullptr) {
859         return StatusCode::SCREEN_NOT_FOUND;
860     }
861     return screenManager_->SetMirrorScreenVisibleRect(id, mainScreenRect, supportRotation);
862 }
863 
SetCastScreenEnableSkipWindow(ScreenId id,bool enable)864 int32_t RSRenderServiceConnection::SetCastScreenEnableSkipWindow(ScreenId id, bool enable)
865 {
866     std::lock_guard<std::mutex> lock(mutex_);
867     if (!screenManager_) {
868         return StatusCode::SCREEN_NOT_FOUND;
869     }
870     return screenManager_->SetCastScreenEnableSkipWindow(id, enable);
871 }
872 
SetVirtualScreenSurface(ScreenId id,sptr<Surface> surface)873 int32_t RSRenderServiceConnection::SetVirtualScreenSurface(ScreenId id, sptr<Surface> surface)
874 {
875     std::lock_guard<std::mutex> lock(mutex_);
876     if (!screenManager_) {
877         return StatusCode::SCREEN_NOT_FOUND;
878     }
879     return screenManager_->SetVirtualScreenSurface(id, surface);
880 }
881 
882 #ifdef OHOS_BUILD_ENABLE_MAGICCURSOR
SetPointerColorInversionConfig(float darkBuffer,float brightBuffer,int64_t interval,int32_t rangeSize)883 int32_t RSRenderServiceConnection::SetPointerColorInversionConfig(float darkBuffer,
884     float brightBuffer, int64_t interval, int32_t rangeSize)
885 {
886     RSMagicPointerRenderManager::GetInstance().SetPointerColorInversionConfig(darkBuffer, brightBuffer,
887         interval, rangeSize);
888     return StatusCode::SUCCESS;
889 }
890 
SetPointerColorInversionEnabled(bool enable)891 int32_t RSRenderServiceConnection::SetPointerColorInversionEnabled(bool enable)
892 {
893     RSMagicPointerRenderManager::GetInstance().SetPointerColorInversionEnabled(enable);
894     return StatusCode::SUCCESS;
895 }
896 
RegisterPointerLuminanceChangeCallback(sptr<RSIPointerLuminanceChangeCallback> callback)897 int32_t RSRenderServiceConnection::RegisterPointerLuminanceChangeCallback(
898     sptr<RSIPointerLuminanceChangeCallback> callback)
899 {
900     if (!callback) {
901         RS_LOGE("RegisterPointerLuminanceChangeCallback: callback is nullptr");
902         return StatusCode::INVALID_ARGUMENTS;
903     }
904     RSMagicPointerRenderManager::GetInstance().RegisterPointerLuminanceChangeCallback(remotePid_, callback);
905     return StatusCode::SUCCESS;
906 }
907 
UnRegisterPointerLuminanceChangeCallback()908 int32_t RSRenderServiceConnection::UnRegisterPointerLuminanceChangeCallback()
909 {
910     RSMagicPointerRenderManager::GetInstance().UnRegisterPointerLuminanceChangeCallback(remotePid_);
911     return StatusCode::SUCCESS;
912 }
913 #endif
914 
RemoveVirtualScreen(ScreenId id)915 void RSRenderServiceConnection::RemoveVirtualScreen(ScreenId id)
916 {
917     std::lock_guard<std::mutex> lock(mutex_);
918     if (!screenManager_) {
919         return;
920     }
921     screenManager_->RemoveVirtualScreen(id);
922     virtualScreenIds_.erase(id);
923     EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
924     NotifyRefreshRateEvent(event);
925 }
926 
SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)927 int32_t RSRenderServiceConnection::SetScreenChangeCallback(sptr<RSIScreenChangeCallback> callback)
928 {
929     if (!callback) {
930         RS_LOGE("%{public}s: callback is nullptr", __func__);
931         return INVALID_ARGUMENTS;
932     }
933     std::unique_lock<std::mutex> lock(mutex_);
934     if (screenChangeCallback_ == callback) {
935         RS_LOGE("%{public}s: the callback has been set", __func__);
936         return INVALID_ARGUMENTS;
937     }
938     if (screenManager_ == nullptr) {
939         RS_LOGE("%{public}s: screenManager_ is nullptr", __func__);
940         return SCREEN_NOT_FOUND;
941     }
942 
943     if (screenChangeCallback_ != nullptr) {
944         // remove the old callback
945         RS_LOGW("%{public}s: last screenChangeCallback_ should be removed", __func__);
946         screenManager_->RemoveScreenChangeCallback(screenChangeCallback_);
947     }
948 
949     // update
950     int32_t status = screenManager_->AddScreenChangeCallback(callback);
951     screenChangeCallback_ = callback;
952     return status;
953 }
954 
SetScreenSwitchingNotifyCallback(sptr<RSIScreenSwitchingNotifyCallback> callback)955 int32_t RSRenderServiceConnection::SetScreenSwitchingNotifyCallback(sptr<RSIScreenSwitchingNotifyCallback> callback)
956 {
957     if (screenManager_ == nullptr) {
958         RS_LOGE("%{public}s: screenManager_ is nullptr", __func__);
959         return SCREEN_NOT_FOUND;
960     }
961 
962     // update
963     int32_t status = screenManager_->SetScreenSwitchingNotifyCallback(callback);
964     return status;
965 }
966 
SetScreenActiveMode(ScreenId id,uint32_t modeId)967 void RSRenderServiceConnection::SetScreenActiveMode(ScreenId id, uint32_t modeId)
968 {
969     if (!screenManager_) {
970         return;
971     }
972     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
973     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
974 #ifdef RS_ENABLE_GPU
975         return RSHardwareThread::Instance().ScheduleTask(
976             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
977 #endif
978     } else if (mainThread_ != nullptr) {
979         return mainThread_->ScheduleTask(
980             [=]() { screenManager_->SetScreenActiveMode(id, modeId); }).wait();
981     }
982 }
983 
SetScreenRefreshRate(ScreenId id,int32_t sceneId,int32_t rate)984 void RSRenderServiceConnection::SetScreenRefreshRate(ScreenId id, int32_t sceneId, int32_t rate)
985 {
986     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetScreenRefreshRate");
987     HgmTaskHandleThread::Instance().PostTask([id, sceneId, rate] () {
988         int32_t setResult = HgmCore::Instance().SetScreenRefreshRate(id, sceneId, rate);
989         if (setResult != 0) {
990             RS_LOGW("SetScreenRefreshRate request of screen %{public}" PRIu64 " of rate %{public}d is refused",
991                 id, rate);
992             return;
993         }
994     });
995     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
996 }
997 
SetRefreshRateMode(int32_t refreshRateMode)998 void RSRenderServiceConnection::SetRefreshRateMode(int32_t refreshRateMode)
999 {
1000     ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::SetRefreshRateMode");
1001     HgmTaskHandleThread::Instance().PostTask([refreshRateMode] () {
1002         int32_t setResult = HgmCore::Instance().SetRefreshRateMode(refreshRateMode);
1003         RSSystemProperties::SetHgmRefreshRateModesEnabled(std::to_string(refreshRateMode));
1004         if (setResult != 0) {
1005             RS_LOGW("SetRefreshRateMode mode %{public}d is not supported", refreshRateMode);
1006         }
1007     });
1008     ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
1009 }
1010 
SyncFrameRateRange(FrameRateLinkerId id,const FrameRateRange & range,int32_t animatorExpectedFrameRate)1011 void RSRenderServiceConnection::SyncFrameRateRange(FrameRateLinkerId id,
1012     const FrameRateRange& range, int32_t animatorExpectedFrameRate)
1013 {
1014     if (!mainThread_) {
1015         return;
1016     }
1017     mainThread_->ScheduleTask(
1018         [weakThis = wptr<RSRenderServiceConnection>(this), id, &range, animatorExpectedFrameRate]() {
1019             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1020             if (connection == nullptr || connection->mainThread_ == nullptr) {
1021                 return;
1022             }
1023             auto& context = connection->mainThread_->GetContext();
1024             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
1025             auto linker = linkerMap.GetFrameRateLinker(id);
1026             if (linker == nullptr) {
1027                 RS_LOGW("SyncFrameRateRange there is no frameRateLinker for id %{public}" PRIu64, id);
1028                 return;
1029             }
1030             linker->SetExpectedRange(range);
1031             linker->SetAnimatorExpectedFrameRate(animatorExpectedFrameRate);
1032             if (range.type_ != OHOS::Rosen::NATIVE_VSYNC_FRAME_RATE_TYPE) {
1033                 return;
1034             }
1035             auto appVSyncDistributor = connection->appVSyncDistributor_;
1036             if (appVSyncDistributor == nullptr) {
1037                 return;
1038             }
1039             auto conn = appVSyncDistributor->GetVSyncConnection(id);
1040             if (conn == nullptr) {
1041                 return;
1042             }
1043             std::weak_ptr<RSRenderFrameRateLinker> weakPtr = linker;
1044             conn->RegisterRequestNativeVSyncCallback([weakPtr]() {
1045                 RS_TRACE_NAME("NativeVSync request frame, update timepoint");
1046                 auto linker = weakPtr.lock();
1047                 if (linker == nullptr) {
1048                     return;
1049                 }
1050                 linker->UpdateNativeVSyncTimePoint();
1051             });
1052         }).wait();
1053 }
1054 
UnregisterFrameRateLinker(FrameRateLinkerId id)1055 void RSRenderServiceConnection::UnregisterFrameRateLinker(FrameRateLinkerId id)
1056 {
1057     if (!mainThread_) {
1058         return;
1059     }
1060     mainThread_->ScheduleTask(
1061         [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
1062             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1063             if (connection == nullptr || connection->mainThread_ == nullptr) {
1064                 return;
1065             }
1066             auto& context = connection->mainThread_->GetContext();
1067             auto& linkerMap = context.GetMutableFrameRateLinkerMap();
1068             auto linker = linkerMap.GetFrameRateLinker(id);
1069             if (linker == nullptr) {
1070                 RS_LOGE("UnregisterFrameRateLinker there is no frameRateLinker for id %{public}" PRIu64, id);
1071                 return;
1072             }
1073             linkerMap.UnregisterFrameRateLinker(id);
1074         }).wait();
1075 }
1076 
GetScreenCurrentRefreshRate(ScreenId id)1077 uint32_t RSRenderServiceConnection::GetScreenCurrentRefreshRate(ScreenId id)
1078 {
1079     uint32_t rate = HgmTaskHandleThread::Instance().ScheduleTask([id] () -> uint32_t {
1080         return HgmCore::Instance().GetScreenCurrentRefreshRate(id);
1081     }).get();
1082     if (rate == 0) {
1083         RS_LOGW("GetScreenCurrentRefreshRate failed to get current refreshrate of"
1084             " screen : %{public}" PRIu64, id);
1085     }
1086     return rate;
1087 }
1088 
GetScreenSupportedRefreshRates(ScreenId id)1089 std::vector<int32_t> RSRenderServiceConnection::GetScreenSupportedRefreshRates(ScreenId id)
1090 {
1091     return HgmTaskHandleThread::Instance().ScheduleTask([id] () -> std::vector<int32_t> {
1092         return HgmCore::Instance().GetScreenComponentRefreshRates(id);
1093     }).get();
1094 }
1095 
GetShowRefreshRateEnabled(bool & enable)1096 ErrCode RSRenderServiceConnection::GetShowRefreshRateEnabled(bool& enable)
1097 {
1098     enable = RSRealtimeRefreshRateManager::Instance().GetShowRefreshRateEnabled();
1099     return ERR_OK;
1100 }
1101 
SetShowRefreshRateEnabled(bool enabled,int32_t type)1102 void RSRenderServiceConnection::SetShowRefreshRateEnabled(bool enabled, int32_t type)
1103 {
1104     return RSRealtimeRefreshRateManager::Instance().SetShowRefreshRateEnabled(enabled, type);
1105 }
1106 
GetRealtimeRefreshRate(ScreenId screenId)1107 uint32_t RSRenderServiceConnection::GetRealtimeRefreshRate(ScreenId screenId)
1108 {
1109     return RSRealtimeRefreshRateManager::Instance().GetRealtimeRefreshRate(screenId);
1110 }
1111 
GetRefreshInfo(pid_t pid,std::string & enable)1112 ErrCode RSRenderServiceConnection::GetRefreshInfo(pid_t pid, std::string& enable)
1113 {
1114     if (!mainThread_) {
1115         enable = "";
1116         return ERR_INVALID_VALUE;
1117     }
1118     auto& context = mainThread_->GetContext();
1119     auto& nodeMap = context.GetMutableNodeMap();
1120     std::string surfaceName = nodeMap.GetSelfDrawSurfaceNameByPid(pid);
1121     if (surfaceName.empty()) {
1122         enable = "";
1123         return ERR_INVALID_VALUE;
1124     }
1125     std::string dumpString;
1126     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1127     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1128 #ifdef RS_ENABLE_GPU
1129         RSHardwareThread::Instance().ScheduleTask(
1130             [weakThis = wptr<RSRenderServiceConnection>(this), &dumpString, &surfaceName]() {
1131                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1132                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1133                     return;
1134                 }
1135                 connection->screenManager_->FpsDump(dumpString, surfaceName);
1136             }).wait();
1137 #endif
1138     } else {
1139         mainThread_->ScheduleTask(
1140             [weakThis = wptr<RSRenderServiceConnection>(this), &dumpString, &surfaceName]() {
1141                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1142                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1143                     return;
1144                 }
1145                 connection->screenManager_->FpsDump(dumpString, surfaceName);
1146             }).wait();
1147     }
1148     enable = dumpString;
1149     return ERR_OK;
1150 }
1151 
GetRefreshInfoToSP(NodeId id,std::string & enable)1152 ErrCode RSRenderServiceConnection::GetRefreshInfoToSP(NodeId id, std::string& enable)
1153 {
1154     if (!mainThread_) {
1155         enable = "";
1156         return ERR_INVALID_VALUE;
1157     }
1158     std::string dumpString;
1159     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1160     auto dumpTask = [weakThis = wptr<RSRenderServiceConnection>(this), &dumpString, &id]() {
1161         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1162         if (connection == nullptr) {
1163             RS_LOGE("GetRefreshInfoToSP connection is nullptr");
1164             return;
1165         }
1166         if (connection->screenManager_ == nullptr) {
1167             RS_LOGE("GetRefreshInfoToSP connection->screenManager_ is nullptr");
1168             return;
1169         }
1170         RSSurfaceFpsManager::GetInstance().Dump(dumpString, id);
1171     };
1172     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1173 #ifdef RS_ENABLE_GPU
1174         RSHardwareThread::Instance().ScheduleTask(dumpTask).wait();
1175 #endif
1176     } else {
1177         mainThread_->ScheduleTask(dumpTask).wait();
1178     }
1179     enable = dumpString;
1180     return ERR_OK;
1181 }
1182 
GetCurrentRefreshRateMode()1183 int32_t RSRenderServiceConnection::GetCurrentRefreshRateMode()
1184 {
1185     return HgmTaskHandleThread::Instance().ScheduleTask([] () -> int32_t {
1186         return HgmCore::Instance().GetCurrentRefreshRateMode();
1187     }).get();
1188 }
1189 
SetPhysicalScreenResolution(ScreenId id,uint32_t width,uint32_t height)1190 int32_t RSRenderServiceConnection::SetPhysicalScreenResolution(ScreenId id, uint32_t width, uint32_t height)
1191 {
1192     if (!screenManager_) {
1193         return StatusCode::SCREEN_MANAGER_NULL;
1194     }
1195     return screenManager_->SetPhysicalScreenResolution(id, width, height);
1196 }
1197 
SetVirtualScreenResolution(ScreenId id,uint32_t width,uint32_t height)1198 int32_t RSRenderServiceConnection::SetVirtualScreenResolution(ScreenId id, uint32_t width, uint32_t height)
1199 {
1200     if (!screenManager_) {
1201         return StatusCode::SCREEN_NOT_FOUND;
1202     }
1203     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1204     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1205 #ifdef RS_ENABLE_GPU
1206         return RSHardwareThread::Instance().ScheduleTask(
1207             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
1208 #else
1209         return StatusCode::SCREEN_NOT_FOUND;
1210 #endif
1211     } else if (mainThread_ != nullptr) {
1212         return mainThread_->ScheduleTask(
1213             [=]() { return screenManager_->SetVirtualScreenResolution(id, width, height); }).get();
1214     } else {
1215         return StatusCode::SCREEN_NOT_FOUND;
1216     }
1217 }
1218 
MarkPowerOffNeedProcessOneFrame()1219 ErrCode RSRenderServiceConnection::MarkPowerOffNeedProcessOneFrame()
1220 {
1221     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1222     if (renderType != UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1223         return ERR_INVALID_VALUE;
1224     }
1225 #ifdef RS_ENABLE_GPU
1226     renderThread_.PostTask(
1227         [weakThis = wptr<RSRenderServiceConnection>(this)]() {
1228             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1229             if (connection == nullptr || connection->screenManager_ == nullptr) {
1230                 return;
1231             }
1232             connection->screenManager_->MarkPowerOffNeedProcessOneFrame();
1233         }
1234     );
1235 #endif
1236     return ERR_OK;
1237 }
1238 
RepaintEverything()1239 ErrCode RSRenderServiceConnection::RepaintEverything()
1240 {
1241     if (mainThread_ == nullptr) {
1242         RS_LOGE("RepaintEverything, mainThread_ is null, return");
1243         return ERR_INVALID_VALUE;
1244     }
1245     auto task = []() -> void {
1246         RS_LOGI("RepaintEverything, setDirtyflag, forceRefresh in mainThread");
1247         RSMainThread::Instance()->SetDirtyFlag();
1248         RSMainThread::Instance()->ForceRefreshForUni();
1249     };
1250     mainThread_->PostTask(task);
1251     return ERR_OK;
1252 }
1253 
ForceRefreshOneFrameWithNextVSync()1254 ErrCode RSRenderServiceConnection::ForceRefreshOneFrameWithNextVSync()
1255 {
1256     if (!mainThread_) {
1257         RS_LOGE("%{public}s mainThread_ is nullptr, return", __func__);
1258         return ERR_INVALID_VALUE;
1259     }
1260 
1261     auto task = [weakThis = wptr<RSRenderServiceConnection>(this)]() -> void {
1262         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1263         if (connection == nullptr || connection->mainThread_ == nullptr) {
1264             return;
1265         }
1266 
1267         RS_LOGI("ForceRefreshOneFrameWithNextVSync, setDirtyflag, forceRefresh in mainThread");
1268         connection->mainThread_->SetDirtyFlag();
1269         connection->mainThread_->RequestNextVSync();
1270     };
1271     mainThread_->PostTask(task);
1272     return ERR_OK;
1273 }
1274 
DisablePowerOffRenderControl(ScreenId id)1275 void RSRenderServiceConnection::DisablePowerOffRenderControl(ScreenId id)
1276 {
1277     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1278     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1279 #ifdef RS_ENABLE_GPU
1280         renderThread_.PostTask(
1281             [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
1282                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1283                 if (connection == nullptr || connection->screenManager_ == nullptr) {
1284                     return;
1285                 }
1286                 connection->screenManager_->DisablePowerOffRenderControl(id);
1287             }
1288         );
1289 #endif
1290     }
1291 }
1292 
SetScreenPowerStatus(ScreenId id,ScreenPowerStatus status)1293 void RSRenderServiceConnection::SetScreenPowerStatus(ScreenId id, ScreenPowerStatus status)
1294 {
1295     if (screenManager_ == nullptr || mainThread_ == nullptr) {
1296         RS_LOGE("%{public}s screenManager or mainThread is null, id: %{public}" PRIu64, __func__, id);
1297         return;
1298     }
1299     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1300     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1301 #ifdef RS_ENABLE_GPU
1302         RSHardwareThread::Instance().ScheduleTask([=]() {
1303             screenManager_->SetScreenPowerStatus(id, status);
1304         }).wait();
1305         screenManager_->WaitScreenPowerStatusTask();
1306         mainThread_->SetDiscardJankFrames(true);
1307         RSJankStatsRenderFrameHelper::GetInstance().SetDiscardJankFrames(true);
1308         HgmTaskHandleThread::Instance().PostTask([id, status]() {
1309             HgmCore::Instance().NotifyScreenPowerStatus(id, status);
1310         });
1311 #endif
1312     } else {
1313         mainThread_->ScheduleTask(
1314             [=]() { screenManager_->SetScreenPowerStatus(id, status); }).wait();
1315     }
1316 }
1317 
1318 namespace {
TakeSurfaceCaptureForUiParallel(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const Drawing::Rect & specifiedAreaRect)1319 void TakeSurfaceCaptureForUiParallel(
1320     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
1321     const Drawing::Rect& specifiedAreaRect)
1322 {
1323 #ifdef RS_ENABLE_GPU
1324     RS_LOGI("TakeSurfaceCaptureForUiParallel nodeId:[%{public}" PRIu64 "], issync:%{public}s", id,
1325         captureConfig.isSync ? "true" : "false");
1326     std::function<void()> captureTask = [id, callback, captureConfig, specifiedAreaRect]() {
1327         RSUiCaptureTaskParallel::Capture(id, callback, captureConfig, specifiedAreaRect);
1328     };
1329     auto& context = RSMainThread::Instance()->GetContext();
1330     if (captureConfig.isSync) {
1331         context.GetUiCaptureHelper().InsertUiCaptureCmdsExecutedFlag(id, false);
1332         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
1333         return;
1334     }
1335 
1336     auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
1337     if (!node) {
1338         RS_LOGE("TakeSurfaceCaptureForUiParallel node is nullptr");
1339         callback->OnSurfaceCapture(id, captureConfig, nullptr);
1340         return;
1341     }
1342 
1343     if (node->IsOnTheTree() && !node->IsDirty() && !node->IsSubTreeDirty()) {
1344         RSMainThread::Instance()->PostTask(captureTask);
1345     } else {
1346         RSMainThread::Instance()->AddUiCaptureTask(id, captureTask);
1347     }
1348 #endif
1349 }
1350 
TakeSurfaceCaptureForUIWithUni(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)1351 void TakeSurfaceCaptureForUIWithUni(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
1352     const RSSurfaceCaptureConfig& captureConfig)
1353 {
1354 #ifdef RS_ENABLE_GPU
1355     std::function<void()> offscreenRenderTask = [id, callback, captureConfig]() -> void {
1356         RS_LOGD("RSRenderService::TakeSurfaceCaptureForUIWithUni callback->OnOffscreenRender"
1357             " nodeId:[%{public}" PRIu64 "]", id);
1358         ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCaptureForUIWithUni");
1359         std::shared_ptr<RSUniUICapture> rsUniUICapture = std::make_shared<RSUniUICapture>(id, captureConfig);
1360         std::shared_ptr<Media::PixelMap> pixelmap = rsUniUICapture->TakeLocalCapture();
1361         callback->OnSurfaceCapture(id, captureConfig, pixelmap.get());
1362         ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
1363     };
1364     if (!captureConfig.isSync) {
1365         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
1366     } else {
1367         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode<RSRenderNode>(id);
1368         if (node == nullptr || !node->GetCommandExecuted()) {
1369             RSOffscreenRenderThread::Instance().InSertCaptureTask(id, offscreenRenderTask);
1370             return;
1371         }
1372         RSOffscreenRenderThread::Instance().PostTask(offscreenRenderTask);
1373         node->SetCommandExecuted(false);
1374     }
1375 #endif
1376 }
1377 }
1378 
TakeSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const RSSurfaceCaptureBlurParam & blurParam,const Drawing::Rect & specifiedAreaRect,RSSurfaceCapturePermissions permissions)1379 void RSRenderServiceConnection::TakeSurfaceCapture(NodeId id, sptr<RSISurfaceCaptureCallback> callback,
1380     const RSSurfaceCaptureConfig& captureConfig, const RSSurfaceCaptureBlurParam& blurParam,
1381     const Drawing::Rect& specifiedAreaRect, RSSurfaceCapturePermissions permissions)
1382 {
1383     if (!mainThread_) {
1384         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1385         return;
1386     }
1387 
1388     std::function<void()> captureTask = [id, callback, captureConfig, blurParam, specifiedAreaRect,
1389         screenCapturePermission = permissions.screenCapturePermission,
1390         isSystemCalling = permissions.isSystemCalling,
1391         selfCapture = permissions.selfCapture]() -> void {
1392         RS_TRACE_NAME_FMT("RSRenderServiceConnection::TakeSurfaceCapture captureTask nodeId:[%" PRIu64 "]", id);
1393         RS_LOGD("TakeSurfaceCapture captureTask begin nodeId:[%{public}" PRIu64 "]", id);
1394         if (captureConfig.captureType == SurfaceCaptureType::UICAPTURE) {
1395             // When the isSync flag in captureConfig is true, UI capture processes commands before capture.
1396             // When the isSync flag in captureConfig is false, UI capture will check null node independently.
1397             // Therefore, a null node is valid for UI capture.
1398             auto uiCaptureHasPermission = selfCapture || isSystemCalling;
1399             if (!uiCaptureHasPermission) {
1400                 RS_LOGE("TakeSurfaceCapture uicapture failed, nodeId:[%{public}" PRIu64
1401                         "], isSystemCalling: %{public}u, selfCapture: %{public}u",
1402                     id, isSystemCalling, selfCapture);
1403                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1404                 return;
1405             }
1406             if (RSUniRenderJudgement::IsUniRender()) {
1407                 TakeSurfaceCaptureForUiParallel(id, callback, captureConfig, specifiedAreaRect);
1408             } else {
1409                 TakeSurfaceCaptureForUIWithUni(id, callback, captureConfig);
1410             }
1411             return;
1412         }
1413         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1414         if (node == nullptr) {
1415             RS_LOGE("TakeSurfaceCapture failed, node is nullptr");
1416             callback->OnSurfaceCapture(id, captureConfig, nullptr);
1417             return;
1418         }
1419         auto displayCaptureHasPermission = screenCapturePermission && isSystemCalling;
1420         auto surfaceCaptureHasPermission = blurParam.isNeedBlur ? isSystemCalling : (selfCapture || isSystemCalling);
1421         if ((node->GetType() == RSRenderNodeType::LOGICAL_DISPLAY_NODE && !displayCaptureHasPermission) ||
1422             (node->GetType() == RSRenderNodeType::SURFACE_NODE && !surfaceCaptureHasPermission)) {
1423             RS_LOGE("TakeSurfaceCapture failed, node type: %{public}u, "
1424                 "screenCapturePermission: %{public}u, isSystemCalling: %{public}u, selfCapture: %{public}u",
1425                 node->GetType(), screenCapturePermission, isSystemCalling, selfCapture);
1426             callback->OnSurfaceCapture(id, captureConfig, nullptr);
1427             return;
1428         }
1429         if (RSUniRenderJudgement::GetUniRenderEnabledType() == UniRenderEnabledType::UNI_RENDER_DISABLED) {
1430             RS_LOGD("RSRenderService::TakeSurfaceCapture captureTaskInner nodeId:[%{public}" PRIu64 "]", id);
1431             ROSEN_TRACE_BEGIN(HITRACE_TAG_GRAPHIC_AGP, "RSRenderService::TakeSurfaceCapture");
1432             RSSurfaceCaptureTask task(id, captureConfig);
1433             if (!task.Run(callback)) {
1434                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1435             }
1436             ROSEN_TRACE_END(HITRACE_TAG_GRAPHIC_AGP);
1437         } else {
1438 #ifdef RS_ENABLE_GPU
1439             RSSurfaceCaptureParam captureParam;
1440             captureParam.id = id;
1441             captureParam.config = captureConfig;
1442             captureParam.isSystemCalling = isSystemCalling;
1443             captureParam.blurParam = blurParam;
1444             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1445             RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1446 #endif
1447         }
1448     };
1449     mainThread_->PostTask(captureTask);
1450 }
1451 
TakeSurfaceCaptureSoloNode(NodeId id,const RSSurfaceCaptureConfig & captureConfig,RSSurfaceCapturePermissions permissions)1452 std::vector<std::pair<NodeId, std::shared_ptr<Media::PixelMap>>> RSRenderServiceConnection::TakeSurfaceCaptureSoloNode(
1453     NodeId id, const RSSurfaceCaptureConfig& captureConfig, RSSurfaceCapturePermissions permissions)
1454 {
1455     RS_LOGI("TakeSurfaceCaptureSoloNode nodeId:[%{public}" PRIu64 "]", id);
1456     std::vector<std::pair<NodeId, std::shared_ptr<Media::PixelMap>>> pixelMapIdPairVector;
1457     std::function<void()> captureTask = [id, captureConfig, &pixelMapIdPairVector,
1458         isSystemCalling = permissions.isSystemCalling,
1459         selfCapture = permissions.selfCapture]() {
1460         RS_TRACE_NAME_FMT("RSRenderServiceConnection::TakeSurfaceCaptureSoloNode captureTask"
1461             " nodeId:[%" PRIu64 "]", id);
1462         RS_LOGI("TakeSurfaceCaptureSoloNode captureTask begin "
1463             "nodeId:[%{public}" PRIu64 "]", id);
1464         auto uiCaptureHasPermission = selfCapture || isSystemCalling;
1465         if (!uiCaptureHasPermission) {
1466             RS_LOGE("TakeSurfaceCaptureSoloNode "
1467                 "uicapturesolo failed, nodeId:[%{public}" PRIu64
1468                 "], isSystemCalling: %{public}u, selfCapture: %{public}u", id, isSystemCalling, selfCapture);
1469             return;
1470         }
1471         pixelMapIdPairVector = RSUiCaptureSoloTaskParallel::CaptureSoloNode(id, captureConfig);
1472     };
1473     RSMainThread::Instance()->PostSyncTask(captureTask);
1474     return pixelMapIdPairVector;
1475 }
1476 
TakeSelfSurfaceCapture(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)1477 void RSRenderServiceConnection::TakeSelfSurfaceCapture(
1478     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
1479 {
1480     if (!mainThread_) {
1481         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1482         return;
1483     }
1484     bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1485         RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ + "::TAKE_SELF_SURFACE_CAPTURE");
1486     std::function<void()> selfCaptureTask = [id, callback, captureConfig, isSystemCalling]() -> void {
1487         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1488         if (node == nullptr) {
1489             RS_LOGE("TakeSelfSurfaceCapture failed, node is nullptr");
1490             if (callback) {
1491                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1492             }
1493             return;
1494         }
1495         RSSurfaceCaptureParam captureParam;
1496         captureParam.id = id;
1497         captureParam.config = captureConfig;
1498         captureParam.isSystemCalling = isSystemCalling;
1499         captureParam.isSelfCapture = true;
1500         RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1501         RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1502     };
1503     mainThread_->PostTask(selfCaptureTask);
1504 }
1505 
TaskSurfaceCaptureWithAllWindows(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,bool checkDrmAndSurfaceLock,RSSurfaceCapturePermissions permissions)1506 ErrCode RSRenderServiceConnection::TaskSurfaceCaptureWithAllWindows(NodeId id,
1507     sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
1508     bool checkDrmAndSurfaceLock, RSSurfaceCapturePermissions permissions)
1509 {
1510     bool hasPermission = permissions.screenCapturePermission && permissions.isSystemCalling;
1511     if (!mainThread_ || !hasPermission) {
1512         if (callback) {
1513             callback->OnSurfaceCapture(id, captureConfig, nullptr);
1514         }
1515         RS_LOGE("%{public}s mainThread_ is nullptr or permission denied", __func__);
1516         return ERR_PERMISSION_DENIED;
1517     }
1518     RS_TRACE_NAME_FMT("TaskSurfaceCaptureWithAllWindows checkDrmAndSurfaceLock: %d", checkDrmAndSurfaceLock);
1519     std::function<void()> takeSurfaceCaptureTask =
1520         [id, checkDrmAndSurfaceLock, callback, captureConfig, hasPermission]() -> void {
1521         auto displayNode = RSBaseRenderNode::ReinterpretCast<RSLogicalDisplayRenderNode>(
1522             RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id));
1523         if (!displayNode) {
1524             if (callback) {
1525                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1526             }
1527             RS_LOGE("%{public}s failed, displayNode is nullptr", __func__);
1528             return;
1529         }
1530         RSSurfaceCaptureParam captureParam;
1531         captureParam.id = id;
1532         captureParam.config = captureConfig;
1533         captureParam.isSystemCalling = hasPermission;
1534         captureParam.secExemption = hasPermission;
1535         RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1536         RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1537     };
1538     mainThread_->PostTask(takeSurfaceCaptureTask);
1539     return ERR_OK;
1540 }
1541 
FreezeScreen(NodeId id,bool isFreeze)1542 ErrCode RSRenderServiceConnection::FreezeScreen(NodeId id, bool isFreeze)
1543 {
1544     if (!mainThread_) {
1545         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1546         return ERR_INVALID_OPERATION;
1547     }
1548     RS_TRACE_NAME_FMT("FreezeScreen isFreeze: %d", isFreeze);
1549     std::function<void()> setScreenFreezeTask = [id, isFreeze]() -> void {
1550         auto displayNode = RSBaseRenderNode::ReinterpretCast<RSLogicalDisplayRenderNode>(
1551             RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id));
1552         auto screenNode = displayNode == nullptr ? nullptr :
1553             std::static_pointer_cast<RSScreenRenderNode>(displayNode->GetParent().lock());
1554         if (!screenNode) {
1555             RS_LOGE("%{public}s failed, screenNode is nullptr", __func__);
1556             return;
1557         }
1558         screenNode->SetForceFreeze(isFreeze);
1559     };
1560     mainThread_->PostTask(setScreenFreezeTask);
1561     return ERR_OK;
1562 }
1563 
SetWindowFreezeImmediately(NodeId id,bool isFreeze,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig,const RSSurfaceCaptureBlurParam & blurParam)1564 ErrCode RSRenderServiceConnection::SetWindowFreezeImmediately(NodeId id, bool isFreeze,
1565     sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig,
1566     const RSSurfaceCaptureBlurParam& blurParam)
1567 {
1568     if (!mainThread_) {
1569         RS_LOGE("%{public}s mainThread_ is nullptr", __func__);
1570         return ERR_INVALID_VALUE;
1571     }
1572     bool isSystemCalling = RSInterfaceCodeAccessVerifierBase::IsSystemCalling(
1573         RSIRenderServiceConnectionInterfaceCodeAccessVerifier::codeEnumTypeName_ + "::SET_WINDOW_FREEZE_IMMEDIATELY");
1574     std::function<void()> setWindowFreezeTask =
1575         [id, isFreeze, callback, captureConfig, blurParam, isSystemCalling]() -> void {
1576         auto node = RSMainThread::Instance()->GetContext().GetNodeMap().GetRenderNode(id);
1577         if (node == nullptr) {
1578             RS_LOGE("SetWindowFreezeImmediately failed, node is nullptr");
1579             if (callback) {
1580                 callback->OnSurfaceCapture(id, captureConfig, nullptr);
1581             }
1582             return;
1583         }
1584         node->SetStaticCached(isFreeze);
1585         if (isFreeze) {
1586             RSSurfaceCaptureParam captureParam;
1587             captureParam.id = id;
1588             captureParam.config = captureConfig;
1589             captureParam.isSystemCalling = isSystemCalling;
1590             captureParam.isFreeze = isFreeze;
1591             captureParam.blurParam = blurParam;
1592             RSSurfaceCaptureTaskParallel::CheckModifiers(id, captureConfig.useCurWindow);
1593             RSSurfaceCaptureTaskParallel::Capture(callback, captureParam);
1594         } else {
1595             RSSurfaceCaptureTaskParallel::ClearCacheImageByFreeze(id);
1596         }
1597     };
1598     mainThread_->PostTask(setWindowFreezeTask);
1599     return ERR_OK;
1600 }
1601 
TakeUICaptureInRange(NodeId id,sptr<RSISurfaceCaptureCallback> callback,const RSSurfaceCaptureConfig & captureConfig)1602 void RSRenderServiceConnection::TakeUICaptureInRange(
1603     NodeId id, sptr<RSISurfaceCaptureCallback> callback, const RSSurfaceCaptureConfig& captureConfig)
1604 {
1605     std::function<void()> captureTask = [id, callback, captureConfig]() -> void {
1606         RS_TRACE_NAME_FMT("RSRenderServiceConnection::TakeUICaptureInRange captureTask nodeId:[%" PRIu64 "]", id);
1607         RS_LOGD("RSRenderServiceConnection::TakeUICaptureInRange captureTask nodeId:[%{public}" PRIu64 "]", id);
1608         TakeSurfaceCaptureForUiParallel(id, callback, captureConfig, {});
1609     };
1610     RSMainThread::Instance()->PostTask(captureTask);
1611 }
1612 
SetHwcNodeBounds(int64_t rsNodeId,float positionX,float positionY,float positionZ,float positionW)1613 ErrCode RSRenderServiceConnection::SetHwcNodeBounds(int64_t rsNodeId, float positionX, float positionY,
1614     float positionZ, float positionW)
1615 {
1616     if (mainThread_ == nullptr || screenManager_ == nullptr) {
1617         return ERR_INVALID_VALUE;
1618     }
1619 
1620     // adapt video scene pointer
1621     if (screenManager_->GetCurrentVirtualScreenNum() > 0 ||
1622         !RSPointerWindowManager::Instance().GetIsPointerEnableHwc()) {
1623         // when has virtual screen or pointer is enable hwc, we can't skip
1624         RSPointerWindowManager::Instance().SetIsPointerCanSkipFrame(false);
1625         RSMainThread::Instance()->RequestNextVSync();
1626     } else {
1627         RSPointerWindowManager::Instance().SetIsPointerCanSkipFrame(true);
1628     }
1629 
1630     RSPointerWindowManager::Instance().SetHwcNodeBounds(rsNodeId, positionX, positionY,
1631         positionZ, positionW);
1632     return ERR_OK;
1633 }
1634 
RegisterApplicationAgent(uint32_t pid,sptr<IApplicationAgent> app)1635 ErrCode RSRenderServiceConnection::RegisterApplicationAgent(uint32_t pid, sptr<IApplicationAgent> app)
1636 {
1637     if (!mainThread_) {
1638         RS_LOGE("RegisterApplicationAgent mainThread_ is nullptr");
1639         return ERR_INVALID_VALUE;
1640     }
1641     auto captureTask = [weakThis = wptr<RSRenderServiceConnection>(this), pid, app]() -> void {
1642         sptr<RSRenderServiceConnection> connection = weakThis.promote();
1643         if (connection == nullptr || connection->mainThread_ == nullptr) {
1644             RS_LOGE("RegisterApplicationAgent connection or mainThread_ is nullptr");
1645             return;
1646         }
1647         connection->mainThread_->RegisterApplicationAgent(pid, app);
1648     };
1649     mainThread_->PostTask(captureTask);
1650 
1651     app->AsObject()->AddDeathRecipient(applicationDeathRecipient_);
1652     return ERR_OK;
1653 }
1654 
UnRegisterApplicationAgent(sptr<IApplicationAgent> app)1655 void RSRenderServiceConnection::UnRegisterApplicationAgent(sptr<IApplicationAgent> app)
1656 {
1657     auto captureTask = [=]() -> void {
1658         RSMainThread::Instance()->UnRegisterApplicationAgent(app);
1659     };
1660     RSMainThread::Instance()->ScheduleTask(captureTask).wait();
1661 }
1662 
GetVirtualScreenResolution(ScreenId id)1663 RSVirtualScreenResolution RSRenderServiceConnection::GetVirtualScreenResolution(ScreenId id)
1664 {
1665     RSVirtualScreenResolution virtualScreenResolution;
1666     if (!screenManager_) {
1667         return virtualScreenResolution;
1668     }
1669     screenManager_->GetVirtualScreenResolution(id, virtualScreenResolution);
1670     return virtualScreenResolution;
1671 }
1672 
GetScreenActiveMode(uint64_t id,RSScreenModeInfo & screenModeInfo)1673 ErrCode RSRenderServiceConnection::GetScreenActiveMode(uint64_t id, RSScreenModeInfo& screenModeInfo)
1674 {
1675     if (!screenManager_) {
1676         return ERR_INVALID_VALUE;
1677     }
1678     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1679     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1680 #ifdef RS_ENABLE_GPU
1681         RSHardwareThread::Instance().ScheduleTask(
1682             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1683 #else
1684         return screenModeInfo;
1685 #endif
1686     } else if (mainThread_ != nullptr) {
1687         mainThread_->ScheduleTask(
1688             [=, &screenModeInfo]() { return screenManager_->GetScreenActiveMode(id, screenModeInfo); }).wait();
1689     }
1690     return ERR_OK;
1691 }
1692 
GetTotalAppMemSize(float & cpuMemSize,float & gpuMemSize)1693 ErrCode RSRenderServiceConnection::GetTotalAppMemSize(float& cpuMemSize, float& gpuMemSize)
1694 {
1695 #ifdef RS_ENABLE_GPU
1696     RSMainThread::Instance()->GetAppMemoryInMB(cpuMemSize, gpuMemSize);
1697     gpuMemSize += RSSubThreadManager::Instance()->GetAppGpuMemoryInMB();
1698 #endif
1699     return ERR_OK;
1700 }
1701 
GetMemoryGraphic(int pid,MemoryGraphic & memoryGraphic)1702 ErrCode RSRenderServiceConnection::GetMemoryGraphic(int pid, MemoryGraphic& memoryGraphic)
1703 {
1704     if (pid == 0) {
1705         return ERR_INVALID_VALUE;
1706     }
1707     bool enable;
1708     if (GetUniRenderEnabled(enable) == ERR_OK && enable) {
1709         renderThread_.PostSyncTask(
1710             [weakThis = wptr<RSRenderServiceConnection>(this), &memoryGraphic, &pid] {
1711                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
1712                 if (connection == nullptr) {
1713                     return;
1714                 }
1715                 memoryGraphic = MemoryManager::CountPidMemory(pid,
1716                     connection->renderThread_.GetRenderEngine()->GetRenderContext()->GetDrGPUContext());
1717             });
1718         return ERR_OK;
1719     } else {
1720         return ERR_INVALID_VALUE;
1721     }
1722 }
1723 
GetMemoryGraphics(std::vector<MemoryGraphic> & memoryGraphics)1724 ErrCode RSRenderServiceConnection::GetMemoryGraphics(std::vector<MemoryGraphic>& memoryGraphics)
1725 {
1726     bool res;
1727     if (!mainThread_ || GetUniRenderEnabled(res) != ERR_OK || !res) {
1728         return ERR_INVALID_VALUE;
1729     }
1730 
1731     mainThread_->ScheduleTask([mainThread = mainThread_, &memoryGraphics]() {
1732             mainThread->CountMem(memoryGraphics);
1733         }).wait();
1734     return ERR_OK;
1735 }
1736 
GetScreenSupportedModes(ScreenId id)1737 std::vector<RSScreenModeInfo> RSRenderServiceConnection::GetScreenSupportedModes(ScreenId id)
1738 {
1739     if (!screenManager_) {
1740         return std::vector<RSScreenModeInfo>();
1741     }
1742     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1743     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1744 #ifdef RS_ENABLE_GPU
1745         return RSHardwareThread::Instance().ScheduleTask(
1746             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1747 #else
1748         return std::vector<RSScreenModeInfo>();
1749 #endif
1750     } else if (mainThread_ != nullptr) {
1751         return mainThread_->ScheduleTask(
1752             [=]() { return screenManager_->GetScreenSupportedModes(id); }).get();
1753     } else {
1754         return std::vector<RSScreenModeInfo>();
1755     }
1756 }
1757 
GetScreenCapability(ScreenId id)1758 RSScreenCapability RSRenderServiceConnection::GetScreenCapability(ScreenId id)
1759 {
1760     RSScreenCapability screenCapability;
1761     if (!screenManager_) {
1762         return screenCapability;
1763     }
1764     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1765     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1766 #ifdef RS_ENABLE_GPU
1767         return RSHardwareThread::Instance().ScheduleTask(
1768             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1769 #else
1770         return screenCapability;
1771 #endif
1772     } else if (mainThread_ != nullptr) {
1773         return mainThread_->ScheduleTask(
1774             [=]() { return screenManager_->GetScreenCapability(id); }).get();
1775     } else {
1776         return screenCapability;
1777     }
1778 }
1779 
GetScreenPowerStatus(uint64_t screenId,uint32_t & status)1780 ErrCode RSRenderServiceConnection::GetScreenPowerStatus(uint64_t screenId, uint32_t& status)
1781 {
1782     if (!screenManager_) {
1783         status = ScreenPowerStatus::INVALID_POWER_STATUS;
1784         return ERR_INVALID_VALUE;
1785     }
1786     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1787     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1788 #ifdef RS_ENABLE_GPU
1789         status = RSHardwareThread::Instance().ScheduleTask(
1790             [=]() { return screenManager_->GetScreenPowerStatus(screenId); }).get();
1791 #else
1792         status = ScreenPowerStatus::INVALID_POWER_STATUS;
1793 #endif
1794     } else if (mainThread_ != nullptr) {
1795         status = mainThread_->ScheduleTask(
1796             [=]() { return screenManager_->GetScreenPowerStatus(screenId); }).get();
1797     } else {
1798         status = ScreenPowerStatus::INVALID_POWER_STATUS;
1799         return ERR_INVALID_VALUE;
1800     }
1801     return ERR_OK;
1802 }
1803 
GetScreenData(ScreenId id)1804 RSScreenData RSRenderServiceConnection::GetScreenData(ScreenId id)
1805 {
1806     RSScreenData screenData;
1807     if (!screenManager_) {
1808         return screenData;
1809     }
1810     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1811     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1812 #ifdef RS_ENABLE_GPU
1813         return RSHardwareThread::Instance().ScheduleTask(
1814             [=]() { return screenManager_->GetScreenData(id); }).get();
1815 #else
1816         return screenData;
1817 #endif
1818     } else if (mainThread_ != nullptr) {
1819         return mainThread_->ScheduleTask(
1820             [=]() { return screenManager_->GetScreenData(id); }).get();
1821     } else {
1822         return screenData;
1823     }
1824 }
1825 
GetScreenBacklight(uint64_t id,int32_t & level)1826 ErrCode RSRenderServiceConnection::GetScreenBacklight(uint64_t id, int32_t& level)
1827 {
1828     if (!screenManager_) {
1829         level = INVALID_BACKLIGHT_VALUE;
1830         return ERR_INVALID_VALUE;
1831     }
1832     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1833     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1834 #ifdef RS_ENABLE_GPU
1835         level = RSHardwareThread::Instance().ScheduleTask(
1836             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1837 #else
1838         level = INVALID_BACKLIGHT_VALUE;
1839 #endif
1840     } else if (mainThread_ != nullptr) {
1841         level = mainThread_->ScheduleTask(
1842             [=]() { return screenManager_->GetScreenBacklight(id); }).get();
1843     } else {
1844         level = INVALID_BACKLIGHT_VALUE;
1845         return ERR_INVALID_VALUE;
1846     }
1847     return ERR_OK;
1848 }
1849 
SetScreenBacklight(ScreenId id,uint32_t level)1850 void RSRenderServiceConnection::SetScreenBacklight(ScreenId id, uint32_t level)
1851 {
1852     if (!screenManager_) {
1853         RS_LOGE("%{public}s screenManager_ is nullptr.", __func__);
1854         return;
1855     }
1856     RSLuminanceControl::Get().SetSdrLuminance(id, level);
1857     if (RSLuminanceControl::Get().IsHdrOn(id) && level > 0 && mainThread_ != nullptr) {
1858         auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id]() {
1859             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1860             if (connection == nullptr || connection->mainThread_ == nullptr) {
1861                 RS_LOGE("SetScreenBacklight fail");
1862                 return;
1863             }
1864             connection->mainThread_->SetLuminanceChangingStatus(id, true);
1865             connection->mainThread_->SetDirtyFlag();
1866             connection->mainThread_->RequestNextVSync();
1867         };
1868         mainThread_->PostTask(task);
1869         return;
1870     }
1871 
1872     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1873     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1874 #ifdef RS_ENABLE_GPU
1875         screenManager_->SetScreenBacklight(id, level);
1876 #endif
1877     } else if (mainThread_ != nullptr) {
1878         mainThread_->ScheduleTask(
1879             [=]() { screenManager_->SetScreenBacklight(id, level); }).wait();
1880     }
1881 }
1882 
RegisterBufferClearListener(NodeId id,sptr<RSIBufferClearCallback> callback)1883 ErrCode RSRenderServiceConnection::RegisterBufferClearListener(
1884     NodeId id, sptr<RSIBufferClearCallback> callback)
1885 {
1886     if (!mainThread_) {
1887         return ERR_INVALID_VALUE;
1888     }
1889     auto registerBufferClearListener =
1890         [id, callback, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1891             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1892             if (connection == nullptr || connection->mainThread_ == nullptr) {
1893                 return false;
1894             }
1895             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1896                 node->RegisterBufferClearListener(callback);
1897                 return true;
1898             }
1899             return false;
1900     };
1901     mainThread_->PostTask(registerBufferClearListener);
1902     return ERR_OK;
1903 }
1904 
RegisterBufferAvailableListener(NodeId id,sptr<RSIBufferAvailableCallback> callback,bool isFromRenderThread)1905 ErrCode RSRenderServiceConnection::RegisterBufferAvailableListener(
1906     NodeId id, sptr<RSIBufferAvailableCallback> callback, bool isFromRenderThread)
1907 {
1908     if (!mainThread_) {
1909         return ERR_INVALID_VALUE;
1910     }
1911     auto registerBufferAvailableListener =
1912         [id, callback, isFromRenderThread, weakThis = wptr<RSRenderServiceConnection>(this)]() -> bool {
1913             sptr<RSRenderServiceConnection> connection = weakThis.promote();
1914             if (connection == nullptr || connection->mainThread_ == nullptr) {
1915                 return false;
1916             }
1917             if (auto node = connection->mainThread_->GetContext().GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id)) {
1918                 node->RegisterBufferAvailableListener(callback, isFromRenderThread);
1919                 return true;
1920             }
1921             return false;
1922     };
1923     mainThread_->PostTask(registerBufferAvailableListener);
1924     return ERR_OK;
1925 }
1926 
GetScreenSupportedColorGamuts(ScreenId id,std::vector<ScreenColorGamut> & mode)1927 int32_t RSRenderServiceConnection::GetScreenSupportedColorGamuts(ScreenId id, std::vector<ScreenColorGamut>& mode)
1928 {
1929     if (!screenManager_) {
1930         return StatusCode::SCREEN_NOT_FOUND;
1931     }
1932     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1933     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1934 #ifdef RS_ENABLE_GPU
1935         return RSHardwareThread::Instance().ScheduleTask(
1936             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1937 #else
1938         return StatusCode::SCREEN_NOT_FOUND;
1939 #endif
1940     } else if (mainThread_ != nullptr) {
1941         return mainThread_->ScheduleTask(
1942             [=, &mode]() { return screenManager_->GetScreenSupportedColorGamuts(id, mode); }).get();
1943     } else {
1944         return StatusCode::SCREEN_NOT_FOUND;
1945     }
1946 }
1947 
GetScreenSupportedMetaDataKeys(ScreenId id,std::vector<ScreenHDRMetadataKey> & keys)1948 int32_t RSRenderServiceConnection::GetScreenSupportedMetaDataKeys(ScreenId id, std::vector<ScreenHDRMetadataKey>& keys)
1949 {
1950     if (!screenManager_) {
1951         return StatusCode::SCREEN_NOT_FOUND;
1952     }
1953     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1954     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1955 #ifdef RS_ENABLE_GPU
1956         return RSHardwareThread::Instance().ScheduleTask(
1957             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1958 #else
1959         return StatusCode::SCREEN_NOT_FOUND;
1960 #endif
1961     } else if (mainThread_ != nullptr) {
1962         return mainThread_->ScheduleTask(
1963             [=, &keys]() { return screenManager_->GetScreenSupportedMetaDataKeys(id, keys); }).get();
1964     } else {
1965         return StatusCode::SCREEN_NOT_FOUND;
1966     }
1967 }
1968 
GetScreenColorGamut(ScreenId id,ScreenColorGamut & mode)1969 int32_t RSRenderServiceConnection::GetScreenColorGamut(ScreenId id, ScreenColorGamut& mode)
1970 {
1971     if (!screenManager_) {
1972         return StatusCode::SCREEN_NOT_FOUND;
1973     }
1974     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1975     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1976 #ifdef RS_ENABLE_GPU
1977         return RSHardwareThread::Instance().ScheduleTask(
1978             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1979 #else
1980         return StatusCode::SCREEN_NOT_FOUND;
1981 #endif
1982     } else if (mainThread_ != nullptr) {
1983         return mainThread_->ScheduleTask(
1984             [=, &mode]() { return screenManager_->GetScreenColorGamut(id, mode); }).get();
1985     } else {
1986         return StatusCode::SCREEN_NOT_FOUND;
1987     }
1988 }
1989 
SetScreenColorGamut(ScreenId id,int32_t modeIdx)1990 int32_t RSRenderServiceConnection::SetScreenColorGamut(ScreenId id, int32_t modeIdx)
1991 {
1992     if (!screenManager_) {
1993         return StatusCode::SCREEN_NOT_FOUND;
1994     }
1995     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
1996     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
1997 #ifdef RS_ENABLE_GPU
1998         return RSHardwareThread::Instance().ScheduleTask(
1999             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
2000 #else
2001         return StatusCode::SCREEN_NOT_FOUND;
2002 #endif
2003     } else if (mainThread_ != nullptr) {
2004         return mainThread_->ScheduleTask(
2005             [=]() { return screenManager_->SetScreenColorGamut(id, modeIdx); }).get();
2006     } else {
2007         return StatusCode::SCREEN_NOT_FOUND;
2008     }
2009 }
2010 
SetScreenGamutMap(ScreenId id,ScreenGamutMap mode)2011 int32_t RSRenderServiceConnection::SetScreenGamutMap(ScreenId id, ScreenGamutMap mode)
2012 {
2013     if (!screenManager_) {
2014         return StatusCode::SCREEN_NOT_FOUND;
2015     }
2016     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2017     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2018 #ifdef RS_ENABLE_GPU
2019         return RSHardwareThread::Instance().ScheduleTask(
2020             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
2021 #else
2022         return StatusCode::SCREEN_NOT_FOUND;
2023 #endif
2024     } else if (mainThread_ != nullptr) {
2025         return mainThread_->ScheduleTask(
2026             [=]() { return screenManager_->SetScreenGamutMap(id, mode); }).get();
2027     } else {
2028         return StatusCode::SCREEN_NOT_FOUND;
2029     }
2030 }
2031 
SetScreenCorrection(ScreenId id,ScreenRotation screenRotation)2032 int32_t RSRenderServiceConnection::SetScreenCorrection(ScreenId id, ScreenRotation screenRotation)
2033 {
2034     std::lock_guard<std::mutex> lock(mutex_);
2035     if (!screenManager_) {
2036         return StatusCode::SCREEN_NOT_FOUND;
2037     }
2038     return screenManager_->SetScreenCorrection(id, screenRotation);
2039 }
2040 
SetVirtualMirrorScreenCanvasRotation(ScreenId id,bool canvasRotation)2041 bool RSRenderServiceConnection::SetVirtualMirrorScreenCanvasRotation(ScreenId id, bool canvasRotation)
2042 {
2043     std::lock_guard<std::mutex> lock(mutex_);
2044     if (!screenManager_) {
2045         return false;
2046     }
2047     return screenManager_->SetVirtualMirrorScreenCanvasRotation(id, canvasRotation);
2048 }
2049 
SetVirtualScreenAutoRotation(ScreenId id,bool isAutoRotation)2050 int32_t RSRenderServiceConnection::SetVirtualScreenAutoRotation(ScreenId id, bool isAutoRotation)
2051 {
2052     if (!screenManager_) {
2053         return StatusCode::SCREEN_MANAGER_NULL;
2054     }
2055     return screenManager_->SetVirtualScreenAutoRotation(id, isAutoRotation);
2056 }
2057 
SetGlobalDarkColorMode(bool isDark)2058 ErrCode RSRenderServiceConnection::SetGlobalDarkColorMode(bool isDark)
2059 {
2060     std::lock_guard<std::mutex> lock(mutex_);
2061     if (!mainThread_) {
2062         return ERR_INVALID_VALUE;
2063     }
2064     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isDark]() {
2065         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2066         if (connection == nullptr || connection->mainThread_ == nullptr) {
2067             RS_LOGE("SetGlobalDarkColorMode fail");
2068             return;
2069         }
2070         connection->mainThread_->SetGlobalDarkColorMode(isDark);
2071     };
2072     mainThread_->PostTask(task);
2073     return ERR_OK;
2074 }
2075 
SetVirtualMirrorScreenScaleMode(ScreenId id,ScreenScaleMode scaleMode)2076 bool RSRenderServiceConnection::SetVirtualMirrorScreenScaleMode(ScreenId id, ScreenScaleMode scaleMode)
2077 {
2078     std::lock_guard<std::mutex> lock(mutex_);
2079     if (!screenManager_) {
2080         return false;
2081     }
2082     return screenManager_->SetVirtualMirrorScreenScaleMode(id, scaleMode);
2083 }
2084 
GetScreenGamutMap(ScreenId id,ScreenGamutMap & mode)2085 int32_t RSRenderServiceConnection::GetScreenGamutMap(ScreenId id, ScreenGamutMap& mode)
2086 {
2087     if (!screenManager_) {
2088         return StatusCode::SCREEN_NOT_FOUND;
2089     }
2090     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2091     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2092 #ifdef RS_ENABLE_GPU
2093         return RSHardwareThread::Instance().ScheduleTask(
2094             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
2095 #else
2096         return StatusCode::SCREEN_NOT_FOUND;
2097 #endif
2098     } else if (mainThread_ != nullptr) {
2099         return mainThread_->ScheduleTask(
2100             [=, &mode]() { return screenManager_->GetScreenGamutMap(id, mode); }).get();
2101     } else {
2102         return StatusCode::SCREEN_NOT_FOUND;
2103     }
2104 }
2105 
GetScreenHDRCapability(ScreenId id,RSScreenHDRCapability & screenHdrCapability)2106 int32_t RSRenderServiceConnection::GetScreenHDRCapability(ScreenId id, RSScreenHDRCapability& screenHdrCapability)
2107 {
2108     std::lock_guard<std::mutex> lock(mutex_);
2109     if (!screenManager_) {
2110         return StatusCode::SCREEN_NOT_FOUND;
2111     }
2112     return screenManager_->GetScreenHDRCapability(id, screenHdrCapability);
2113 }
2114 
GetPixelFormat(ScreenId id,GraphicPixelFormat & pixelFormat,int32_t & resCode)2115 ErrCode RSRenderServiceConnection::GetPixelFormat(ScreenId id, GraphicPixelFormat& pixelFormat, int32_t& resCode)
2116 {
2117     if (!screenManager_) {
2118         resCode = StatusCode::SCREEN_NOT_FOUND;
2119         return ERR_INVALID_VALUE;
2120     }
2121     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2122     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2123 #ifdef RS_ENABLE_GPU
2124         resCode = RSHardwareThread::Instance().ScheduleTask(
2125             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
2126         return ERR_OK;
2127 #else
2128         resCode = StatusCode::SCREEN_NOT_FOUND;
2129         return ERR_INVALID_VALUE;
2130 #endif
2131     } else if (mainThread_ != nullptr) {
2132         resCode = mainThread_->ScheduleTask(
2133             [=, &pixelFormat]() { return screenManager_->GetPixelFormat(id, pixelFormat); }).get();
2134         return ERR_OK;
2135     } else {
2136         resCode = StatusCode::SCREEN_NOT_FOUND;
2137         return ERR_INVALID_VALUE;
2138     }
2139 }
2140 
SetPixelFormat(ScreenId id,GraphicPixelFormat pixelFormat,int32_t & resCode)2141 ErrCode RSRenderServiceConnection::SetPixelFormat(ScreenId id, GraphicPixelFormat pixelFormat, int32_t& resCode)
2142 {
2143     if (!screenManager_) {
2144         resCode = StatusCode::SCREEN_NOT_FOUND;
2145         return ERR_INVALID_VALUE;
2146     }
2147     if (pixelFormat < 0 ||
2148         (pixelFormat >= GRAPHIC_PIXEL_FMT_END_OF_VALID && pixelFormat != GRAPHIC_PIXEL_FMT_VENDER_MASK)) {
2149         resCode = StatusCode::INVALID_ARGUMENTS;
2150         return ERR_INVALID_VALUE;
2151     }
2152     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2153     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2154 #ifdef RS_ENABLE_GPU
2155         resCode = RSHardwareThread::Instance().ScheduleTask(
2156             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
2157         return ERR_OK;
2158 #else
2159         resCode = StatusCode::SCREEN_NOT_FOUND;
2160         return ERR_INVALID_VALUE;
2161 #endif
2162     } else if (mainThread_ != nullptr) {
2163         resCode = mainThread_->ScheduleTask(
2164             [=]() { return screenManager_->SetPixelFormat(id, pixelFormat); }).get();
2165         return ERR_OK;
2166     } else {
2167         resCode = StatusCode::SCREEN_NOT_FOUND;
2168         return ERR_INVALID_VALUE;
2169     }
2170 }
2171 
GetScreenSupportedHDRFormats(ScreenId id,std::vector<ScreenHDRFormat> & hdrFormats,int32_t & resCode)2172 ErrCode RSRenderServiceConnection::GetScreenSupportedHDRFormats(
2173     ScreenId id, std::vector<ScreenHDRFormat>& hdrFormats, int32_t& resCode)
2174 {
2175     if (!screenManager_) {
2176         resCode = StatusCode::SCREEN_NOT_FOUND;
2177         return ERR_INVALID_VALUE;
2178     }
2179     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2180     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2181 #ifdef RS_ENABLE_GPU
2182         resCode = RSHardwareThread::Instance().ScheduleTask(
2183             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
2184         return ERR_OK;
2185 #else
2186         resCode = StatusCode::SCREEN_NOT_FOUND;
2187         return ERR_INVALID_VALUE;
2188 #endif
2189     } else if (mainThread_ != nullptr) {
2190         resCode = mainThread_->ScheduleTask(
2191             [=, &hdrFormats]() { return screenManager_->GetScreenSupportedHDRFormats(id, hdrFormats); }).get();
2192         return ERR_OK;
2193     } else {
2194         resCode = StatusCode::SCREEN_NOT_FOUND;
2195         return ERR_INVALID_VALUE;
2196     }
2197 }
2198 
GetScreenHDRFormat(ScreenId id,ScreenHDRFormat & hdrFormat,int32_t & resCode)2199 ErrCode RSRenderServiceConnection::GetScreenHDRFormat(ScreenId id, ScreenHDRFormat& hdrFormat, int32_t& resCode)
2200 {
2201     if (!screenManager_) {
2202         resCode = StatusCode::SCREEN_NOT_FOUND;
2203         return ERR_INVALID_VALUE;
2204     }
2205     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2206     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2207 #ifdef RS_ENABLE_GPU
2208         resCode = RSHardwareThread::Instance().ScheduleTask(
2209             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
2210         return ERR_OK;
2211 #else
2212         resCode = StatusCode::SCREEN_NOT_FOUND;
2213         return ERR_INVALID_VALUE;
2214 #endif
2215     } else if (mainThread_ != nullptr) {
2216         resCode = mainThread_->ScheduleTask(
2217             [=, &hdrFormat]() { return screenManager_->GetScreenHDRFormat(id, hdrFormat); }).get();
2218         return ERR_OK;
2219     } else {
2220         resCode = StatusCode::SCREEN_NOT_FOUND;
2221         return ERR_INVALID_VALUE;
2222     }
2223 }
2224 
SetScreenHDRFormat(ScreenId id,int32_t modeIdx,int32_t & resCode)2225 ErrCode RSRenderServiceConnection::SetScreenHDRFormat(ScreenId id, int32_t modeIdx, int32_t& resCode)
2226 {
2227     if (!screenManager_) {
2228         resCode = StatusCode::SCREEN_NOT_FOUND;
2229         return ERR_INVALID_VALUE;
2230     }
2231     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2232     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2233 #ifdef RS_ENABLE_GPU
2234         resCode = RSHardwareThread::Instance().ScheduleTask(
2235             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
2236         return ERR_OK;
2237 #else
2238         resCode = StatusCode::SCREEN_NOT_FOUND;
2239         return ERR_INVALID_VALUE;
2240 #endif
2241     } else if (mainThread_ != nullptr) {
2242         resCode = mainThread_->ScheduleTask(
2243             [=]() { return screenManager_->SetScreenHDRFormat(id, modeIdx); }).get();
2244         return ERR_OK;
2245     } else {
2246         resCode = StatusCode::SCREEN_NOT_FOUND;
2247         return ERR_INVALID_VALUE;
2248     }
2249 }
2250 
GetScreenHDRStatus(ScreenId id,HdrStatus & hdrStatus,int32_t & resCode)2251 ErrCode RSRenderServiceConnection::GetScreenHDRStatus(ScreenId id, HdrStatus& hdrStatus, int32_t& resCode)
2252 {
2253     if (mainThread_ == nullptr) {
2254         return ERR_INVALID_VALUE;
2255     }
2256     HdrStatus hdrStatusRet = HdrStatus::NO_HDR;
2257     StatusCode resCodeRet = StatusCode::SCREEN_NOT_FOUND;
2258     auto isTimeout = std::make_shared<bool>(0);
2259     std::weak_ptr<bool> isTimeoutWeak = isTimeout;
2260     auto task = [id, mainThread = mainThread_, &resCodeRet, &hdrStatusRet, isTimeoutWeak]() {
2261         if (isTimeoutWeak.expired()) {
2262             RS_LOGE("GetScreenHDRStatus time out, ScreenId: [%{public}" PRIu64 "]", id);
2263             return;
2264         }
2265         std::shared_ptr<RSScreenRenderNode> screenNode = nullptr;
2266         auto& nodeMap = mainThread->GetContext().GetNodeMap();
2267         nodeMap.TraverseScreenNodes([id, &screenNode](const std::shared_ptr<RSScreenRenderNode>& node) {
2268             if (node && node->GetScreenId() == id) {
2269                 screenNode = node;
2270             }
2271         });
2272         if (screenNode == nullptr) {
2273             resCodeRet = StatusCode::SCREEN_NOT_FOUND;
2274             return;
2275         }
2276         hdrStatusRet = screenNode->GetLastDisplayHDRStatus();
2277         resCodeRet = StatusCode::SUCCESS;
2278     };
2279     auto span = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(100)); // timeout 100 ms
2280     if (mainThread_->ScheduleTask(task).wait_for(span) == std::future_status::timeout) {
2281         isTimeout.reset();
2282     }
2283     if (isTimeoutWeak.expired() && resCodeRet != StatusCode::SUCCESS) {
2284         return ERR_TIMED_OUT;
2285     }
2286     if (resCodeRet == StatusCode::SUCCESS) {
2287         hdrStatus = hdrStatusRet;
2288     }
2289     resCode = resCodeRet;
2290     return ERR_OK;
2291 }
2292 
GetScreenSupportedColorSpaces(ScreenId id,std::vector<GraphicCM_ColorSpaceType> & colorSpaces,int32_t & resCode)2293 ErrCode RSRenderServiceConnection::GetScreenSupportedColorSpaces(
2294     ScreenId id, std::vector<GraphicCM_ColorSpaceType>& colorSpaces, int32_t& resCode)
2295 {
2296     if (!screenManager_) {
2297         resCode = StatusCode::SCREEN_NOT_FOUND;
2298         return ERR_INVALID_VALUE;
2299     }
2300     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2301     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2302 #ifdef RS_ENABLE_GPU
2303         resCode = RSHardwareThread::Instance().ScheduleTask(
2304             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
2305         return ERR_OK;
2306 #else
2307         resCode = StatusCode::SCREEN_NOT_FOUND;
2308         return ERR_INVALID_VALUE;
2309 #endif
2310     } else if (mainThread_ != nullptr) {
2311         resCode = mainThread_->ScheduleTask(
2312             [=, &colorSpaces]() { return screenManager_->GetScreenSupportedColorSpaces(id, colorSpaces); }).get();
2313         return ERR_OK;
2314     } else {
2315         resCode = StatusCode::SCREEN_NOT_FOUND;
2316         return ERR_INVALID_VALUE;
2317     }
2318 }
2319 
GetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType & colorSpace,int32_t & resCode)2320 ErrCode RSRenderServiceConnection::GetScreenColorSpace(
2321     ScreenId id, GraphicCM_ColorSpaceType& colorSpace, int32_t& resCode)
2322 {
2323     if (!screenManager_) {
2324         resCode = StatusCode::SCREEN_NOT_FOUND;
2325         return ERR_INVALID_VALUE;
2326     }
2327     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2328     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2329 #ifdef RS_ENABLE_GPU
2330         resCode = RSHardwareThread::Instance().ScheduleTask(
2331             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
2332         return ERR_OK;
2333 #else
2334         resCode = StatusCode::SCREEN_NOT_FOUND;
2335         return ERR_INVALID_VALUE;
2336 #endif
2337     } else if (mainThread_ != nullptr) {
2338         resCode = mainThread_->ScheduleTask(
2339             [=, &colorSpace]() { return screenManager_->GetScreenColorSpace(id, colorSpace); }).get();
2340         return ERR_OK;
2341     } else {
2342         resCode = StatusCode::SCREEN_NOT_FOUND;
2343         return ERR_INVALID_VALUE;
2344     }
2345 }
2346 
SetScreenColorSpace(ScreenId id,GraphicCM_ColorSpaceType colorSpace,int32_t & resCode)2347 ErrCode RSRenderServiceConnection::SetScreenColorSpace(
2348     ScreenId id, GraphicCM_ColorSpaceType colorSpace, int32_t& resCode)
2349 {
2350     if (!screenManager_) {
2351         resCode = StatusCode::SCREEN_NOT_FOUND;
2352         return ERR_INVALID_VALUE;
2353     }
2354     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2355     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2356 #ifdef RS_ENABLE_GPU
2357         resCode = RSHardwareThread::Instance().ScheduleTask(
2358             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
2359         return ERR_OK;
2360 #else
2361         resCode = StatusCode::SCREEN_NOT_FOUND;
2362         return ERR_INVALID_VALUE;
2363 #endif
2364     } else if (mainThread_ != nullptr) {
2365         resCode = mainThread_->ScheduleTask(
2366             [=]() { return screenManager_->SetScreenColorSpace(id, colorSpace); }).get();
2367         return ERR_OK;
2368     } else {
2369         resCode = StatusCode::SCREEN_NOT_FOUND;
2370         return ERR_INVALID_VALUE;
2371     }
2372 }
2373 
GetScreenType(ScreenId id,RSScreenType & screenType)2374 int32_t RSRenderServiceConnection::GetScreenType(ScreenId id, RSScreenType& screenType)
2375 {
2376     std::lock_guard<std::mutex> lock(mutex_);
2377     if (!screenManager_) {
2378         return StatusCode::SCREEN_NOT_FOUND;
2379     }
2380     return screenManager_->GetScreenType(id, screenType);
2381 }
2382 
GetBitmap(NodeId id,Drawing::Bitmap & bitmap,bool & success)2383 ErrCode RSRenderServiceConnection::GetBitmap(NodeId id, Drawing::Bitmap& bitmap, bool& success)
2384 {
2385     if (!mainThread_) {
2386         success = false;
2387         return ERR_INVALID_VALUE;
2388     }
2389     std::promise<bool> result;
2390     std::future<bool> future = result.get_future();
2391     RSMainThread* mainThread = mainThread_;
2392 #ifdef RS_ENABLE_GPU
2393     RSUniRenderThread* renderThread = &renderThread_;
2394     auto getBitmapTask = [id, &bitmap, mainThread, renderThread, &result]() {
2395         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
2396         if (node == nullptr) {
2397             RS_LOGE("GetBitmap cannot find NodeId: [%{public}" PRIu64 "]", id);
2398             result.set_value(false);
2399             return;
2400         }
2401         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
2402             RS_LOGE("GetBitmap RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
2403             result.set_value(false);
2404             return;
2405         }
2406         auto grContext = renderThread->GetRenderEngine()->GetRenderContext()->GetDrGPUContext();
2407         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
2408         auto getDrawableBitmapTask = [drawableNode, &bitmap, grContext, &result]() {
2409             bitmap = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)
2410                 ->GetBitmap(grContext);
2411             result.set_value(!bitmap.IsEmpty());
2412         };
2413         renderThread->PostTask(getDrawableBitmapTask);
2414     };
2415     mainThread_->PostTask(getBitmapTask);
2416 #endif
2417     success = future.get();
2418     return ERR_OK;
2419 }
2420 
GetPixelmap(NodeId id,const std::shared_ptr<Media::PixelMap> pixelmap,const Drawing::Rect * rect,std::shared_ptr<Drawing::DrawCmdList> drawCmdList,bool & success)2421 ErrCode RSRenderServiceConnection::GetPixelmap(NodeId id, const std::shared_ptr<Media::PixelMap> pixelmap,
2422     const Drawing::Rect* rect, std::shared_ptr<Drawing::DrawCmdList> drawCmdList, bool& success)
2423 {
2424     if (!mainThread_) {
2425         success = false;
2426         return ERR_INVALID_VALUE;
2427     }
2428     std::promise<bool> result;
2429     std::future<bool> future = result.get_future();
2430 #ifdef RS_ENABLE_GPU
2431     RSMainThread* mainThread = mainThread_;
2432     RSUniRenderThread* renderThread = &renderThread_;
2433     auto getPixelMapTask = [id, pixelmap, rect, drawCmdList, mainThread, renderThread, &result]() {
2434         auto node = mainThread->GetContext().GetNodeMap().GetRenderNode<RSCanvasDrawingRenderNode>(id);
2435         if (node == nullptr) {
2436             RS_LOGD("GetPixelmap: cannot find NodeId: [%{public}" PRIu64 "]", id);
2437             result.set_value(false);
2438             return;
2439         }
2440         if (node->GetType() != RSRenderNodeType::CANVAS_DRAWING_NODE) {
2441             RS_LOGE("GetPixelmap: RenderNodeType != RSRenderNodeType::CANVAS_DRAWING_NODE");
2442             result.set_value(false);
2443             return;
2444         }
2445 
2446         auto tid = node->GetTid(); // planning: id may change in subthread
2447         auto drawableNode = DrawableV2::RSRenderNodeDrawableAdapter::OnGenerate(node);
2448         if (drawableNode) {
2449             tid = std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->GetTid();
2450         }
2451         auto getDrawablePixelmapTask = [drawableNode, pixelmap, rect, &result, tid, drawCmdList]() {
2452             result.set_value(std::static_pointer_cast<DrawableV2::RSCanvasDrawingRenderNodeDrawable>(drawableNode)->
2453                 GetPixelmap(pixelmap, rect, tid, drawCmdList));
2454         };
2455         if (!node->IsOnTheTree()) {
2456             node->ClearOp();
2457         }
2458         if (tid == UNI_MAIN_THREAD_INDEX) {
2459             if (!mainThread->IsIdle() && mainThread->GetContext().HasActiveNode(node)) {
2460                 result.set_value(false);
2461                 return;
2462             }
2463             result.set_value(node->GetPixelmap(pixelmap, rect, tid, drawCmdList));
2464         } else if (tid == UNI_RENDER_THREAD_INDEX) {
2465             renderThread->PostTask(getDrawablePixelmapTask);
2466         } else {
2467             const auto& tidMap = RSSubThreadManager::Instance()->GetReThreadIndexMap();
2468             if (auto found = tidMap.find(tid); found != tidMap.end()) {
2469                 RSTaskDispatcher::GetInstance().PostTask(found->second, getDrawablePixelmapTask, false);
2470             } else {
2471                 renderThread->PostTask(getDrawablePixelmapTask);
2472             }
2473         }
2474     };
2475     mainThread_->PostTask(getPixelMapTask);
2476 #endif
2477     success = future.get();
2478     return ERR_OK;
2479 }
2480 
RegisterTypeface(uint64_t globalUniqueId,std::shared_ptr<Drawing::Typeface> & typeface)2481 bool RSRenderServiceConnection::RegisterTypeface(uint64_t globalUniqueId,
2482     std::shared_ptr<Drawing::Typeface>& typeface)
2483 {
2484     RS_LOGI("reg typeface, pid[%{public}d], familyname:%{public}s, uniqueid:%{public}u",
2485         RSTypefaceCache::GetTypefacePid(globalUniqueId), typeface->GetFamilyName().c_str(),
2486         RSTypefaceCache::GetTypefaceId(globalUniqueId));
2487     RSTypefaceCache::Instance().CacheDrawingTypeface(globalUniqueId, typeface);
2488     return true;
2489 }
2490 
UnRegisterTypeface(uint64_t globalUniqueId)2491 bool RSRenderServiceConnection::UnRegisterTypeface(uint64_t globalUniqueId)
2492 {
2493     RS_LOGW("uneg typeface: pid[%{public}d], uniqueid:%{public}u",
2494         RSTypefaceCache::GetTypefacePid(globalUniqueId), RSTypefaceCache::GetTypefaceId(globalUniqueId));
2495     RSTypefaceCache::Instance().AddDelayDestroyQueue(globalUniqueId);
2496     return true;
2497 }
2498 
GetDisplayIdentificationData(ScreenId id,uint8_t & outPort,std::vector<uint8_t> & edidData)2499 int32_t RSRenderServiceConnection::GetDisplayIdentificationData(ScreenId id, uint8_t& outPort,
2500     std::vector<uint8_t>& edidData)
2501 {
2502     std::lock_guard<std::mutex> lock(mutex_);
2503     if (!screenManager_) {
2504         return StatusCode::SCREEN_NOT_FOUND;
2505     }
2506     return screenManager_->GetDisplayIdentificationData(id, outPort, edidData);
2507 }
2508 
SetScreenSkipFrameInterval(uint64_t id,uint32_t skipFrameInterval,int32_t & resCode)2509 ErrCode RSRenderServiceConnection::SetScreenSkipFrameInterval(uint64_t id, uint32_t skipFrameInterval, int32_t& resCode)
2510 {
2511     if (!screenManager_) {
2512         resCode = StatusCode::SCREEN_NOT_FOUND;
2513         return ERR_INVALID_VALUE;
2514     }
2515     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2516     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2517 #ifdef RS_ENABLE_GPU
2518         resCode = RSHardwareThread::Instance().ScheduleTask(
2519             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
2520 #else
2521         resCode = StatusCode::SCREEN_NOT_FOUND;
2522 #endif
2523     } else {
2524         if (!mainThread_) {
2525             resCode = StatusCode::INVALID_ARGUMENTS;
2526             return ERR_INVALID_VALUE;
2527         }
2528         resCode = mainThread_->ScheduleTask(
2529             [=]() { return screenManager_->SetScreenSkipFrameInterval(id, skipFrameInterval); }).get();
2530     }
2531     return ERR_OK;
2532 }
2533 
SetVirtualScreenRefreshRate(ScreenId id,uint32_t maxRefreshRate,uint32_t & actualRefreshRate,int32_t & retVal)2534 ErrCode RSRenderServiceConnection::SetVirtualScreenRefreshRate(
2535     ScreenId id, uint32_t maxRefreshRate, uint32_t& actualRefreshRate, int32_t& retVal)
2536 {
2537     if (!screenManager_) {
2538         retVal = StatusCode::SCREEN_NOT_FOUND;
2539         return ERR_INVALID_VALUE;
2540     }
2541     retVal = screenManager_->SetVirtualScreenRefreshRate(id, maxRefreshRate, actualRefreshRate);
2542     return ERR_OK;
2543 }
2544 
SetScreenActiveRect(ScreenId id,const Rect & activeRect,uint32_t & repCode)2545 ErrCode RSRenderServiceConnection::SetScreenActiveRect(ScreenId id, const Rect& activeRect, uint32_t& repCode)
2546 {
2547     if (!screenManager_) {
2548         repCode = StatusCode::SCREEN_NOT_FOUND;
2549         return ERR_INVALID_VALUE;
2550     }
2551     GraphicIRect dstActiveRect {
2552         .x = activeRect.x,
2553         .y = activeRect.y,
2554         .w = activeRect.w,
2555         .h = activeRect.h,
2556     };
2557     if (!mainThread_) {
2558         repCode = StatusCode::INVALID_ARGUMENTS;
2559         return ERR_INVALID_VALUE;
2560     }
2561     auto task = [weakScreenManager = wptr<RSScreenManager>(screenManager_), id, dstActiveRect]() -> void {
2562         sptr<RSScreenManager> screenManager = weakScreenManager.promote();
2563         if (!screenManager) {
2564             return;
2565         }
2566         screenManager->SetScreenActiveRect(id, dstActiveRect);
2567     };
2568     mainThread_->ScheduleTask(task).wait();
2569 
2570     HgmTaskHandleThread::Instance().PostTask([id, dstActiveRect]() {
2571         HgmCore::Instance().NotifyScreenRectFrameRateChange(id, dstActiveRect);
2572     });
2573     repCode = StatusCode::SUCCESS;
2574     return ERR_OK;
2575 }
2576 
SetScreenOffset(ScreenId id,int32_t offsetX,int32_t offsetY)2577 void RSRenderServiceConnection::SetScreenOffset(ScreenId id, int32_t offsetX, int32_t offsetY)
2578 {
2579     if (!screenManager_) {
2580         return;
2581     }
2582     screenManager_->SetScreenOffset(id, offsetX, offsetY);
2583 }
2584 
SetScreenFrameGravity(ScreenId id,int32_t gravity)2585 void RSRenderServiceConnection::SetScreenFrameGravity(ScreenId id, int32_t gravity)
2586 {
2587     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, gravity]() -> void {
2588         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2589         if (connection == nullptr || connection->mainThread_ == nullptr) {
2590             return;
2591         }
2592         auto& context = connection->mainThread_->GetContext();
2593         context.GetNodeMap().TraverseScreenNodes([id, gravity](auto& node) {
2594             if (node && node->GetScreenId() == id) {
2595                 node->GetMutableRenderProperties().SetFrameGravity(static_cast<Gravity>(gravity));
2596             }
2597         });
2598     };
2599     mainThread_->PostTask(task);
2600 }
2601 
RegisterOcclusionChangeCallback(sptr<RSIOcclusionChangeCallback> callback,int32_t & repCode)2602 ErrCode RSRenderServiceConnection::RegisterOcclusionChangeCallback(
2603     sptr<RSIOcclusionChangeCallback> callback, int32_t& repCode)
2604 {
2605     std::lock_guard<std::mutex> lock(mutex_);
2606     if (!mainThread_) {
2607         repCode = StatusCode::INVALID_ARGUMENTS;
2608         return ERR_INVALID_VALUE;
2609     }
2610     if (!callback) {
2611         RS_LOGD("RegisterOcclusionChangeCallback: callback is nullptr");
2612         repCode = StatusCode::INVALID_ARGUMENTS;
2613         return ERR_INVALID_VALUE;
2614     }
2615     mainThread_->RegisterOcclusionChangeCallback(remotePid_, callback);
2616     repCode = StatusCode::SUCCESS;
2617     return ERR_OK;
2618 }
2619 
RegisterSurfaceOcclusionChangeCallback(NodeId id,sptr<RSISurfaceOcclusionChangeCallback> callback,std::vector<float> & partitionPoints)2620 int32_t RSRenderServiceConnection::RegisterSurfaceOcclusionChangeCallback(
2621     NodeId id, sptr<RSISurfaceOcclusionChangeCallback> callback, std::vector<float>& partitionPoints)
2622 {
2623     std::lock_guard<std::mutex> lock(mutex_);
2624     if (!mainThread_) {
2625         return StatusCode::INVALID_ARGUMENTS;
2626     }
2627     if (!callback) {
2628         RS_LOGD("RegisterSurfaceOcclusionChangeCallback: callback is nullptr");
2629         return StatusCode::INVALID_ARGUMENTS;
2630     }
2631     mainThread_->RegisterSurfaceOcclusionChangeCallback(id, remotePid_, callback, partitionPoints);
2632     return StatusCode::SUCCESS;
2633 }
2634 
UnRegisterSurfaceOcclusionChangeCallback(NodeId id)2635 int32_t RSRenderServiceConnection::UnRegisterSurfaceOcclusionChangeCallback(NodeId id)
2636 {
2637     std::lock_guard<std::mutex> lock(mutex_);
2638     if (!mainThread_) {
2639         return StatusCode::INVALID_ARGUMENTS;
2640     }
2641     mainThread_->UnRegisterSurfaceOcclusionChangeCallback(id);
2642     return StatusCode::SUCCESS;
2643 }
2644 
RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)2645 int32_t RSRenderServiceConnection::RegisterHgmConfigChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)
2646 {
2647     std::lock_guard<std::mutex> lock(mutex_);
2648     if (!callback) {
2649         RS_LOGD("RegisterHgmConfigChangeCallback: callback is nullptr");
2650         return StatusCode::INVALID_ARGUMENTS;
2651     }
2652 
2653     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2654         HgmConfigCallbackManager::GetInstance()->RegisterHgmConfigChangeCallback(remotePid_, callback);
2655     });
2656     return StatusCode::SUCCESS;
2657 }
2658 
RegisterHgmRefreshRateModeChangeCallback(sptr<RSIHgmConfigChangeCallback> callback)2659 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateModeChangeCallback(
2660     sptr<RSIHgmConfigChangeCallback> callback)
2661 {
2662     std::lock_guard<std::mutex> lock(mutex_);
2663     if (!callback) {
2664         RS_LOGD("RegisterHgmRefreshRateModeChangeCallback: callback is nullptr");
2665         return StatusCode::INVALID_ARGUMENTS;
2666     }
2667 
2668     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2669         HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateModeChangeCallback(remotePid_, callback);
2670     });
2671     return StatusCode::SUCCESS;
2672 }
2673 
RegisterHgmRefreshRateUpdateCallback(sptr<RSIHgmConfigChangeCallback> callback)2674 int32_t RSRenderServiceConnection::RegisterHgmRefreshRateUpdateCallback(
2675     sptr<RSIHgmConfigChangeCallback> callback)
2676 {
2677     std::lock_guard<std::mutex> lock(mutex_);
2678 
2679     HgmTaskHandleThread::Instance().PostSyncTask([this, &callback] () {
2680         HgmConfigCallbackManager::GetInstance()->RegisterHgmRefreshRateUpdateCallback(remotePid_, callback);
2681     });
2682     return StatusCode::SUCCESS;
2683 }
2684 
RegisterFirstFrameCommitCallback(sptr<RSIFirstFrameCommitCallback> callback)2685 int32_t RSRenderServiceConnection::RegisterFirstFrameCommitCallback(
2686     sptr<RSIFirstFrameCommitCallback> callback)
2687 {
2688     std::lock_guard<std::mutex> lock(mutex_);
2689     RSFirstFrameNotifier::GetInstance().RegisterFirstFrameCommitCallback(remotePid_, callback);
2690     return StatusCode::SUCCESS;
2691 }
2692 
RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)2693 int32_t RSRenderServiceConnection::RegisterFrameRateLinkerExpectedFpsUpdateCallback(int32_t dstPid,
2694     sptr<RSIFrameRateLinkerExpectedFpsUpdateCallback> callback)
2695 {
2696     if (dstPid == 0) {
2697         return StatusCode::INVALID_ARGUMENTS;
2698     }
2699 
2700     HgmTaskHandleThread::Instance().PostTask([remotePid = remotePid_, dstPid, callback] () {
2701         HgmConfigCallbackManager::GetInstance()->RegisterXComponentExpectedFrameRateCallback(
2702             remotePid, dstPid, callback);
2703     });
2704 
2705     return StatusCode::SUCCESS;
2706 }
2707 
SetAppWindowNum(uint32_t num)2708 ErrCode RSRenderServiceConnection::SetAppWindowNum(uint32_t num)
2709 {
2710     if (!mainThread_) {
2711         return ERR_INVALID_VALUE;
2712     }
2713     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), num]() -> void {
2714         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2715         if (!connection || !connection->mainThread_) {
2716             return;
2717         }
2718         connection->mainThread_->SetAppWindowNum(num);
2719     };
2720     mainThread_->PostTask(task);
2721 
2722     return ERR_OK;
2723 }
2724 
SetSystemAnimatedScenes(SystemAnimatedScenes systemAnimatedScenes,bool isRegularAnimation,bool & success)2725 ErrCode RSRenderServiceConnection::SetSystemAnimatedScenes(
2726     SystemAnimatedScenes systemAnimatedScenes, bool isRegularAnimation, bool& success)
2727 {
2728     std::lock_guard<std::mutex> lock(mutex_);
2729     if (!mainThread_) {
2730         success = false;
2731         return ERR_INVALID_VALUE;
2732     }
2733 #ifdef RS_ENABLE_GPU
2734     RSUifirstManager::Instance().OnProcessAnimateScene(systemAnimatedScenes);
2735     success = mainThread_->SetSystemAnimatedScenes(systemAnimatedScenes, isRegularAnimation);
2736     return ERR_OK;
2737 #else
2738     success = false;
2739     return ERR_INVALID_VALUE;
2740 #endif
2741 }
2742 
ShowWatermark(const std::shared_ptr<Media::PixelMap> & watermarkImg,bool isShow)2743 void RSRenderServiceConnection::ShowWatermark(const std::shared_ptr<Media::PixelMap> &watermarkImg, bool isShow)
2744 {
2745     if (!mainThread_) {
2746         return;
2747     }
2748     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), watermarkImg, isShow]() -> void {
2749         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2750         if (connection == nullptr || connection->mainThread_ == nullptr) {
2751             return;
2752         }
2753         connection->mainThread_->ShowWatermark(watermarkImg, isShow);
2754     };
2755     mainThread_->PostTask(task);
2756 }
2757 
ResizeVirtualScreen(ScreenId id,uint32_t width,uint32_t height)2758 int32_t RSRenderServiceConnection::ResizeVirtualScreen(ScreenId id, uint32_t width, uint32_t height)
2759 {
2760     if (!screenManager_) {
2761         return StatusCode::SCREEN_NOT_FOUND;
2762     }
2763     auto renderType = RSUniRenderJudgement::GetUniRenderEnabledType();
2764     if (renderType == UniRenderEnabledType::UNI_RENDER_ENABLED_FOR_ALL) {
2765 #ifdef RS_ENABLE_GPU
2766         return RSHardwareThread::Instance().ScheduleTask(
2767             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
2768                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
2769                 if (connection == nullptr || connection->screenManager_ == nullptr) {
2770                     return RS_CONNECTION_ERROR;
2771                 }
2772                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
2773             }
2774         ).get();
2775 #else
2776         return StatusCode::SCREEN_NOT_FOUND;
2777 #endif
2778     } else if (mainThread_ != nullptr) {
2779         return mainThread_->ScheduleTask(
2780             [weakThis = wptr<RSRenderServiceConnection>(this), id, width, height]() -> int32_t {
2781                 sptr<RSRenderServiceConnection> connection = weakThis.promote();
2782                 if (connection == nullptr || connection->screenManager_ == nullptr) {
2783                     return RS_CONNECTION_ERROR;
2784                 }
2785                 return connection->screenManager_->ResizeVirtualScreen(id, width, height);
2786             }
2787         ).get();
2788     } else {
2789         return StatusCode::SCREEN_NOT_FOUND;
2790     }
2791 }
2792 
ReportJankStats()2793 ErrCode RSRenderServiceConnection::ReportJankStats()
2794 {
2795 #ifdef RS_ENABLE_GPU
2796     auto task = []() -> void { RSJankStats::GetInstance().ReportJankStats(); };
2797     renderThread_.PostTask(task);
2798 #endif
2799     return ERR_OK;
2800 }
2801 
NotifyLightFactorStatus(int32_t lightFactorStatus)2802 ErrCode RSRenderServiceConnection::NotifyLightFactorStatus(int32_t lightFactorStatus)
2803 {
2804     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, lightFactorStatus]() {
2805         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2806         if (frameRateMgr != nullptr) {
2807             frameRateMgr->HandleLightFactorStatus(pid, lightFactorStatus);
2808         }
2809     });
2810     return ERR_OK;
2811 }
2812 
NotifyPackageEvent(uint32_t listSize,const std::vector<std::string> & packageList)2813 void RSRenderServiceConnection::NotifyPackageEvent(uint32_t listSize, const std::vector<std::string>& packageList)
2814 {
2815     if (!mainThread_) {
2816         return;
2817     }
2818     mainThread_->NotifyPackageEvent(packageList);
2819     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, listSize, packageList]() {
2820         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2821         if (frameRateMgr != nullptr) {
2822             frameRateMgr->HandlePackageEvent(pid, packageList);
2823         }
2824     });
2825 }
2826 
NotifyAppStrategyConfigChangeEvent(const std::string & pkgName,uint32_t listSize,const std::vector<std::pair<std::string,std::string>> & newConfig)2827 void RSRenderServiceConnection::NotifyAppStrategyConfigChangeEvent(const std::string& pkgName, uint32_t listSize,
2828     const std::vector<std::pair<std::string, std::string>>& newConfig)
2829 {
2830     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, listSize, pkgName, newConfig] () {
2831         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2832         if (frameRateMgr != nullptr) {
2833             frameRateMgr->HandleAppStrategyConfigEvent(pid, pkgName, newConfig);
2834         }
2835     });
2836 }
2837 
NotifyRefreshRateEvent(const EventInfo & eventInfo)2838 void RSRenderServiceConnection::NotifyRefreshRateEvent(const EventInfo& eventInfo)
2839 {
2840     if (VOTER_SCENE_BLUR == eventInfo.eventName) {
2841         RsFrameBlurPredict::GetInstance().TakeEffectBlurScene(eventInfo);
2842         return;
2843     }
2844 
2845     if (VOTER_SCENE_GPU == eventInfo.eventName) {
2846         RsFrameReport::GetInstance().ReportScbSceneInfo(eventInfo.description, eventInfo.eventStatus);
2847         return;
2848     }
2849     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, eventInfo]() {
2850         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2851         if (frameRateMgr != nullptr) {
2852             frameRateMgr->HandleRefreshRateEvent(pid, eventInfo);
2853         }
2854     });
2855 }
2856 
SetWindowExpectedRefreshRate(const std::unordered_map<uint64_t,EventInfo> & eventInfos)2857 void RSRenderServiceConnection::SetWindowExpectedRefreshRate(
2858     const std::unordered_map<uint64_t, EventInfo>& eventInfos
2859 )
2860 {
2861     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, eventInfos]() {
2862         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2863         if (frameRateMgr != nullptr) {
2864             auto& softVsyncMgr = frameRateMgr->SoftVSyncMgrRef();
2865             softVsyncMgr.SetWindowExpectedRefreshRate(pid, eventInfos);
2866         }
2867     });
2868 }
2869 
SetWindowExpectedRefreshRate(const std::unordered_map<std::string,EventInfo> & eventInfos)2870 void RSRenderServiceConnection::SetWindowExpectedRefreshRate(
2871     const std::unordered_map<std::string, EventInfo>& eventInfos
2872 )
2873 {
2874     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, eventInfos]() {
2875         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2876         if (frameRateMgr != nullptr) {
2877             auto& softVsyncMgr = frameRateMgr->SoftVSyncMgrRef();
2878             softVsyncMgr.SetWindowExpectedRefreshRate(pid, eventInfos);
2879         }
2880     });
2881 }
2882 
NotifySoftVsyncEvent(uint32_t pid,uint32_t rateDiscount)2883 ErrCode RSRenderServiceConnection::NotifySoftVsyncEvent(uint32_t pid, uint32_t rateDiscount)
2884 {
2885     if (!appVSyncDistributor_) {
2886         return ERR_INVALID_VALUE;
2887     }
2888     appVSyncDistributor_->SetQosVSyncRateByPidPublic(pid, rateDiscount, true);
2889     return ERR_OK;
2890 }
2891 
NotifySoftVsyncRateDiscountEvent(uint32_t pid,const std::string & name,uint32_t rateDiscount)2892 bool RSRenderServiceConnection::NotifySoftVsyncRateDiscountEvent(uint32_t pid,
2893     const std::string &name, uint32_t rateDiscount)
2894 {
2895     if (!appVSyncDistributor_) {
2896         return false;
2897     }
2898 
2899     std::vector<uint64_t> linkerIds = appVSyncDistributor_->GetVsyncNameLinkerIds(pid, name);
2900     if (linkerIds.empty()) {
2901         RS_LOGW("NotifySoftVsyncRateDiscountEvent: pid=%{public}d linkerIds is nullptr.",
2902             pid);
2903         return false;
2904     }
2905 
2906     auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2907     if (frameRateMgr == nullptr) {
2908         RS_LOGW("NotifySoftVsyncRateDiscountEvent: pid=%{public}d frameRateMgr is nullptr.",
2909             pid);
2910         return false;
2911     }
2912 
2913     if (!frameRateMgr->SetVsyncRateDiscountLTPO(linkerIds, rateDiscount)) {
2914         RS_LOGW("NotifySoftVsyncRateDiscountEvent: pid=%{public}d Set LTPO fail.",
2915             pid);
2916         return false;
2917     }
2918 
2919     VsyncError ret = appVSyncDistributor_->SetVsyncRateDiscountLTPS(pid, name, rateDiscount);
2920     if (ret != VSYNC_ERROR_OK) {
2921         RS_LOGW("NotifySoftVsyncRateDiscountEvent: pid=%{public}d Set LTPS fail.",
2922             pid);
2923         return false;
2924     }
2925 
2926     return true;
2927 }
2928 
NotifyTouchEvent(int32_t touchStatus,int32_t touchCnt)2929 ErrCode RSRenderServiceConnection::NotifyTouchEvent(int32_t touchStatus, int32_t touchCnt)
2930 {
2931     if (mainThread_ != nullptr) {
2932         mainThread_->HandleTouchEvent(touchStatus, touchCnt);
2933         return ERR_INVALID_VALUE;
2934     }
2935     auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2936     if (frameRateMgr != nullptr) {
2937         frameRateMgr->HandleTouchEvent(remotePid_, touchStatus, touchCnt);
2938     }
2939     return ERR_OK;
2940 }
2941 
NotifyDynamicModeEvent(bool enableDynamicModeEvent)2942 void RSRenderServiceConnection::NotifyDynamicModeEvent(bool enableDynamicModeEvent)
2943 {
2944     HgmTaskHandleThread::Instance().PostTask([enableDynamicModeEvent] () {
2945         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2946         if (frameRateMgr == nullptr) {
2947             RS_LOGW("NotifyDynamicModeEvent: frameRateMgr is nullptr.");
2948             return;
2949         }
2950         frameRateMgr->HandleDynamicModeEvent(enableDynamicModeEvent);
2951     });
2952 }
2953 
NotifyHgmConfigEvent(const std::string & eventName,bool state)2954 ErrCode RSRenderServiceConnection::NotifyHgmConfigEvent(const std::string &eventName, bool state)
2955 {
2956     HgmTaskHandleThread::Instance().PostTask([eventName, state] () {
2957         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
2958         if (frameRateMgr == nullptr) {
2959             RS_LOGW("NotifyHgmConfigEvent: frameRateMgr is nullptr.");
2960             return;
2961         }
2962         RS_LOGI("NotifyHgmConfigEvent: recive notify %{public}s, %{public}d",
2963             eventName.c_str(), state);
2964         if (eventName == "HGMCONFIG_HIGH_TEMP") {
2965             frameRateMgr->HandleScreenExtStrategyChange(state, HGM_CONFIG_TYPE_THERMAL_SUFFIX);
2966         } else if (eventName == "IA_DRAG_SLIDE") {
2967             frameRateMgr->HandleScreenExtStrategyChange(state, HGM_CONFIG_TYPE_DRAGSLIDE_SUFFIX);
2968         } else if (eventName == "IL_THROW_SLIDE") {
2969             frameRateMgr->HandleScreenExtStrategyChange(state, HGM_CONFIG_TYPE_THROWSLIDE_SUFFIX);
2970         }
2971     });
2972     return ERR_OK;
2973 }
2974 
NotifyXComponentExpectedFrameRate(const std::string & id,int32_t expectedFrameRate)2975 ErrCode RSRenderServiceConnection::NotifyXComponentExpectedFrameRate(const std::string& id, int32_t expectedFrameRate)
2976 {
2977     HgmTaskHandleThread::Instance().PostTask([remotePid = remotePid_, id, expectedFrameRate] () {
2978         HgmConfigCallbackManager::GetInstance()->SyncXComponentExpectedFrameRateCallback(
2979             remotePid, id, expectedFrameRate);
2980     });
2981     return ERR_OK;
2982 }
2983 
ReportEventResponse(DataBaseRs info)2984 ErrCode RSRenderServiceConnection::ReportEventResponse(DataBaseRs info)
2985 {
2986     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), info]() -> void {
2987         RSJankStats::GetInstance().SetReportEventResponse(info);
2988         sptr<RSRenderServiceConnection> connection = weakThis.promote();
2989         if (connection == nullptr || connection->mainThread_ == nullptr) {
2990             return;
2991         }
2992         connection->mainThread_->SetForceRsDVsync(info.sceneId);
2993     };
2994 #ifdef RS_ENABLE_GPU
2995     renderThread_.PostTask(task);
2996     RSUifirstManager::Instance().OnProcessEventResponse(info);
2997 #endif
2998     RSUifirstFrameRateControl::Instance().SetAnimationStartInfo(info);
2999     return ERR_OK;
3000 }
3001 
ReportEventComplete(DataBaseRs info)3002 ErrCode RSRenderServiceConnection::ReportEventComplete(DataBaseRs info)
3003 {
3004     auto task = [info]() -> void {
3005         RSJankStats::GetInstance().SetReportEventComplete(info);
3006     };
3007 #ifdef RS_ENABLE_GPU
3008     renderThread_.PostTask(task);
3009     RSUifirstManager::Instance().OnProcessEventComplete(info);
3010 #endif
3011     return ERR_OK;
3012 }
3013 
ReportEventJankFrame(DataBaseRs info)3014 ErrCode RSRenderServiceConnection::ReportEventJankFrame(DataBaseRs info)
3015 {
3016 #ifdef RS_ENABLE_GPU
3017     bool isReportTaskDelayed = renderThread_.IsMainLooping();
3018     auto task = [info, isReportTaskDelayed]() -> void {
3019         RSJankStats::GetInstance().SetReportEventJankFrame(info, isReportTaskDelayed);
3020     };
3021     renderThread_.PostTask(task);
3022 #endif
3023     RSUifirstFrameRateControl::Instance().SetAnimationEndInfo(info);
3024     return ERR_OK;
3025 }
3026 
ReportRsSceneJankStart(AppInfo info)3027 void RSRenderServiceConnection::ReportRsSceneJankStart(AppInfo info)
3028 {
3029     auto task = [info]() -> void {
3030         RSJankStats::GetInstance().SetReportRsSceneJankStart(info);
3031     };
3032     renderThread_.PostTask(task);
3033 }
3034 
ReportRsSceneJankEnd(AppInfo info)3035 void RSRenderServiceConnection::ReportRsSceneJankEnd(AppInfo info)
3036 {
3037     auto task = [info]() -> void {
3038         RSJankStats::GetInstance().SetReportRsSceneJankEnd(info);
3039     };
3040     renderThread_.PostTask(task);
3041 }
3042 
ReportGameStateData(GameStateData info)3043 ErrCode RSRenderServiceConnection::ReportGameStateData(GameStateData info)
3044 {
3045     RS_LOGD("ReportGameStateData = %{public}s, uid = %{public}d, state = %{public}d, "
3046             "pid = %{public}d renderTid = %{public}d ",
3047         info.bundleName.c_str(), info.uid, info.state, info.pid, info.renderTid);
3048 
3049     FrameReport::GetInstance().SetGameScene(info.pid, info.state);
3050     return ERR_OK;
3051 }
3052 
SetHardwareEnabled(NodeId id,bool isEnabled,SelfDrawingNodeType selfDrawingType,bool dynamicHardwareEnable)3053 ErrCode RSRenderServiceConnection::SetHardwareEnabled(NodeId id, bool isEnabled, SelfDrawingNodeType selfDrawingType,
3054     bool dynamicHardwareEnable)
3055 {
3056     if (!mainThread_) {
3057         return ERR_INVALID_VALUE;
3058     }
3059     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, isEnabled, selfDrawingType,
3060         dynamicHardwareEnable]() -> void {
3061         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3062         if (connection == nullptr || connection->mainThread_ == nullptr) {
3063             return;
3064         }
3065         auto& context = connection->mainThread_->GetContext();
3066         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
3067         if (node) {
3068             node->SetHardwareEnabled(isEnabled, selfDrawingType, dynamicHardwareEnable);
3069         }
3070     };
3071     mainThread_->PostTask(task);
3072     return ERR_OK;
3073 }
3074 
SetHidePrivacyContent(NodeId id,bool needHidePrivacyContent,uint32_t & resCode)3075 ErrCode RSRenderServiceConnection::SetHidePrivacyContent(NodeId id, bool needHidePrivacyContent, uint32_t& resCode)
3076 {
3077     if (!mainThread_) {
3078         resCode = static_cast<int32_t>(RSInterfaceErrorCode::UNKNOWN_ERROR);
3079         return ERR_INVALID_VALUE;
3080     }
3081     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), id, needHidePrivacyContent]() -> void {
3082         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3083         if (connection == nullptr || connection->mainThread_ == nullptr) {
3084             return;
3085         }
3086         auto& context = connection->mainThread_->GetContext();
3087         auto node = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(id);
3088         if (node) {
3089             node->SetHidePrivacyContent(needHidePrivacyContent);
3090         }
3091     };
3092     mainThread_->PostTask(task);
3093     resCode = static_cast<uint32_t>(RSInterfaceErrorCode::NO_ERROR);
3094     return ERR_OK;
3095 }
3096 
SetCacheEnabledForRotation(bool isEnabled)3097 ErrCode RSRenderServiceConnection::SetCacheEnabledForRotation(bool isEnabled)
3098 {
3099     if (!mainThread_) {
3100         return ERR_INVALID_VALUE;
3101     }
3102     auto task = [isEnabled]() {
3103         RSSystemProperties::SetCacheEnabledForRotation(isEnabled);
3104     };
3105     mainThread_->PostTask(task);
3106     return ERR_OK;
3107 }
3108 
GetActiveDirtyRegionInfo()3109 std::vector<ActiveDirtyRegionInfo> RSRenderServiceConnection::GetActiveDirtyRegionInfo()
3110 {
3111 #ifdef RS_ENABLE_GPU
3112     const auto& activeDirtyRegionInfos = GpuDirtyRegionCollection::GetInstance().GetActiveDirtyRegionInfo();
3113     GpuDirtyRegionCollection::GetInstance().ResetActiveDirtyRegionInfo();
3114     return activeDirtyRegionInfos;
3115 #else
3116     return {};
3117 #endif
3118 }
3119 
GetGlobalDirtyRegionInfo()3120 GlobalDirtyRegionInfo RSRenderServiceConnection::GetGlobalDirtyRegionInfo()
3121 {
3122 #ifdef RS_ENABLE_GPU
3123     const auto& globalDirtyRegionInfo = GpuDirtyRegionCollection::GetInstance().GetGlobalDirtyRegionInfo();
3124     GpuDirtyRegionCollection::GetInstance().ResetGlobalDirtyRegionInfo();
3125     return globalDirtyRegionInfo;
3126 #else
3127     return {};
3128 #endif
3129 }
3130 
GetLayerComposeInfo()3131 LayerComposeInfo RSRenderServiceConnection::GetLayerComposeInfo()
3132 {
3133     const auto& layerComposeInfo = LayerComposeCollection::GetInstance().GetLayerComposeInfo();
3134     LayerComposeCollection::GetInstance().ResetLayerComposeInfo();
3135     return layerComposeInfo;
3136 }
3137 
GetHwcDisabledReasonInfo()3138 HwcDisabledReasonInfos RSRenderServiceConnection::GetHwcDisabledReasonInfo()
3139 {
3140     return HwcDisabledReasonCollection::GetInstance().GetHwcDisabledReasonInfo();
3141 }
3142 
GetHdrOnDuration(int64_t & hdrOnDuration)3143 ErrCode RSRenderServiceConnection::GetHdrOnDuration(int64_t& hdrOnDuration)
3144 {
3145     auto rsHdrCollection = RsHdrCollection::GetInstance();
3146     if (rsHdrCollection == nullptr) {
3147         return ERR_INVALID_VALUE;
3148     }
3149     hdrOnDuration = rsHdrCollection->GetHdrOnDuration();
3150     rsHdrCollection->ResetHdrOnDuration();
3151     return ERR_OK;
3152 }
3153 
SetVmaCacheStatus(bool flag)3154 ErrCode RSRenderServiceConnection::SetVmaCacheStatus(bool flag)
3155 {
3156 #ifdef RS_ENABLE_GPU
3157     renderThread_.SetVmaCacheStatus(flag);
3158 #endif
3159     return ERR_OK;
3160 }
3161 
3162 #ifdef TP_FEATURE_ENABLE
SetTpFeatureConfig(int32_t feature,const char * config,TpFeatureConfigType tpFeatureConfigType)3163 ErrCode RSRenderServiceConnection::SetTpFeatureConfig(int32_t feature, const char* config,
3164     TpFeatureConfigType tpFeatureConfigType)
3165 {
3166     switch (tpFeatureConfigType) {
3167         case TpFeatureConfigType::DEFAULT_TP_FEATURE: {
3168             if (!TOUCH_SCREEN->IsSetFeatureConfigHandleValid()) {
3169                 RS_LOGW("SetTpFeatureConfig: SetFeatureConfigHandl is nullptr");
3170                 return ERR_INVALID_VALUE;
3171             }
3172             if (TOUCH_SCREEN->SetFeatureConfig(feature, config) < 0) {
3173                 RS_LOGW("SetTpFeatureConfig: SetFeatureConfig failed");
3174                 return ERR_INVALID_VALUE;
3175             }
3176             return ERR_OK;
3177         }
3178         case TpFeatureConfigType::AFT_TP_FEATURE: {
3179             if (!TOUCH_SCREEN->IsSetAftConfigHandleValid()) {
3180                 RS_LOGW("SetTpFeatureConfig: SetAftConfigHandl is nullptr");
3181                 return ERR_INVALID_VALUE;
3182             }
3183             if (TOUCH_SCREEN->SetAftConfig(config) < 0) {
3184                 RS_LOGW("SetTpFeatureConfig: SetAftConfig failed");
3185                 return ERR_INVALID_VALUE;
3186             }
3187             return ERR_OK;
3188         }
3189         default: {
3190             RS_LOGW("SetTpFeatureConfig: unknown TpFeatureConfigType: %" PRIu8"",
3191                 static_cast<uint8_t>(tpFeatureConfigType));
3192             return ERR_INVALID_VALUE;
3193         }
3194     }
3195 }
3196 #endif
3197 
SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)3198 void RSRenderServiceConnection::SetVirtualScreenUsingStatus(bool isVirtualScreenUsingStatus)
3199 {
3200     if (isVirtualScreenUsingStatus) {
3201         EventInfo event = { "VOTER_VIRTUALDISPLAY", ADD_VOTE, OLED_60_HZ, OLED_60_HZ };
3202         NotifyRefreshRateEvent(event);
3203     } else {
3204         EventInfo event = { "VOTER_VIRTUALDISPLAY", REMOVE_VOTE };
3205         NotifyRefreshRateEvent(event);
3206     }
3207     return;
3208 }
3209 
SetCurtainScreenUsingStatus(bool isCurtainScreenOn)3210 ErrCode RSRenderServiceConnection::SetCurtainScreenUsingStatus(bool isCurtainScreenOn)
3211 {
3212     if (!mainThread_) {
3213         return ERR_INVALID_VALUE;
3214     }
3215     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), isCurtainScreenOn]() -> void {
3216         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3217         if (connection == nullptr || connection->mainThread_ == nullptr) {
3218             return;
3219         }
3220         connection->mainThread_->SetCurtainScreenUsingStatus(isCurtainScreenOn);
3221     };
3222     mainThread_->PostTask(task);
3223     return ERR_OK;
3224 }
3225 
DropFrameByPid(const std::vector<int32_t> pidList)3226 ErrCode RSRenderServiceConnection::DropFrameByPid(const std::vector<int32_t> pidList)
3227 {
3228     if (!mainThread_) {
3229         return ERR_INVALID_VALUE;
3230     }
3231     mainThread_->ScheduleTask(
3232         [weakThis = wptr<RSRenderServiceConnection>(this), pidList]() {
3233             // don't use 'this' directly
3234             sptr<RSRenderServiceConnection> connection = weakThis.promote();
3235             if (connection == nullptr || connection->mainThread_ == nullptr) {
3236                 return;
3237             }
3238             connection->mainThread_->AddPidNeedDropFrame(pidList);
3239         }
3240     );
3241     return ERR_OK;
3242 }
3243 
SetGpuCrcDirtyEnabledPidList(const std::vector<int32_t> pidList)3244 ErrCode RSRenderServiceConnection::SetGpuCrcDirtyEnabledPidList(const std::vector<int32_t> pidList)
3245 {
3246     if (!mainThread_ || pidList.size() > PIDLIST_SIZE_MAX) {
3247         return ERR_INVALID_VALUE;
3248     }
3249     mainThread_->ScheduleTask(
3250         [weakThis = wptr<RSRenderServiceConnection>(this), pidList]() {
3251             // don't use 'this' directly
3252             sptr<RSRenderServiceConnection> connection = weakThis.promote();
3253             if (connection == nullptr || connection->mainThread_ == nullptr) {
3254                 return;
3255             }
3256             RSGpuDirtyCollector::GetInstance().SetSelfDrawingGpuDirtyPidList(pidList);
3257         }
3258     );
3259     return ERR_OK;
3260 }
3261 
SetOptimizeCanvasDirtyPidList(const std::vector<int32_t> & pidList)3262 ErrCode RSRenderServiceConnection::SetOptimizeCanvasDirtyPidList(const std::vector<int32_t>& pidList)
3263 {
3264     if (pidList.size() > PIDLIST_SIZE_MAX) {
3265         return ERR_INVALID_VALUE;
3266     }
3267     RSOptimizeCanvasDirtyCollector::GetInstance().SetOptimizeCanvasDirtyPidList(pidList);
3268     return ERR_OK;
3269 }
3270 
RegisterUIExtensionCallback(uint64_t userId,sptr<RSIUIExtensionCallback> callback,bool unobscured)3271 int32_t RSRenderServiceConnection::RegisterUIExtensionCallback(uint64_t userId, sptr<RSIUIExtensionCallback> callback,
3272     bool unobscured)
3273 {
3274     std::lock_guard<std::mutex> lock(mutex_);
3275     if (!mainThread_) {
3276         return StatusCode::INVALID_ARGUMENTS;
3277     }
3278     if (!callback) {
3279         RS_LOGE("RegisterUIExtensionCallback register null callback, failed.");
3280         return StatusCode::INVALID_ARGUMENTS;
3281     }
3282     mainThread_->RegisterUIExtensionCallback(remotePid_, userId, callback, unobscured);
3283     return StatusCode::SUCCESS;
3284 }
3285 
SetVirtualScreenStatus(ScreenId id,VirtualScreenStatus screenStatus,bool & success)3286 ErrCode RSRenderServiceConnection::SetVirtualScreenStatus(ScreenId id,
3287     VirtualScreenStatus screenStatus, bool& success)
3288 {
3289     if (!screenManager_) {
3290         success = false;
3291         return StatusCode::SCREEN_NOT_FOUND;
3292     }
3293     RS_LOGD("SetVirtualScreenStatus ScreenId:%{public}" PRIu64 " screenStatus:%{public}d",
3294         id, screenStatus);
3295     success = screenManager_->SetVirtualScreenStatus(id, screenStatus);
3296     return StatusCode::SUCCESS;
3297 }
3298 
SetAncoForceDoDirect(bool direct,bool & res)3299 ErrCode RSRenderServiceConnection::SetAncoForceDoDirect(bool direct, bool& res)
3300 {
3301     std::lock_guard<std::mutex> lock(mutex_);
3302     if (mainThread_ == nullptr) {
3303         res = false;
3304         return ERR_INVALID_VALUE;
3305     }
3306     mainThread_->SetAncoForceDoDirect(direct);
3307     res = true;
3308     return ERR_OK;
3309 }
3310 
SetFreeMultiWindowStatus(bool enable)3311 void RSRenderServiceConnection::SetFreeMultiWindowStatus(bool enable)
3312 {
3313 #ifdef RS_ENABLE_GPU
3314     if (mainThread_ == nullptr) {
3315         return;
3316     }
3317     auto task = [enable]() -> void {
3318         RSUifirstManager::Instance().SetFreeMultiWindowStatus(enable);
3319     };
3320     mainThread_->PostTask(task);
3321 #endif
3322 }
3323 
RegisterSurfaceBufferCallback(pid_t pid,uint64_t uid,sptr<RSISurfaceBufferCallback> callback)3324 ErrCode RSRenderServiceConnection::RegisterSurfaceBufferCallback(pid_t pid, uint64_t uid,
3325     sptr<RSISurfaceBufferCallback> callback)
3326 {
3327     RSSurfaceBufferCallbackManager::Instance().RegisterSurfaceBufferCallback(pid, uid, callback);
3328     return ERR_OK;
3329 }
3330 
UnregisterSurfaceBufferCallback(pid_t pid,uint64_t uid)3331 ErrCode RSRenderServiceConnection::UnregisterSurfaceBufferCallback(pid_t pid, uint64_t uid)
3332 {
3333     RSSurfaceBufferCallbackManager::Instance().UnregisterSurfaceBufferCallback(pid, uid);
3334     return ERR_OK;
3335 }
3336 
SetLayerTopForHWC(NodeId nodeId,bool isTop,uint32_t zOrder)3337 ErrCode RSRenderServiceConnection::SetLayerTopForHWC(NodeId nodeId, bool isTop, uint32_t zOrder)
3338 {
3339     if (mainThread_ == nullptr) {
3340         return ERR_INVALID_VALUE;
3341     }
3342     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeId, isTop, zOrder]() -> void {
3343         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3344         if (connection == nullptr || connection->mainThread_ == nullptr) {
3345             return;
3346         }
3347         auto& context = connection->mainThread_->GetContext();
3348         auto surfaceNode = context.GetNodeMap().GetRenderNode<RSSurfaceRenderNode>(nodeId);
3349         if (surfaceNode == nullptr) {
3350             return;
3351         }
3352         surfaceNode->SetLayerTop(isTop, false);
3353         surfaceNode->SetTopLayerZOrder(zOrder);
3354         // It can be displayed immediately after layer-top changed.
3355         connection->mainThread_->SetDirtyFlag();
3356         connection->mainThread_->RequestNextVSync();
3357     };
3358     mainThread_->PostTask(task);
3359     return ERR_OK;
3360 }
3361 
SetLayerTop(const std::string & nodeIdStr,bool isTop)3362 ErrCode RSRenderServiceConnection::SetLayerTop(const std::string &nodeIdStr, bool isTop)
3363 {
3364     if (mainThread_ == nullptr) {
3365         return ERR_INVALID_VALUE;
3366     }
3367     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isTop]() -> void {
3368         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3369         if (connection == nullptr || connection->mainThread_ == nullptr) {
3370             return;
3371         }
3372         auto& context = connection->mainThread_->GetContext();
3373         context.GetNodeMap().TraverseSurfaceNodes(
3374             [&nodeIdStr, &isTop](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
3375             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
3376                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
3377                 surfaceNode->SetLayerTop(isTop);
3378                 return;
3379             }
3380         });
3381         // It can be displayed immediately after layer-top changed.
3382         connection->mainThread_->SetDirtyFlag();
3383         connection->mainThread_->RequestNextVSync();
3384     };
3385     mainThread_->PostTask(task);
3386     return ERR_OK;
3387 }
3388 
SetForceRefresh(const std::string & nodeIdStr,bool isForceRefresh)3389 ErrCode RSRenderServiceConnection::SetForceRefresh(const std::string &nodeIdStr, bool isForceRefresh)
3390 {
3391     if (mainThread_ == nullptr) {
3392         return ERR_INVALID_VALUE;
3393     }
3394     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isForceRefresh]() -> void {
3395         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3396         if (connection == nullptr || connection->mainThread_ == nullptr) {
3397             return;
3398         }
3399         auto& context = connection->mainThread_->GetContext();
3400         context.GetNodeMap().TraverseSurfaceNodes(
3401             [&nodeIdStr, &isForceRefresh](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
3402             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
3403                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
3404                 surfaceNode->SetForceRefresh(isForceRefresh);
3405                 return;
3406             }
3407         });
3408     };
3409     mainThread_->PostTask(task);
3410     return ERR_OK;
3411 }
3412 
RegisterTransactionDataCallback(uint64_t token,uint64_t timeStamp,sptr<RSITransactionDataCallback> callback)3413 void RSRenderServiceConnection::RegisterTransactionDataCallback(uint64_t token,
3414     uint64_t timeStamp, sptr<RSITransactionDataCallback> callback)
3415 {
3416     RSTransactionDataCallbackManager::Instance().RegisterTransactionDataCallback(token, timeStamp, callback);
3417 }
3418 
SetColorFollow(const std::string & nodeIdStr,bool isColorFollow)3419 void RSRenderServiceConnection::SetColorFollow(const std::string &nodeIdStr, bool isColorFollow)
3420 {
3421     if (mainThread_ == nullptr) {
3422         return;
3423     }
3424     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeIdStr, isColorFollow]() -> void {
3425         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3426         if (connection == nullptr || connection->mainThread_ == nullptr) {
3427             return;
3428         }
3429         auto& context = connection->mainThread_->GetContext();
3430         context.GetNodeMap().TraverseSurfaceNodes(
3431             [&nodeIdStr, &isColorFollow](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
3432             if ((surfaceNode != nullptr) && (surfaceNode->GetName() == nodeIdStr) &&
3433                 (surfaceNode->GetSurfaceNodeType() == RSSurfaceNodeType::SELF_DRAWING_NODE)) {
3434                 surfaceNode->SetColorFollow(isColorFollow);
3435                 return;
3436             }
3437         });
3438         connection->mainThread_->SetDirtyFlag();
3439         connection->mainThread_->RequestNextVSync();
3440     };
3441     mainThread_->PostTask(task);
3442 }
3443 
NotifyScreenSwitched()3444 ErrCode RSRenderServiceConnection::NotifyScreenSwitched()
3445 {
3446     std::lock_guard<std::mutex> lock(mutex_);
3447     if (!screenManager_) {
3448         RS_LOGE("NotifyScreenSwitched screenManager_ is nullptr");
3449         return ERR_INVALID_VALUE;
3450     }
3451     RS_LOGI("NotifyScreenSwitched SetScreenSwitchStatus true");
3452     RS_TRACE_NAME_FMT("NotifyScreenSwitched");
3453     screenManager_->SetScreenSwitchStatus(true);
3454     return ERR_OK;
3455 }
3456 
SetWindowContainer(NodeId nodeId,bool value)3457 ErrCode RSRenderServiceConnection::SetWindowContainer(NodeId nodeId, bool value)
3458 {
3459     if (!mainThread_) {
3460         return ERR_INVALID_VALUE;
3461     }
3462     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), nodeId, value]() -> void {
3463         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3464         if (connection == nullptr || connection->mainThread_ == nullptr) {
3465             return;
3466         }
3467         auto& nodeMap = connection->mainThread_->GetContext().GetNodeMap();
3468         if (auto node = nodeMap.GetRenderNode<RSCanvasRenderNode>(nodeId)) {
3469             auto displayNodeId = node->GetLogicalDisplayNodeId();
3470             if (auto displayNode = nodeMap.GetRenderNode<RSLogicalDisplayRenderNode>(displayNodeId)) {
3471                 RS_LOGD("SetWindowContainer nodeId: %{public}" PRIu64 ", value: %{public}d",
3472                     nodeId, value);
3473                 displayNode->SetWindowContainer(value ? node : nullptr);
3474             } else {
3475                 RS_LOGE("SetWindowContainer displayNode is nullptr, nodeId: %{public}"
3476                     PRIu64, displayNodeId);
3477             }
3478         } else {
3479             RS_LOGE("SetWindowContainer node is nullptr, nodeId: %{public}" PRIu64,
3480                 nodeId);
3481         }
3482     };
3483     mainThread_->PostTask(task);
3484     return ERR_OK;
3485 }
3486 
RegisterSelfDrawingNodeRectChangeCallback(const RectConstraint & constraint,sptr<RSISelfDrawingNodeRectChangeCallback> callback)3487 int32_t RSRenderServiceConnection::RegisterSelfDrawingNodeRectChangeCallback(
3488     const RectConstraint& constraint, sptr<RSISelfDrawingNodeRectChangeCallback> callback)
3489 {
3490     std::lock_guard<std::mutex> lock(mutex_);
3491 
3492     if (!mainThread_) {
3493         return StatusCode::INVALID_ARGUMENTS;
3494     }
3495     if (!callback) {
3496         RS_LOGE("RegisterSelfDrawingNodeRectChangeCallback register null callback, failed.");
3497         return StatusCode::INVALID_ARGUMENTS;
3498     }
3499 
3500     auto task = [pid = remotePid_, constraint, callback]() {
3501         SelfDrawingNodeMonitor::GetInstance().RegisterRectChangeCallback(pid, constraint, callback);
3502     };
3503     mainThread_->PostTask(task);
3504     return StatusCode::SUCCESS;
3505 }
3506 
UnRegisterSelfDrawingNodeRectChangeCallback()3507 int32_t RSRenderServiceConnection::UnRegisterSelfDrawingNodeRectChangeCallback()
3508 {
3509     std::lock_guard<std::mutex> lock(mutex_);
3510 
3511     if (!mainThread_) {
3512         return StatusCode::INVALID_ARGUMENTS;
3513     }
3514     auto task = [pid = remotePid_]() { SelfDrawingNodeMonitor::GetInstance().UnRegisterRectChangeCallback(pid); };
3515     mainThread_->PostTask(task);
3516     return StatusCode::SUCCESS;
3517 }
3518 
3519 #ifdef RS_ENABLE_OVERLAY_DISPLAY
SetOverlayDisplayMode(int32_t mode)3520 ErrCode RSRenderServiceConnection::SetOverlayDisplayMode(int32_t mode)
3521 {
3522     RS_LOGI("SetOverlayDisplayMode: mode: [%{public}d]", mode);
3523     return RSOverlayDisplayManager::Instance().SetOverlayDisplayMode(mode) == 0 ? ERR_OK : ERR_INVALID_VALUE;
3524 }
3525 #endif
3526 
NotifyPageName(const std::string & packageName,const std::string & pageName,bool isEnter)3527 ErrCode RSRenderServiceConnection::NotifyPageName(const std::string &packageName,
3528     const std::string &pageName, bool isEnter)
3529 {
3530     HgmTaskHandleThread::Instance().PostTask([pid = remotePid_, packageName, pageName, isEnter]() {
3531         auto frameRateMgr = HgmCore::Instance().GetFrameRateMgr();
3532         if (frameRateMgr != nullptr) {
3533             frameRateMgr->NotifyPageName(pid, packageName, pageName, isEnter);
3534         }
3535     });
3536     return StatusCode::SUCCESS;
3537 }
3538 
GetHighContrastTextState()3539 bool RSRenderServiceConnection::GetHighContrastTextState()
3540 {
3541     return RSBaseRenderEngine::IsHighContrastEnabled();
3542 }
3543 
AvcodecVideoStart(uint64_t uniqueId,std::string & surfaceName,uint32_t fps,uint64_t reportTime)3544 ErrCode RSRenderServiceConnection::AvcodecVideoStart(
3545     uint64_t uniqueId, std::string& surfaceName, uint32_t fps, uint64_t reportTime)
3546 {
3547     RSJankStats::GetInstance().AvcodecVideoStart(uniqueId, surfaceName, fps, reportTime);
3548     return ERR_OK;
3549 }
3550 
AvcodecVideoStop(uint64_t uniqueId,std::string & surfaceName,uint32_t fps)3551 ErrCode RSRenderServiceConnection::AvcodecVideoStop(uint64_t uniqueId, std::string& surfaceName, uint32_t fps)
3552 {
3553     RSJankStats::GetInstance().AvcodecVideoStop(uniqueId, surfaceName, fps);
3554     return ERR_OK;
3555 }
3556 
SetBehindWindowFilterEnabled(bool enabled)3557 ErrCode RSRenderServiceConnection::SetBehindWindowFilterEnabled(bool enabled)
3558 {
3559     if (!mainThread_) {
3560         RS_LOGE("SetBehindWindowFilterEnabled mainThread_ is nullptr.");
3561         return ERR_INVALID_VALUE;
3562     }
3563     auto task = [weakThis = wptr<RSRenderServiceConnection>(this), enabled]() -> void {
3564         sptr<RSRenderServiceConnection> connection = weakThis.promote();
3565         if (connection == nullptr || connection->mainThread_ == nullptr) {
3566             return;
3567         }
3568         if (RSSystemProperties::GetBehindWindowFilterEnabled() == enabled) {
3569             return;
3570         }
3571         RSSystemProperties::SetBehindWindowFilterEnabled(enabled);
3572         auto& nodeMap = connection->mainThread_->GetContext().GetNodeMap();
3573         bool needRequestNextVSync = false;
3574         nodeMap.TraverseSurfaceNodes(
3575             [&needRequestNextVSync](const std::shared_ptr<RSSurfaceRenderNode>& surfaceNode) mutable {
3576                 if (!surfaceNode) {
3577                     return;
3578                 }
3579                 if (!surfaceNode->NeedUpdateDrawableBehindWindow()) {
3580                     return;
3581                 }
3582                 surfaceNode->SetContentDirty();
3583                 needRequestNextVSync = true;
3584             });
3585         if (needRequestNextVSync) {
3586             connection->mainThread_->RequestNextVSync();
3587             connection->mainThread_->SetForceUpdateUniRenderFlag(true);
3588         }
3589     };
3590     mainThread_->PostTask(task);
3591     return ERR_OK;
3592 }
3593 
GetBehindWindowFilterEnabled(bool & enabled)3594 ErrCode RSRenderServiceConnection::GetBehindWindowFilterEnabled(bool& enabled)
3595 {
3596     enabled = RSSystemProperties::GetBehindWindowFilterEnabled();
3597     return ERR_OK;
3598 }
3599 
GetPidGpuMemoryInMB(pid_t pid,float & gpuMemInMB)3600 int32_t RSRenderServiceConnection::GetPidGpuMemoryInMB(pid_t pid, float &gpuMemInMB)
3601 {
3602     MemorySnapshotInfo memorySnapshotInfo;
3603 
3604     bool ret = MemorySnapshot::Instance().GetMemorySnapshotInfoByPid(pid, memorySnapshotInfo);
3605     if (!ret) {
3606         RS_LOGD("RSRenderServiceConnection::GetPidGpuMemoryInMB fail to find pid!");
3607         return ERR_INVALID_VALUE;
3608     }
3609     gpuMemInMB = static_cast<float>(memorySnapshotInfo.gpuMemory) / MEM_BYTE_TO_MB;
3610     RS_LOGD("RSRenderServiceConnection::GetPidGpuMemoryInMB called succ");
3611     return ERR_OK;
3612 }
3613 
ProfilerServiceOpenFile(const HrpServiceDirInfo & dirInfo,const std::string & fileName,int32_t flags,int & outFd)3614 RetCodeHrpService RSRenderServiceConnection::ProfilerServiceOpenFile(const HrpServiceDirInfo& dirInfo,
3615     const std::string& fileName, int32_t flags, int& outFd)
3616 {
3617 #ifdef RS_PROFILER_ENABLED
3618     if (fileName.length() == 0 || !HrpServiceValidDirOrFileName(fileName)) {
3619         return RET_HRP_SERVICE_ERR_INVALID_PARAM;
3620     }
3621 
3622     return RSProfiler::HrpServiceOpenFile(dirInfo, fileName, flags, outFd);
3623 #else
3624     outFd = -1;
3625     return RET_HRP_SERVICE_ERR_UNSUPPORTED;
3626 #endif
3627 }
3628 
ProfilerServicePopulateFiles(const HrpServiceDirInfo & dirInfo,uint32_t firstFileIndex,std::vector<HrpServiceFileInfo> & outFiles)3629 RetCodeHrpService RSRenderServiceConnection::ProfilerServicePopulateFiles(const HrpServiceDirInfo& dirInfo,
3630     uint32_t firstFileIndex, std::vector<HrpServiceFileInfo>& outFiles)
3631 {
3632 #ifdef RS_PROFILER_ENABLED
3633     return RSProfiler::HrpServicePopulateFiles(dirInfo, firstFileIndex, outFiles);
3634 #else
3635     outFiles.clear();
3636     return RET_HRP_SERVICE_ERR_UNSUPPORTED;
3637 #endif
3638 }
3639 
ProfilerIsSecureScreen()3640 bool RSRenderServiceConnection::ProfilerIsSecureScreen()
3641 {
3642 #ifdef RS_PROFILER_ENABLED
3643     if (!RSSystemProperties::GetProfilerEnabled()) {
3644         return false;
3645     }
3646     return RSProfiler::IsSecureScreen();
3647 #else
3648     return false;
3649 #endif
3650 }
3651 
ClearUifirstCache(NodeId id)3652 void RSRenderServiceConnection::ClearUifirstCache(NodeId id)
3653 {
3654     if (!mainThread_) {
3655         return;
3656     }
3657     auto task = [id]() -> void {
3658         RSUifirstManager::Instance().AddMarkedClearCacheNode(id);
3659     };
3660     mainThread_->PostTask(task);
3661 }
3662 } // namespace Rosen
3663 } // namespace OHOS
3664