1 /*
2  * Copyright (c) 2022-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 "avsession_manager_impl.h"
17 #include "iservice_registry.h"
18 #include "ipc_skeleton.h"
19 #include "system_ability_definition.h"
20 #include "avsession_log.h"
21 #include "avsession_errors.h"
22 #include "avsession_event_handler.h"
23 #include "session_listener_client.h"
24 #include "avsession_trace.h"
25 #include "avsession_sysevent.h"
26 #include "avsession_utils.h"
27 
28 namespace OHOS::AVSession {
29 
30 sptr<ClientDeathStub> AVSessionManagerImpl::clientDeath_ = nullptr;
31 
AVSessionManagerImpl()32 AVSessionManagerImpl::AVSessionManagerImpl()
33 {
34     SLOGD("constructor");
35 }
36 
DetachCallback()37 extern "C" __attribute__((destructor)) void AVSessionManagerImpl::DetachCallback()
38 {
39     SLOGI("DetachCallback in");
40     if (clientDeath_ != nullptr) {
41         SLOGI("DetachCallback with clientDeath delete");
42         auto ref = clientDeath_.GetRefPtr();
43         clientDeath_ = nullptr;
44         delete ref;
45     }
46 }
47 
GetService()48 sptr<AVSessionServiceProxy> AVSessionManagerImpl::GetService()
49 {
50     std::lock_guard<std::mutex> lockGuard(lock_);
51     if (service_) {
52         return service_;
53     }
54 
55     auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
56     if (mgr == nullptr) {
57         SLOGE("failed to get sa mgr");
58         return nullptr;
59     }
60     auto object = mgr->GetSystemAbility(AVSESSION_SERVICE_ID);
61     if (object == nullptr) {
62         SLOGE("failed to get service");
63         return nullptr;
64     }
65     service_ = iface_cast<AVSessionServiceProxy>(object);
66     if (service_ != nullptr) {
67         serviceDeathRecipient_ = new(std::nothrow) ServiceDeathRecipient([this] { OnServiceDie(); });
68         if (serviceDeathRecipient_ == nullptr) {
69             SLOGE("register ServiceDeathRecipient failed");
70             return nullptr;
71         }
72 
73         sptr<IAVSessionService> serviceBase = service_;
74         serviceBase->AsObject()->AddDeathRecipient(serviceDeathRecipient_);
75 
76         SLOGD("get service success");
77         RegisterClientDeathObserver();
78     }
79     return service_;
80 }
81 
OnServiceDie()82 void AVSessionManagerImpl::OnServiceDie()
83 {
84     SLOGI("enter");
85     auto callback = deathCallback_;
86     {
87         std::lock_guard<std::mutex> lockGuard(lock_);
88         service_.clear();
89         listenerMapByUserId_.clear();
90         deathCallback_ = nullptr;
91     }
92     if (callback) {
93         callback();
94     }
95     HISYSEVENT_RESET;
96     HISYSEVENT_UNREGISTER;
97     std::string cachePath(AVSessionUtils::GetCachePathName());
98     AVSessionUtils::DeleteCacheFiles(cachePath);
99 }
100 
CreateSession(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName)101 std::shared_ptr<AVSession> AVSessionManagerImpl::CreateSession(const std::string& tag, int32_t type,
102                                                                const AppExecFwk::ElementName& elementName)
103 {
104     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::CreateSession");
105     if (tag.empty() || elementName.GetBundleName().empty() || elementName.GetAbilityName().empty()) {
106         SLOGE("param is invalid");
107         return nullptr;
108     }
109     if (type != AVSession::SESSION_TYPE_AUDIO && type != AVSession::SESSION_TYPE_VIDEO
110         && type != AVSession::SESSION_TYPE_VOICE_CALL && type != AVSession::SESSION_TYPE_VIDEO_CALL) {
111         SLOGE("type is invalid");
112         return nullptr;
113     }
114 
115     auto service = GetService();
116     return service ? service->CreateSession(tag, type, elementName) : nullptr;
117 }
118 
CreateSession(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName,std::shared_ptr<AVSession> & session)119 int32_t AVSessionManagerImpl::CreateSession(const std::string& tag, int32_t type,
120                                             const AppExecFwk::ElementName& elementName,
121                                             std::shared_ptr<AVSession>& session)
122 {
123     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::CreateSession with ret");
124     if (tag.empty() || elementName.GetBundleName().empty() || elementName.GetAbilityName().empty()) {
125         SLOGE("param is invalid");
126         return ERR_INVALID_PARAM;
127     }
128     if (type != AVSession::SESSION_TYPE_AUDIO && type != AVSession::SESSION_TYPE_VIDEO
129         && type != AVSession::SESSION_TYPE_VOICE_CALL && type != AVSession::SESSION_TYPE_VIDEO_CALL) {
130         SLOGE("type is invalid");
131         return ERR_INVALID_PARAM;
132     }
133 
134     auto service = GetService();
135     return service ? service->CreateSession(tag, type, elementName, session) : ERR_SERVICE_NOT_EXIST;
136 }
137 
GetAllSessionDescriptors(std::vector<AVSessionDescriptor> & descriptors)138 int32_t AVSessionManagerImpl::GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors)
139 {
140     auto service = GetService();
141     return service ? service->GetAllSessionDescriptors(descriptors) : ERR_SERVICE_NOT_EXIST;
142 }
143 
GetActivatedSessionDescriptors(std::vector<AVSessionDescriptor> & activatedSessions)144 int32_t AVSessionManagerImpl::GetActivatedSessionDescriptors(std::vector<AVSessionDescriptor>& activatedSessions)
145 {
146     std::vector<AVSessionDescriptor> descriptors;
147     int32_t ret = GetAllSessionDescriptors(descriptors);
148     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllSessionDescriptors failed");
149 
150     for (const auto& descriptor : descriptors) {
151         if (descriptor.isActive_) {
152             activatedSessions.push_back(descriptor);
153         }
154     }
155     return ret;
156 }
157 
GetSessionDescriptorsBySessionId(const std::string & sessionId,AVSessionDescriptor & descriptor)158 int32_t AVSessionManagerImpl::GetSessionDescriptorsBySessionId(const std::string& sessionId,
159                                                                AVSessionDescriptor& descriptor)
160 {
161     if (sessionId.empty()) {
162         SLOGE("sessionId is invalid");
163         return ERR_INVALID_PARAM;
164     }
165 
166     auto service = GetService();
167     return service ? service->GetSessionDescriptorsBySessionId(sessionId, descriptor) : ERR_SERVICE_NOT_EXIST;
168 }
169 
GetHistoricalSessionDescriptors(int32_t maxSize,std::vector<AVSessionDescriptor> & descriptors)170 int32_t AVSessionManagerImpl::GetHistoricalSessionDescriptors(int32_t maxSize,
171     std::vector<AVSessionDescriptor>& descriptors)
172 {
173     auto service = GetService();
174     return service ? service->GetHistoricalSessionDescriptors(maxSize, descriptors) : ERR_SERVICE_NOT_EXIST;
175 }
176 
GetHistoricalAVQueueInfos(int32_t maxSize,int32_t maxAppSize,std::vector<AVQueueInfo> & avQueueInfos)177 int32_t AVSessionManagerImpl::GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize,
178     std::vector<AVQueueInfo>& avQueueInfos)
179 {
180     auto service = GetService();
181     return service ? service->GetHistoricalAVQueueInfos(maxSize, maxAppSize, avQueueInfos) : ERR_SERVICE_NOT_EXIST;
182 }
183 
StartAVPlayback(const std::string & bundleName,const std::string & assetId)184 int32_t AVSessionManagerImpl::StartAVPlayback(const std::string& bundleName, const std::string& assetId)
185 {
186     auto service = GetService();
187     return service ? service->StartAVPlayback(bundleName, assetId) : ERR_SERVICE_NOT_EXIST;
188 }
189 
CreateController(const std::string & sessionId,std::shared_ptr<AVSessionController> & controller)190 int32_t AVSessionManagerImpl::CreateController(const std::string& sessionId,
191     std::shared_ptr<AVSessionController>& controller)
192 {
193     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::CreateController");
194     if (sessionId.empty()) {
195         SLOGE("sessionId is invalid");
196         return ERR_INVALID_PARAM;
197     }
198 
199     auto service = GetService();
200     return service ? service->CreateController(sessionId, controller) : ERR_SERVICE_NOT_EXIST;
201 }
202 
203 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
GetAVCastController(const std::string & sessionId,std::shared_ptr<AVCastController> & castController)204 int32_t AVSessionManagerImpl::GetAVCastController(const std::string& sessionId,
205     std::shared_ptr<AVCastController>& castController)
206 {
207     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::GetAVCastController");
208     if (sessionId.empty()) {
209         SLOGE("sessionId is invalid");
210         return ERR_INVALID_PARAM;
211     }
212 
213     auto service = GetService();
214     return service ? service->GetAVCastController(sessionId, castController) : ERR_SERVICE_NOT_EXIST;
215 }
216 #endif
217 
GetSessionListenerClient(const std::shared_ptr<SessionListener> & listener)218 sptr<ISessionListener> AVSessionManagerImpl::GetSessionListenerClient(const std::shared_ptr<SessionListener>& listener)
219 {
220     if (listener == nullptr) {
221         SLOGE("listener recv is nullptr");
222         return nullptr;
223     }
224 
225     sptr<ISessionListener> listenerPtr = new(std::nothrow) SessionListenerClient(listener);
226     if (listenerPtr == nullptr) {
227         SLOGE("listener create is nullptr");
228         return nullptr;
229     }
230     return listenerPtr;
231 }
232 
RegisterSessionListener(const std::shared_ptr<SessionListener> & listener)233 int32_t AVSessionManagerImpl::RegisterSessionListener(const std::shared_ptr<SessionListener>& listener)
234 {
235     auto service = GetService();
236     if (service == nullptr) {
237         return ERR_SERVICE_NOT_EXIST;
238     }
239 
240     std::lock_guard<std::mutex> lockGuard(lock_);
241     sptr<ISessionListener> listenerPtr = GetSessionListenerClient(listener);
242     if (listenerPtr == nullptr) {
243         return ERR_INVALID_PARAM;
244     }
245 
246     int32_t ret = service->RegisterSessionListener(listenerPtr);
247     if (ret <= AVSESSION_SUCCESS) {
248         SLOGE("RegisterSessionListener fail with ret %{public}d", ret);
249         return ret;
250     }
251     SLOGI("RegisterSessionListener for user %{public}d", ret);
252     listenerMapByUserId_[ret] = listenerPtr;
253     return AVSESSION_SUCCESS;
254 }
255 
RegisterSessionListenerForAllUsers(const std::shared_ptr<SessionListener> & listener)256 int32_t AVSessionManagerImpl::RegisterSessionListenerForAllUsers(const std::shared_ptr<SessionListener>& listener)
257 {
258     SLOGI("RegisterSessionListenerForAllUsers in");
259     auto service = GetService();
260     if (service == nullptr) {
261         return ERR_SERVICE_NOT_EXIST;
262     }
263 
264     std::lock_guard<std::mutex> lockGuard(lock_);
265     sptr<ISessionListener> listenerPtr = GetSessionListenerClient(listener);
266     if (listenerPtr == nullptr) {
267         return ERR_INVALID_PARAM;
268     }
269 
270     auto ret = service->RegisterSessionListenerForAllUsers(listenerPtr);
271     if (ret != AVSESSION_SUCCESS) {
272         SLOGE("RegisterSessionListenerForAllUsers fail with ret %{public}d", ret);
273         return ret;
274     }
275     listenerMapByUserId_[userIdForAllUsers_] = listenerPtr;
276     return AVSESSION_SUCCESS;
277 }
278 
RegisterServiceDeathCallback(const DeathCallback & callback)279 int32_t AVSessionManagerImpl::RegisterServiceDeathCallback(const DeathCallback& callback)
280 {
281     deathCallback_ = callback;
282     return AVSESSION_SUCCESS;
283 }
284 
UnregisterServiceDeathCallback()285 int32_t AVSessionManagerImpl::UnregisterServiceDeathCallback()
286 {
287     deathCallback_ = nullptr;
288     return AVSESSION_SUCCESS;
289 }
290 
SendSystemAVKeyEvent(const MMI::KeyEvent & keyEvent)291 int32_t AVSessionManagerImpl::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent)
292 {
293     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::SendSystemAVKeyEvent");
294     if (!keyEvent.IsValid()) {
295         SLOGE("keyEvent is invalid");
296         return ERR_COMMAND_NOT_SUPPORT;
297     }
298 
299     auto service = GetService();
300     return service ? service->SendSystemAVKeyEvent(keyEvent) : ERR_SERVICE_NOT_EXIST;
301 }
302 
SendSystemControlCommand(const AVControlCommand & command)303 int32_t AVSessionManagerImpl::SendSystemControlCommand(const AVControlCommand& command)
304 {
305     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::SendSystemControlCommand");
306     if (!command.IsValid()) {
307         SLOGE("command is invalid");
308         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "INVALID_COMMAND", "CMD", command.GetCommand(),
309             "ERROR_CODE", ERR_INVALID_PARAM, "ERROR_INFO", "avsessionmanagerimpl command is invalid");
310         return ERR_COMMAND_NOT_SUPPORT;
311     }
312 
313     auto service = GetService();
314     if (service == nullptr) {
315         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "GET_SERVICE_ERROR",
316             "ERROR_CODE", ERR_SERVICE_NOT_EXIST, "ERROR_INFO", "mgrimp sendsystemcontrolcommand get service error");
317         return ERR_SERVICE_NOT_EXIST;
318     }
319     return service->SendSystemControlCommand(command);
320 }
321 
CastAudio(const SessionToken & token,const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors)322 int32_t AVSessionManagerImpl::CastAudio(const SessionToken& token,
323                                         const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors)
324 {
325     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::CastAudio");
326     CHECK_AND_RETURN_RET_LOG(descriptors.size() > 0, ERR_INVALID_PARAM, "devices size is zero");
327     auto service = GetService();
328     return service ? service->CastAudio(token, descriptors) : ERR_SERVICE_NOT_EXIST;
329 }
330 
CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors)331 int32_t AVSessionManagerImpl::CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors)
332 {
333     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::CastAudioForAll");
334     CHECK_AND_RETURN_RET_LOG(descriptors.size() > 0, ERR_INVALID_PARAM, "devices size is zero");
335     auto service = GetService();
336     return service ? service->CastAudioForAll(descriptors) : ERR_SERVICE_NOT_EXIST;
337 }
338 
Close(void)339 int32_t AVSessionManagerImpl::Close(void)
340 {
341     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::Close");
342     int32_t ret = ERR_SERVICE_NOT_EXIST;
343     auto service = GetService();
344     if (service) {
345         sptr<IAVSessionService> serviceBase = service;
346         serviceBase->AsObject()->RemoveDeathRecipient(serviceDeathRecipient_);
347         serviceDeathRecipient_ = nullptr;
348         ret = service->Close();
349     }
350     SLOGI("manager impl close with listener clear");
351     listenerMapByUserId_.clear();
352 
353     AVSessionEventHandler::GetInstance().AVSessionRemoveHandler();
354     return ret;
355 }
356 
357 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
StartCastDiscovery(const int32_t castDeviceCapability,std::vector<std::string> drmSchemes)358 int32_t AVSessionManagerImpl::StartCastDiscovery(
359     const int32_t castDeviceCapability, std::vector<std::string> drmSchemes)
360 {
361     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StartCastDiscovery");
362     auto service = GetService();
363     return service ? service->StartCastDiscovery(castDeviceCapability, drmSchemes) : ERR_SERVICE_NOT_EXIST;
364 }
365 
StopCastDiscovery()366 int32_t AVSessionManagerImpl::StopCastDiscovery()
367 {
368     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StopCastDiscovery");
369     auto service = GetService();
370     return service ? service->StopCastDiscovery() : ERR_SERVICE_NOT_EXIST;
371 }
372 
SetDiscoverable(const bool enable)373 int32_t AVSessionManagerImpl::SetDiscoverable(const bool enable)
374 {
375     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::SetDiscoverable");
376     auto service = GetService();
377     return service ? service->SetDiscoverable(enable) : ERR_SERVICE_NOT_EXIST;
378 }
379 
StartDeviceLogging(int32_t fd,uint32_t maxSize)380 int32_t AVSessionManagerImpl::StartDeviceLogging(int32_t fd, uint32_t maxSize)
381 {
382     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StartDeviceLogging");
383     auto service = GetService();
384     return service ? service->StartDeviceLogging(fd, maxSize) : ERR_SERVICE_NOT_EXIST;
385 }
386 
StopDeviceLogging()387 int32_t AVSessionManagerImpl::StopDeviceLogging()
388 {
389     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StopDeviceLogging");
390     auto service = GetService();
391     return service ? service->StopDeviceLogging() : ERR_SERVICE_NOT_EXIST;
392 }
393 
StartCast(const SessionToken & sessionToken,const OutputDeviceInfo & outputDeviceInfo)394 int32_t AVSessionManagerImpl::StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo)
395 {
396     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StartCast");
397     auto service = GetService();
398     return service ? service->StartCast(sessionToken, outputDeviceInfo) : ERR_SERVICE_NOT_EXIST;
399 }
400 
StopCast(const SessionToken & sessionToken)401 int32_t AVSessionManagerImpl::StopCast(const SessionToken& sessionToken)
402 {
403     AVSESSION_TRACE_SYNC_START("AVSessionManagerImpl::StopCast");
404     auto service = GetService();
405     return service ? service->StopCast(sessionToken) : ERR_SERVICE_NOT_EXIST;
406 }
407 #endif
408 
RegisterClientDeathObserver()409 void AVSessionManagerImpl::RegisterClientDeathObserver()
410 {
411     clientDeath_ = new(std::nothrow) ClientDeathStub();
412     if (clientDeath_ == nullptr) {
413         SLOGE("malloc failed");
414         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "MALLOC_FAILED",
415             "ERROR_INFO", "avsession manager impl register client death observer malloc failed");
416         return;
417     }
418 
419     if (service_->RegisterClientDeathObserver(clientDeath_) != AVSESSION_SUCCESS) {
420         SLOGE("register failed");
421         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "REGISTER_FAILED",
422             "ERROR_INFO", "avsession manager impl register client death observer register failed");
423         return;
424     }
425     SLOGI("RegisterClientDeathObserver with ClientDeathStub success");
426 }
427 
ServiceDeathRecipient(const std::function<void ()> & callback)428 ServiceDeathRecipient::ServiceDeathRecipient(const std::function<void()>& callback)
429     : callback_(callback)
430 {
431     SLOGD("construct");
432 }
433 
OnRemoteDied(const wptr<IRemoteObject> & object)434 void ServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object)
435 {
436     if (callback_) {
437         callback_();
438     }
439 }
440 } // namespace OHOS::AVSession
441