• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 "dcamera_sink_controller.h"
17 
18 #include <securec.h>
19 #include <thread>
20 
21 #include "anonymous_string.h"
22 #include "dcamera_channel_sink_impl.h"
23 #include "dcamera_client.h"
24 #include "dcamera_metadata_setting_cmd.h"
25 #include "dcamera_protocol.h"
26 #include "dcamera_utils_tools.h"
27 
28 #include "dcamera_sink_access_control.h"
29 #include "dcamera_sink_controller_channel_listener.h"
30 #include "dcamera_sink_controller_state_callback.h"
31 #include "dcamera_sink_output.h"
32 #include "dcamera_sink_service_ipc.h"
33 
34 #include "distributed_camera_constants.h"
35 #include "distributed_camera_errno.h"
36 #include "distributed_hardware_log.h"
37 #ifdef DEVICE_SECURITY_LEVEL_ENABLE
38 #include "device_security_defines.h"
39 #include "device_security_info.h"
40 #endif
41 #include "ffrt_inner.h"
42 #include "idistributed_camera_source.h"
43 #include "ipc_skeleton.h"
44 #include "dcamera_low_latency.h"
45 #ifdef OS_ACCOUNT_ENABLE
46 #include "ohos_account_kits.h"
47 #include "os_account_manager.h"
48 #endif
49 #include <sys/prctl.h>
50 
51 namespace OHOS {
52 namespace DistributedHardware {
53 const int DEFAULT_DEVICE_SECURITY_LEVEL = -1;
54 const std::string PAGE_SUBTYPE = "camera";
55 
DCameraSinkController(std::shared_ptr<ICameraSinkAccessControl> & accessControl,const sptr<IDCameraSinkCallback> & sinkCallback)56 DCameraSinkController::DCameraSinkController(std::shared_ptr<ICameraSinkAccessControl>& accessControl,
57     const sptr<IDCameraSinkCallback> &sinkCallback)
58     : isInit_(false), sessionState_(DCAMERA_CHANNEL_STATE_DISCONNECTED), accessControl_(accessControl),
59       sinkCallback_(sinkCallback)
60 {
61 }
62 
~DCameraSinkController()63 DCameraSinkController::~DCameraSinkController()
64 {
65     if (isInit_) {
66         UnInit();
67     }
68 }
69 
StartCapture(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos,int32_t sceneMode)70 int32_t DCameraSinkController::StartCapture(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos,
71     int32_t sceneMode)
72 {
73     DHLOGI("StartCapture dhId: %{public}s, mode: %{public}d", GetAnonyString(dhId_).c_str(), sceneMode);
74     std::string accessType = "";
75     CHECK_AND_RETURN_RET_LOG(accessControl_ == nullptr, DCAMERA_BAD_VALUE, "accessControl_ is null.");
76     if ((accessControl_->IsSensitiveSrcAccess(SRC_TYPE)) &&
77         (accessControl_->GetAccessControlType(accessType) == DCAMERA_SAME_ACCOUNT)) {
78         int32_t ret = StartCaptureInner(captureInfos);
79         if (ret == DCAMERA_OK) {
80             accessControl_->NotifySensitiveSrc(SRC_TYPE);
81         }
82         return ret;
83     } else {
84         std::shared_ptr<std::string> param = std::make_shared<std::string>("");
85         std::shared_ptr<std::vector<std::shared_ptr<DCameraCaptureInfo>>> infos =
86             std::make_shared<std::vector<std::shared_ptr<DCameraCaptureInfo>>>(captureInfos);
87         CHECK_AND_RETURN_RET_LOG(sinkCotrEventHandler_ == nullptr, DCAMERA_BAD_VALUE, "sinkCotrEventHandler_ is null.");
88         AppExecFwk::InnerEvent::Pointer triggerEvent =
89                 AppExecFwk::InnerEvent::Get(EVENT_FRAME_TRIGGER, param, 0);
90         AppExecFwk::InnerEvent::Pointer authorizationEvent =
91                 AppExecFwk::InnerEvent::Get(EVENT_AUTHORIZATION, infos, 0);
92         sinkCotrEventHandler_->SendEvent(triggerEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
93         sinkCotrEventHandler_->SendEvent(authorizationEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
94     }
95     return DCAMERA_OK;
96 }
97 
StopCapture()98 int32_t DCameraSinkController::StopCapture()
99 {
100     DHLOGI("StopCapture dhId: %{public}s", GetAnonyString(dhId_).c_str());
101     std::lock_guard<std::mutex> autoLock(captureLock_);
102     if (operator_ == nullptr) {
103         return DCAMERA_BAD_VALUE;
104     }
105     int32_t ret = operator_->StopCapture();
106     if (ret != DCAMERA_OK) {
107         DHLOGE("client stop capture failed, dhId: %{public}s, ret: %{public}d",
108                GetAnonyString(dhId_).c_str(), ret);
109         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("operator stop capture failed."));
110         return ret;
111     }
112     if (output_ == nullptr) {
113         return DCAMERA_BAD_VALUE;
114     }
115     ret = output_->StopCapture();
116     if (ret != DCAMERA_OK) {
117         DHLOGE("output stop capture failed, dhId: %{public}s, ret: %{public}d",
118                GetAnonyString(dhId_).c_str(), ret);
119         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("output stop capture failed"));
120         return ret;
121     }
122     DHLOGI("StopCapture %{public}s success", GetAnonyString(dhId_).c_str());
123     return DCAMERA_OK;
124 }
125 
ChannelNeg(std::shared_ptr<DCameraChannelInfo> & info)126 int32_t DCameraSinkController::ChannelNeg(std::shared_ptr<DCameraChannelInfo>& info)
127 {
128     DHLOGI("ChannelNeg dhId: %{public}s", GetAnonyString(dhId_).c_str());
129     int32_t ret = output_->OpenChannel(info);
130     if (ret != DCAMERA_OK) {
131         DHLOGE("channel negotiate failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
132         return ret;
133     }
134 
135     DHLOGI("ChannelNeg %{public}s success", GetAnonyString(dhId_).c_str());
136     return DCAMERA_OK;
137 }
138 
DCameraNotify(std::shared_ptr<DCameraEvent> & events)139 int32_t DCameraSinkController::DCameraNotify(std::shared_ptr<DCameraEvent>& events)
140 {
141     DHLOGI("DCameraNotify dhId: %{public}s", GetAnonyString(dhId_).c_str());
142     CHECK_AND_RETURN_RET_LOG(srcDevId_.empty(), DCAMERA_BAD_VALUE, "source deviceId is empty");
143 
144     DCameraEventCmd eventCmd;
145     std::string jsonStr = "";
146     eventCmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE;
147     eventCmd.dhId_ = dhId_;
148     eventCmd.command_ = DCAMERA_PROTOCOL_CMD_STATE_NOTIFY;
149     eventCmd.value_ = events;
150     int32_t ret = eventCmd.Marshal(jsonStr);
151     if (ret != DCAMERA_OK) {
152         DHLOGE("DCameraEventCmd marshal failed, dhId: %{public}s, ret: %{public}d",
153                GetAnonyString(dhId_).c_str(), ret);
154         return ret;
155     }
156 
157     if (ManageSelectChannel::GetInstance().GetSinkConnect()) {
158         std::shared_ptr<DataBuffer> buffer = std::make_shared<DataBuffer>(jsonStr.length() + 1);
159         ret = memcpy_s(buffer->Data(), buffer->Capacity(),
160             reinterpret_cast<uint8_t *>(const_cast<char *>(jsonStr.c_str())), jsonStr.length());
161         CHECK_AND_RETURN_RET_LOG(ret != EOK, DCAMERA_BAD_VALUE, "DCameraNotify memcpy_s failed, ret: %{public}d", ret);
162         ret = channel_->SendData(buffer);
163         if (ret != DCAMERA_OK) {
164             DHLOGE("DCameraNotify channel send data failed, dhId: %{public}s ret: %{public}d",
165                 GetAnonyString(dhId_).c_str(), ret);
166             return DCAMERA_BAD_VALUE;
167         }
168     } else {
169         std::string sinkDevId;
170         ret = GetLocalDeviceNetworkId(sinkDevId);
171         if (ret != DCAMERA_OK) {
172             DHLOGE("GetLocalDeviceNetworkId failed, devId: %{public}s, dhId: %{public}s, ret: %{public}d",
173                 GetAnonyString(sinkDevId).c_str(), GetAnonyString(dhId_).c_str(), ret);
174             return ret;
175         }
176 
177         sptr<IDistributedCameraSource> sourceSA = DCameraSinkServiceIpc::GetInstance().GetSourceRemoteCamSrv(srcDevId_);
178         CHECK_AND_RETURN_RET_LOG(sourceSA == nullptr, DCAMERA_BAD_VALUE, "sourceSA is null");
179         ret = sourceSA->DCameraNotify(sinkDevId, dhId_, jsonStr);
180         if (ret != DCAMERA_OK) {
181             DHLOGE("SourceSA notify failed, srcId: %{public}s, sinkId: %{public}s, dhId: %{public}s, ret: %{public}d",
182                 GetAnonyString(srcDevId_).c_str(), GetAnonyString(sinkDevId).c_str(),
183                 GetAnonyString(dhId_).c_str(), ret);
184             return ret;
185         }
186     }
187 
188     DHLOGI("DCameraNotify %{public}s success", GetAnonyString(dhId_).c_str());
189     return DCAMERA_OK;
190 }
191 
UpdateSettings(std::vector<std::shared_ptr<DCameraSettings>> & settings)192 int32_t DCameraSinkController::UpdateSettings(std::vector<std::shared_ptr<DCameraSettings>>& settings)
193 {
194     DHLOGI("UpdateSettings dhId: %{public}s", GetAnonyString(dhId_).c_str());
195     int32_t ret = operator_->UpdateSettings(settings);
196     if (ret != DCAMERA_OK) {
197         DHLOGE("UpdateSettings failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
198         return ret;
199     }
200 
201     DHLOGI("UpdateSettings %{public}s success", GetAnonyString(dhId_).c_str());
202     return DCAMERA_OK;
203 }
204 
GetCameraInfo(std::shared_ptr<DCameraInfo> & camInfo)205 int32_t DCameraSinkController::GetCameraInfo(std::shared_ptr<DCameraInfo>& camInfo)
206 {
207     DHLOGI("GetCameraInfo dhId: %{public}s, session state: %{public}d", GetAnonyString(dhId_).c_str(), sessionState_);
208     camInfo->state_ = sessionState_;
209     return DCAMERA_OK;
210 }
211 
CheckSensitive()212 int32_t DCameraSinkController::CheckSensitive()
213 {
214     if (sinkCallback_ == nullptr) {
215         DHLOGE("check sensitive callback is nullptr.");
216         return DCAMERA_BAD_VALUE;
217     }
218     int32_t ret = sinkCallback_->OnNotifyResourceInfo(ResourceEventType::EVENT_TYPE_QUERY_RESOURCE, PAGE_SUBTYPE,
219         srcDevId_, isSensitive_, isSameAccount_);
220     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, ret, "Query resource failed, ret: %{public}d", ret);
221     DHLOGI("OpenChannel isSensitive: %{public}d, isSameAccout: %{public}d", isSensitive_, isSameAccount_);
222     if (isSensitive_ && !isSameAccount_) {
223         DHLOGE("Privacy resource must be logged in with the same account.");
224         return DCAMERA_BAD_VALUE;
225     }
226 
227     if (isCheckSecLevel_) {
228         std::string sinkDevId;
229         ret = GetLocalDeviceNetworkId(sinkDevId);
230         CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, ret, "GetLocalDeviceNetworkId failed, ret: %{public}d", ret);
231         if (isSensitive_ && !CheckDeviceSecurityLevel(srcDevId_, sinkDevId)) {
232             DHLOGE("Check device security level failed!");
233             return DCAMERA_BAD_VALUE;
234         }
235     }
236     return DCAMERA_OK;
237 }
238 
OpenChannel(std::shared_ptr<DCameraOpenInfo> & openInfo)239 int32_t DCameraSinkController::OpenChannel(std::shared_ptr<DCameraOpenInfo>& openInfo)
240 {
241     DHLOGI("DCameraSinkController OpenChannel Start, dhId: %{public}s", GetAnonyString(dhId_).c_str());
242     ManageSelectChannel::GetInstance().SetSinkConnect(false);
243     if (sessionState_ != DCAMERA_CHANNEL_STATE_DISCONNECTED) {
244         DHLOGE("wrong state, dhId: %{public}s, sessionState: %{public}d", GetAnonyString(dhId_).c_str(), sessionState_);
245         return DCAMERA_WRONG_STATE;
246     }
247     srcDevId_ = openInfo->sourceDevId_;
248     std::vector<DCameraIndex> indexs;
249     indexs.push_back(DCameraIndex(srcDevId_, dhId_));
250     auto controller = std::shared_ptr<DCameraSinkController>(shared_from_this());
251     std::shared_ptr<ICameraChannelListener> listener =
252         std::make_shared<DCameraSinkControllerChannelListener>(controller);
253     int32_t ret = channel_->CreateSession(indexs, SESSION_FLAG, DCAMERA_SESSION_MODE_CTRL, listener);
254     if (ret != DCAMERA_OK) {
255         DHLOGE("channel create session failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
256         return ret;
257     }
258     DHLOGI("DCameraSinkController OpenChannel %{public}s success", GetAnonyString(dhId_).c_str());
259     return DCAMERA_OK;
260 }
261 
PullUpPage()262 int32_t DCameraSinkController::PullUpPage()
263 {
264     if (isSensitive_) {
265         bool isSensitive = false;
266         bool isSameAccout = false;
267         int32_t ret = sinkCallback_->OnNotifyResourceInfo(ResourceEventType::EVENT_TYPE_PULL_UP_PAGE, PAGE_SUBTYPE,
268             srcDevId_, isSensitive, isSameAccout);
269         if (ret != DCAMERA_OK) {
270             DHLOGE("pull up page failed, ret %{public}d", ret);
271             return ret;
272         }
273         isPageStatus_.store(true);
274     }
275     return DCAMERA_OK;
276 }
277 
CloseChannel()278 int32_t DCameraSinkController::CloseChannel()
279 {
280     DHLOGI("DCameraSinkController CloseChannel Start, dhId: %{public}s", GetAnonyString(dhId_).c_str());
281     std::lock_guard<std::mutex> autoLock(channelLock_);
282     if (!ManageSelectChannel::GetInstance().GetSinkConnect()) {
283         DCameraSinkServiceIpc::GetInstance().DeleteSourceRemoteCamSrv(srcDevId_);
284         if (channel_ == nullptr) {
285             DHLOGE("DCameraSinkController CloseChannel channel_ is nullptr");
286             return DCAMERA_BAD_VALUE;
287         }
288         int32_t ret = channel_->ReleaseSession();
289         if (ret != DCAMERA_OK) {
290             DHLOGE("DCameraSinkController release channel failed, dhId: %{public}s, ret: %{public}d",
291                 GetAnonyString(dhId_).c_str(), ret);
292         }
293 
294         ret = output_->CloseChannel();
295         if (ret != DCAMERA_OK) {
296             DHLOGE("DCameraSinkController CloseChannel failed, dhId: %{public}s, ret: %{public}d",
297                 GetAnonyString(dhId_).c_str(), ret);
298         }
299     }
300     srcDevId_.clear();
301     sessionState_ = DCAMERA_CHANNEL_STATE_DISCONNECTED;
302     isPageStatus_.store(false);
303     DHLOGI("DCameraSinkController CloseChannel %{public}s success", GetAnonyString(dhId_).c_str());
304     return DCAMERA_OK;
305 }
306 
Init(std::vector<DCameraIndex> & indexs)307 int32_t DCameraSinkController::Init(std::vector<DCameraIndex>& indexs)
308 {
309     DHLOGI("DCameraSinkController Init");
310     dhId_ = indexs[0].dhId_;
311     operator_ = std::make_shared<DCameraClient>(dhId_);
312     output_ = std::make_shared<DCameraSinkOutput>(dhId_, operator_);
313     int32_t ret = output_->Init();
314     if (ret != DCAMERA_OK) {
315         DHLOGE("output init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
316         return ret;
317     }
318 
319     auto controller = std::shared_ptr<DCameraSinkController>(shared_from_this());
320     std::shared_ptr<StateCallback> stateCallback = std::make_shared<DCameraSinkControllerStateCallback>(controller);
321     operator_->SetStateCallback(stateCallback);
322     ret = operator_->Init();
323     if (ret != DCAMERA_OK) {
324         DHLOGE("operator init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
325         return ret;
326     }
327 
328     channel_ = std::make_shared<DCameraChannelSinkImpl>();
329     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create(true);
330     sinkCotrEventHandler_ =
331         std::make_shared<DCameraSinkController::DCameraSinkContrEventHandler>(runner, shared_from_this());
332     isInit_ = true;
333     initCallback_ = std::make_shared<DeviceInitCallback>();
334     ManageSelectChannel::GetInstance().SetSinkConnect(true);
335     ret = CreateCtrlSession();
336     if (ret != DCAMERA_OK) {
337         DHLOGE("CreateCtrlSessiion init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
338         return ret;
339     }
340     std::shared_ptr<DCameraChannelInfo> info = std::make_shared<DCameraChannelInfo>();
341     info->sourceDevId_ = "";
342     DCameraChannelDetail continueChInfo(CONTINUE_SESSION_FLAG, CONTINUOUS_FRAME);
343     DCameraChannelDetail snapShotChInfo(SNAP_SHOT_SESSION_FLAG, SNAPSHOT_FRAME);
344     info->detail_.push_back(continueChInfo);
345     info->detail_.push_back(snapShotChInfo);
346     ret = ChannelNeg(info);
347     if (ret != DCAMERA_OK) {
348         DHLOGE("ChannelNeg init failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
349         return ret;
350     }
351     DHLOGI("DCameraSinkController Init %{public}s success", GetAnonyString(dhId_).c_str());
352     return DCAMERA_OK;
353 }
354 
CreateCtrlSession()355 int32_t DCameraSinkController::CreateCtrlSession()
356 {
357     DHLOGI("DCameraSinkController CreateCtrlSessiion Start, dhId: %{public}s", GetAnonyString(dhId_).c_str());
358     if (sessionState_ != DCAMERA_CHANNEL_STATE_DISCONNECTED) {
359         DHLOGE("wrong state, dhId: %{public}s, sessionState: %{public}d", GetAnonyString(dhId_).c_str(), sessionState_);
360         return DCAMERA_WRONG_STATE;
361     }
362     DCameraLowLatency::GetInstance().EnableLowLatency();
363     std::vector<DCameraIndex> indexs;
364     indexs.push_back(DCameraIndex("", dhId_));
365     auto controller = std::shared_ptr<DCameraSinkController>(shared_from_this());
366     std::shared_ptr<ICameraChannelListener> listener =
367         std::make_shared<DCameraSinkControllerChannelListener>(controller);
368     int32_t ret = channel_->CreateSession(indexs, SESSION_FLAG, DCAMERA_SESSION_MODE_CTRL, listener);
369     if (ret != DCAMERA_OK) {
370         DHLOGE("channel create session failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
371         return ret;
372     }
373     DHLOGI("DCameraSinkController CreateCtrlSessiion %{public}s success", GetAnonyString(dhId_).c_str());
374     return DCAMERA_OK;
375 }
376 
UnInit()377 int32_t DCameraSinkController::UnInit()
378 {
379     DHLOGI("DCameraSinkController UnInit dhId: %{public}s", GetAnonyString(dhId_).c_str());
380     std::lock_guard<std::mutex> autoLock(autoLock_);
381     int32_t ret = StopCapture();
382     if (ret != DCAMERA_OK) {
383         DHLOGE("DCameraSinkController UnInit %{public}s stop capture failed, ret: %{public}d",
384             GetAnonyString(dhId_).c_str(), ret);
385     }
386 
387     ret = CloseChannel();
388     if (ret != DCAMERA_OK) {
389         DHLOGE("DCameraSinkController UnInit %{public}s close channel failed, ret: %{public}d",
390             GetAnonyString(dhId_).c_str(), ret);
391     }
392 
393     DCameraLowLatency::GetInstance().DisableLowLatency();
394     if (ManageSelectChannel::GetInstance().GetSinkConnect()) {
395         if (channel_ != nullptr) {
396             ret = channel_->ReleaseSession();
397             if (ret != DCAMERA_OK) {
398                 DHLOGE("DCameraSinkController release channel failed, dhId: %{public}s, ret: %{public}d",
399                     GetAnonyString(dhId_).c_str(), ret);
400             }
401         }
402         if (output_ != nullptr) {
403             ret = output_->CloseChannel();
404             if (ret != DCAMERA_OK) {
405                 DHLOGE("DCameraSinkController output CloseChannel failed, dhId: %{public}s, ret: %{public}d",
406                     GetAnonyString(dhId_).c_str(), ret);
407             }
408         }
409     }
410 
411     if (output_ != nullptr) {
412         ret = output_->UnInit();
413         if (ret != DCAMERA_OK) {
414             DHLOGE("DCameraSinkController release output failed, dhId: %{public}s, ret: %{public}d",
415                    GetAnonyString(dhId_).c_str(), ret);
416         }
417     }
418 
419     if (operator_ != nullptr) {
420         ret = operator_->UnInit();
421         if (ret != DCAMERA_OK) {
422             DHLOGE("DCameraSinkController release operator failed, dhId: %{public}s, ret: %{public}d",
423                    GetAnonyString(dhId_).c_str(), ret);
424         }
425     }
426 
427     isInit_ = false;
428     ManageSelectChannel::GetInstance().SetSinkConnect(false);
429     DHLOGI("DCameraSinkController UnInit %{public}s success", GetAnonyString(dhId_).c_str());
430     return DCAMERA_OK;
431 }
432 
DCameraSinkContrEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner,std::shared_ptr<DCameraSinkController> sinkContrPtr)433 DCameraSinkController::DCameraSinkContrEventHandler::DCameraSinkContrEventHandler(
434     const std::shared_ptr<AppExecFwk::EventRunner> &runner, std::shared_ptr<DCameraSinkController> sinkContrPtr)
435     : AppExecFwk::EventHandler(runner), sinkContrWPtr_(sinkContrPtr)
436 {
437     DHLOGI("Ctor DCameraSinkContrEventHandler.");
438 }
439 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)440 void DCameraSinkController::DCameraSinkContrEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
441 {
442     CHECK_AND_RETURN_LOG(event == nullptr, "event is nullptr.");
443     uint32_t eventId = event->GetInnerEventId();
444     auto sinkContr = sinkContrWPtr_.lock();
445     if (sinkContr == nullptr) {
446         DHLOGE("Can not get strong self ptr");
447         return;
448     }
449     switch (eventId) {
450         case EVENT_FRAME_TRIGGER:
451             sinkContr->ProcessFrameTrigger(event);
452             break;
453         case EVENT_AUTHORIZATION:
454             sinkContr->ProcessPostAuthorization(event);
455             break;
456         default:
457             DHLOGE("event is undefined, id is %d", eventId);
458             break;
459     }
460 }
461 
ProcessFrameTrigger(const AppExecFwk::InnerEvent::Pointer & event)462 void DCameraSinkController::ProcessFrameTrigger(const AppExecFwk::InnerEvent::Pointer &event)
463 {
464     DHLOGD("Receive frame trigger event then start process data in sink controller.");
465     std::shared_ptr<std::string> param = event->GetSharedObject<std::string>();
466     CHECK_AND_RETURN_LOG(param == nullptr, "ProcessFrameTrigger get param is null");
467     accessControl_->TriggerFrame(*param);
468 }
469 
ProcessPostAuthorization(const AppExecFwk::InnerEvent::Pointer & event)470 void DCameraSinkController::ProcessPostAuthorization(const AppExecFwk::InnerEvent::Pointer &event)
471 {
472     DHLOGD("Receive post authorization event then start process data in sink controller.");
473     std::shared_ptr<std::vector<std::shared_ptr<DCameraCaptureInfo>>> captureInfos =
474         event->GetSharedObject<std::vector<std::shared_ptr<DCameraCaptureInfo>>>();
475     CHECK_AND_RETURN_LOG(captureInfos == nullptr, "ProcessPostAuthorization get captureInfos is null");
476     PostAuthorization(*captureInfos);
477 }
478 
OnStateChanged(std::shared_ptr<DCameraEvent> & event)479 void DCameraSinkController::OnStateChanged(std::shared_ptr<DCameraEvent>& event)
480 {
481     DHLOGI("DCameraSinkController::OnStateChanged dhId: %{public}s, result: %{public}d",
482            GetAnonyString(dhId_).c_str(), event->eventResult_);
483     if (event->eventResult_ == DCAMERA_EVENT_DEVICE_PREEMPT) {
484         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_PREEMPT, std::string("camera device preempted"));
485     } else {
486         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("camera error"));
487     }
488 }
489 
OnMetadataResult(std::vector<std::shared_ptr<DCameraSettings>> & settings)490 void DCameraSinkController::OnMetadataResult(std::vector<std::shared_ptr<DCameraSettings>>& settings)
491 {
492     DHLOGI("DCameraSinkController::OnMetadataResult dhId: %{public}s", GetAnonyString(dhId_).c_str());
493     if (settings.empty()) {
494         DHLOGE("camera settings is empty");
495         return;
496     }
497     DCameraMetadataSettingCmd cmd;
498     cmd.type_ = DCAMERA_PROTOCOL_TYPE_MESSAGE;
499     cmd.dhId_ = dhId_;
500     cmd.command_ = DCAMERA_PROTOCOL_CMD_METADATA_RESULT;
501     cmd.value_.assign(settings.begin(), settings.end());
502     std::string jsonStr;
503     int32_t ret = cmd.Marshal(jsonStr);
504     if (ret != DCAMERA_OK) {
505         DHLOGE("Marshal metadata settings failed, dhId: %{public}s ret: %{public}d",
506             GetAnonyString(dhId_).c_str(), ret);
507         return;
508     }
509     std::shared_ptr<DataBuffer> buffer = std::make_shared<DataBuffer>(jsonStr.length() + 1);
510     ret = memcpy_s(buffer->Data(), buffer->Capacity(), reinterpret_cast<uint8_t *>(const_cast<char *>(jsonStr.c_str())),
511         jsonStr.length());
512     if (ret != EOK) {
513         DHLOGE("memcpy_s failed, dhId: %{public}s ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
514         return;
515     }
516     ret = channel_->SendData(buffer);
517     if (ret != DCAMERA_OK) {
518         DHLOGE("channel send data failed, dhId: %{public}s ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
519         return;
520     }
521     DHLOGI("DCameraSinkController::OnMetadataResult dhId: %{public}s success", GetAnonyString(dhId_).c_str());
522 }
523 
OnSessionState(int32_t state,std::string networkId)524 void DCameraSinkController::OnSessionState(int32_t state, std::string networkId)
525 {
526     DHLOGI("DCameraSinkController::OnSessionState dhId: %{public}s, state: %{public}d",
527         GetAnonyString(dhId_).c_str(), state);
528     sessionState_ = state;
529     switch (state) {
530         case DCAMERA_CHANNEL_STATE_CONNECTING:
531             DHLOGI("channel is connecting");
532             break;
533         case DCAMERA_CHANNEL_STATE_CONNECTED: {
534             DHLOGI("channel is connected");
535             if (!ManageSelectChannel::GetInstance().GetSinkConnect()) {
536                 break;
537             }
538             srcDevId_ = networkId;
539             if (operator_ == nullptr) {
540                 DHLOGE("operator_ is nullptr");
541                 break;
542             }
543             break;
544         }
545         case DCAMERA_CHANNEL_STATE_DISCONNECTED:
546             DHLOGI("channel is disconnected");
547             ffrt::submit([this]() {
548                 DHLOGI("DCameraSinkController::OnSessionState %{public}s new thread session state: %{public}d",
549                     GetAnonyString(dhId_).c_str(), sessionState_);
550                 prctl(PR_SET_NAME, CHANNEL_DISCONNECTED.c_str());
551                 std::lock_guard<std::mutex> autoLock(autoLock_);
552                 int32_t ret = CloseChannel();
553                 if (ret != DCAMERA_OK) {
554                     DHLOGE("session state: %{public}d, %{public}s close channel failed, ret: %{public}d",
555                         sessionState_, GetAnonyString(dhId_).c_str(), ret);
556                 }
557                 ret = StopCapture();
558                 if (ret != DCAMERA_OK) {
559                     DHLOGE("session state: %{public}d, %{public}s stop capture failed, ret: %{public}d",
560                         sessionState_, GetAnonyString(dhId_).c_str(), ret);
561                 }
562             });
563             break;
564         default:
565             DHLOGE("unknown session state");
566             break;
567     }
568 }
569 
OnSessionError(int32_t eventType,int32_t eventReason,std::string detail)570 void DCameraSinkController::OnSessionError(int32_t eventType, int32_t eventReason, std::string detail)
571 {
572     DHLOGI("DCameraSinkController::OnSessionError dhId: %{public}s, eventType: %{public}d, eventReason: %{public}d,"
573         " detail: %{public}s", GetAnonyString(dhId_).c_str(), eventType, eventReason, detail.c_str());
574 }
575 
OnDataReceived(std::vector<std::shared_ptr<DataBuffer>> & buffers)576 void DCameraSinkController::OnDataReceived(std::vector<std::shared_ptr<DataBuffer>>& buffers)
577 {
578     DHLOGI("OnReceivedData %{public}s control channel receive data", GetAnonyString(dhId_).c_str());
579     for (auto& buffer : buffers) {
580         if (buffer->Size() <= 0 || buffer->Size() > DATABUFF_MAX_SIZE) {
581             DHLOGI("buffer is invalid");
582             return;
583         }
584         HandleReceivedData(buffer);
585     }
586 }
587 
PostAuthorization(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos)588 void DCameraSinkController::PostAuthorization(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos)
589 {
590     DHLOGI("DCameraSinkController::PostAuthorization dhId: %{public}s", GetAnonyString(dhId_).c_str());
591     int32_t ret = StartCaptureInner(captureInfos);
592     if (ret == DCAMERA_OK) {
593         accessControl_->NotifySensitiveSrc(SRC_TYPE);
594     }
595 }
596 
StartCaptureInner(std::vector<std::shared_ptr<DCameraCaptureInfo>> & captureInfos)597 int32_t DCameraSinkController::StartCaptureInner(std::vector<std::shared_ptr<DCameraCaptureInfo>>& captureInfos)
598 {
599     DHLOGI("StartCaptureInner dhId: %{public}s", GetAnonyString(dhId_).c_str());
600     std::lock_guard<std::mutex> autoLock(captureLock_);
601     int32_t ret = output_->StartCapture(captureInfos);
602     if (ret != DCAMERA_OK) {
603         DHLOGE("output start capture failed, dhId: %{public}s, ret: %{public}d", GetAnonyString(dhId_).c_str(), ret);
604         DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_ERROR, std::string("output start capture failed"));
605         return ret;
606     }
607     PropertyCarrier carrier;
608     ret = output_->GetProperty(SURFACE, carrier);
609     if (ret != DCAMERA_OK) {
610         DHLOGD("StartCaptureInner: get property fail.");
611         return DCAMERA_BAD_VALUE;
612     }
613     ret = operator_->StartCapture(captureInfos, carrier.surface_, sceneMode_);
614     if (ret != DCAMERA_OK) {
615         DHLOGE("camera client start capture failed, dhId: %{public}s, ret: %{public}d",
616             GetAnonyString(dhId_).c_str(), ret);
617         if (ret == DCAMERA_ALLOC_ERROR) {
618             DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_NO_PERMISSION,
619                                std::string("operator start capture permission denial."));
620         } else if (ret == DCAMERA_DEVICE_BUSY) {
621             DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_DEVICE_IN_USE,
622                                std::string("operator start capture in used."));
623         }
624         return ret;
625     }
626 
627     DCameraNotifyInner(DCAMERA_MESSAGE, DCAMERA_EVENT_CAMERA_SUCCESS, START_CAPTURE_SUCC);
628     DHLOGI("DCameraSinkController::StartCaptureInner %{public}s success", GetAnonyString(dhId_).c_str());
629     return DCAMERA_OK;
630 }
631 
DCameraNotifyInner(int32_t type,int32_t result,std::string reason)632 int32_t DCameraSinkController::DCameraNotifyInner(int32_t type, int32_t result, std::string reason)
633 {
634     std::shared_ptr<DCameraEvent> event = std::make_shared<DCameraEvent>();
635     event->eventType_ = type;
636     event->eventResult_ = result;
637     event->eventContent_ = reason;
638     return DCameraNotify(event);
639 }
640 
HandleReceivedData(std::shared_ptr<DataBuffer> & dataBuffer)641 int32_t DCameraSinkController::HandleReceivedData(std::shared_ptr<DataBuffer>& dataBuffer)
642 {
643     DHLOGI("DCameraSinkController::HandleReceivedData dhId: %{public}s", GetAnonyString(dhId_).c_str());
644     uint8_t *data = dataBuffer->Data();
645     std::string jsonStr(reinterpret_cast<const char *>(data), dataBuffer->Capacity());
646     cJSON *rootValue = cJSON_Parse(jsonStr.c_str());
647     if (rootValue == nullptr) {
648         return DCAMERA_BAD_VALUE;
649     }
650     cJSON *comvalue = cJSON_GetObjectItemCaseSensitive(rootValue, "Command");
651     if (comvalue == nullptr || !cJSON_IsString(comvalue) || (comvalue->valuestring == nullptr)) {
652         cJSON_Delete(rootValue);
653         DHLOGE("parse command failed");
654         return DCAMERA_BAD_VALUE;
655     }
656     std::string command = std::string(comvalue->valuestring);
657     cJSON_Delete(rootValue);
658     if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_CAPTURE) == 0)) {
659         DCameraCaptureInfoCmd captureInfoCmd;
660         int32_t ret = captureInfoCmd.Unmarshal(jsonStr);
661         if (ret != DCAMERA_OK) {
662             DHLOGE("Capture Info Unmarshal failed, dhId: %{public}s ret: %{public}d",
663                 GetAnonyString(dhId_).c_str(), ret);
664             return ret;
665         }
666         sceneMode_ = captureInfoCmd.sceneMode_;
667         userId_ = captureInfoCmd.userId_;
668         tokenId_ = captureInfoCmd.tokenId_;
669         accountId_ = captureInfoCmd.accountId_;
670         if (!CheckAclRight()) {
671             DHLOGE("ACL check failed.");
672             return DCAMERA_BAD_VALUE;
673         }
674         return StartCapture(captureInfoCmd.value_, sceneMode_);
675     } else if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_UPDATE_METADATA) == 0)) {
676         DCameraMetadataSettingCmd metadataSettingCmd;
677         int32_t ret = metadataSettingCmd.Unmarshal(jsonStr);
678         if (ret != DCAMERA_OK) {
679             DHLOGE("Metadata Setting Unmarshal failed, dhId: %{public}s ret: %{public}d",
680                    GetAnonyString(dhId_).c_str(), ret);
681             return ret;
682         }
683         return UpdateSettings(metadataSettingCmd.value_);
684     } else if ((!command.empty()) && (command.compare(DCAMERA_PROTOCOL_CMD_STOP_CAPTURE) == 0)) {
685         return StopCapture();
686     }
687     return DCAMERA_BAD_VALUE;
688 }
689 
CheckAclRight()690 bool DCameraSinkController::CheckAclRight()
691 {
692     if (userId_ == -1) {
693         DHLOGI("Acl check version compatibility processing.");
694         return true;
695     }
696     std::string sinkDevId;
697     int32_t ret = GetLocalDeviceNetworkId(sinkDevId);
698     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, false, "GetLocalDeviceNetworkId failed, ret: %{public}d", ret);
699     int32_t userId = -1;
700     std::string accountId = "";
701 #ifdef OS_ACCOUNT_ENABLE
702     std::vector<int32_t> ids;
703     ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
704     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK || ids.empty(), false,
705         "Get userId from active os accountIds fail, ret: %{public}d", ret);
706     userId = ids[0];
707 
708     AccountSA::OhosAccountInfo osAccountInfo;
709     ret = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(osAccountInfo);
710     CHECK_AND_RETURN_RET_LOG(ret != DCAMERA_OK, false,
711         "Get accountId from ohos account info fail, ret: %{public}d", ret);
712     accountId = osAccountInfo.uid_;
713 #endif
714     ret = DeviceManager::GetInstance().InitDeviceManager(DCAMERA_PKG_NAME, initCallback_);
715     if (ret != DCAMERA_OK) {
716         DHLOGE("InitDeviceManager failed ret = %{public}d", ret);
717         return false;
718     }
719     DmAccessCaller dmSrcCaller = {
720         .accountId = accountId_,
721         .pkgName = DCAMERA_PKG_NAME,
722         .networkId = srcDevId_,
723         .userId = userId_,
724         .tokenId = tokenId_,
725     };
726     DmAccessCallee dmDstCallee = {
727         .accountId = accountId,
728         .networkId = sinkDevId,
729         .pkgName = DCAMERA_PKG_NAME,
730         .userId = userId,
731         .tokenId = sinkTokenId_,
732     };
733     DHLOGI("CheckAclRight srcDevId: %{public}s, accountId: %{public}s, sinkDevId: %{public}s",
734         GetAnonyString(srcDevId_).c_str(), GetAnonyString(accountId).c_str(), GetAnonyString(sinkDevId).c_str());
735     return DeviceManager::GetInstance().CheckSinkAccessControl(dmSrcCaller, dmDstCallee);
736 }
737 
PauseDistributedHardware(const std::string & networkId)738 int32_t DCameraSinkController::PauseDistributedHardware(const std::string &networkId)
739 {
740     DHLOGI("Pause distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
741     if (networkId.empty()) {
742         DHLOGE("networkId is empty");
743         return DCAMERA_BAD_VALUE;
744     }
745     if (operator_ == nullptr) {
746         DHLOGE("operator_ is nullptr.");
747         return DCAMERA_BAD_VALUE;
748     }
749     int32_t ret = operator_->PauseCapture();
750     if (ret != DCAMERA_OK) {
751         DHLOGE("Pause distributed hardware failed, dhId: %{public}s, ret: %{public}d",
752             GetAnonyString(dhId_).c_str(), ret);
753     }
754     return ret;
755 }
756 
ResumeDistributedHardware(const std::string & networkId)757 int32_t DCameraSinkController::ResumeDistributedHardware(const std::string &networkId)
758 {
759     DHLOGI("Resume distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
760     if (networkId.empty()) {
761         DHLOGE("networkId is empty");
762         return DCAMERA_BAD_VALUE;
763     }
764     if (operator_ == nullptr) {
765         DHLOGE("operator_ is nullptr.");
766         return DCAMERA_BAD_VALUE;
767     }
768     int32_t ret = operator_->ResumeCapture();
769     if (ret != DCAMERA_OK) {
770         DHLOGE("Resume distributed hardware failed, dhId: %{public}s, ret: %{public}d",
771             GetAnonyString(dhId_).c_str(), ret);
772     }
773     return ret;
774 }
775 
StopDistributedHardware(const std::string & networkId)776 int32_t DCameraSinkController::StopDistributedHardware(const std::string &networkId)
777 {
778     DHLOGI("Stop distributed hardware dhId: %{public}s", GetAnonyString(dhId_).c_str());
779     if (networkId.empty()) {
780         DHLOGE("networkId is empty");
781         return DCAMERA_BAD_VALUE;
782     }
783 
784     isPageStatus_.store(false);
785     return DCameraNotifyInner(DCAMERA_SINK_STOP, DCAMERA_EVENT_SINK_STOP, std::string("sink stop dcamera business"));
786 }
787 
CheckDeviceSecurityLevel(const std::string & srcDeviceId,const std::string & dstDeviceId)788 bool DCameraSinkController::CheckDeviceSecurityLevel(const std::string &srcDeviceId, const std::string &dstDeviceId)
789 {
790     DHLOGD("CheckDeviceSecurityLevel srcDeviceId %{public}s, dstDeviceId %{public}s.",
791         GetAnonyString(srcDeviceId).c_str(), GetAnonyString(dstDeviceId).c_str());
792     std::string srcUdid = GetUdidByNetworkId(srcDeviceId);
793     if (srcUdid.empty()) {
794         DHLOGE("src udid is empty");
795         return false;
796     }
797     std::string dstUdid = GetUdidByNetworkId(dstDeviceId);
798     if (dstUdid.empty()) {
799         DHLOGE("dst udid is empty");
800         return false;
801     }
802     DHLOGD("CheckDeviceSecurityLevel srcUdid %{public}s, dstUdid %{public}s.",
803         GetAnonyString(srcUdid).c_str(), GetAnonyString(dstUdid).c_str());
804     int32_t srcDeviceSecurityLevel = GetDeviceSecurityLevel(srcUdid);
805     int32_t dstDeviceSecurityLevel = GetDeviceSecurityLevel(dstUdid);
806     DHLOGI("srcDeviceSecurityLevel is %{public}d, dstDeviceSecurityLevel is %{public}d.",
807         srcDeviceSecurityLevel, dstDeviceSecurityLevel);
808     if (srcDeviceSecurityLevel == DEFAULT_DEVICE_SECURITY_LEVEL ||
809         srcDeviceSecurityLevel < dstDeviceSecurityLevel) {
810         DHLOGE("The device security of source device is lower.");
811         return false;
812     }
813     return true;
814 }
815 
GetDeviceSecurityLevel(const std::string & udid)816 int32_t DCameraSinkController::GetDeviceSecurityLevel(const std::string &udid)
817 {
818     #ifdef DEVICE_SECURITY_LEVEL_ENABLE
819     DeviceIdentify devIdentify;
820     devIdentify.length = DEVICE_ID_MAX_LEN;
821     int32_t ret = memcpy_s(devIdentify.identity, DEVICE_ID_MAX_LEN, udid.c_str(), DEVICE_ID_MAX_LEN);
822     if (ret != 0) {
823         DHLOGE("str copy failed %{public}d", ret);
824         return DEFAULT_DEVICE_SECURITY_LEVEL;
825     }
826     DeviceSecurityInfo *info = nullptr;
827     ret = RequestDeviceSecurityInfo(&devIdentify, nullptr, &info);
828     if (ret != SUCCESS) {
829         DHLOGE("Request device security info failed %{public}d", ret);
830         FreeDeviceSecurityInfo(info);
831         info = nullptr;
832         return DEFAULT_DEVICE_SECURITY_LEVEL;
833     }
834     #endif
835     int32_t level = 0;
836     #ifdef DEVICE_SECURITY_LEVEL_ENABLE
837     ret = GetDeviceSecurityLevelValue(info, &level);
838     DHLOGD("Get device security level, level is %{public}d", level);
839     FreeDeviceSecurityInfo(info);
840     info = nullptr;
841     if (ret != SUCCESS) {
842         DHLOGE("Get device security level failed %{public}d", ret);
843         return DEFAULT_DEVICE_SECURITY_LEVEL;
844     }
845     #endif
846     return level;
847 }
848 
GetUdidByNetworkId(const std::string & networkId)849 std::string DCameraSinkController::GetUdidByNetworkId(const std::string &networkId)
850 {
851     if (networkId.empty()) {
852         DHLOGE("networkId is empty!");
853         return "";
854     }
855     int32_t ret = DeviceManager::GetInstance().InitDeviceManager(DCAMERA_PKG_NAME, initCallback_);
856     if (ret != DCAMERA_OK) {
857         DHLOGE("InitDeviceManager failed ret = %{public}d", ret);
858         return "";
859     }
860     std::string udid = "";
861     ret = DeviceManager::GetInstance().GetUdidByNetworkId(DCAMERA_PKG_NAME, networkId, udid);
862     if (ret != DCAMERA_OK) {
863         DHLOGE("GetUdidByNetworkId failed ret = %{public}d", ret);
864         return "";
865     }
866     return udid;
867 }
868 
SetTokenId(uint64_t token)869 void DCameraSinkController::SetTokenId(uint64_t token)
870 {
871     sinkTokenId_ = token;
872 }
873 
OnRemoteDied()874 void DeviceInitCallback::OnRemoteDied()
875 {
876     DHLOGI("DeviceInitCallback OnRemoteDied");
877 }
878 } // namespace DistributedHardware
879 } // namespace OHOS
880